Calling a PHP function gives only one line from the query result

I use a PHP file to store all the functions that I need in my project. One of them is the following:

function recuperar_opcion_plato_linea ($plato_id) { /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'xxxx'; /*** mysql password ***/ $password = 'xxxxxxx'; try { $dbh = new PDO("mysql:host=$hostname;dbname=xxx", $username, $password); /*** echo a message saying we have connected ***/ /*** The SQL SELECT statement ***/ $sql = "SELECT * FROM tb_opciones_linea_comanda WHERE id_linea = '".$plato_id."'"; foreach ($dbh->query($sql) as $row) { return $row['id_opcion']; } /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } } 

In another file, I call this function, but it gives only the first line of the query result, and there are at least 3 lines.

And this is part of the PHP code to call the recuperar_opcion_plato_linea function:

 <?php do { ?> <p><?php echo $row_Recordset1['cantidad_pedido']." "; ?> <?php echo recuperar_nombre_plato($row_Recordset1['plato_pedido'])." "."$ ".$row_Recordset1['precio_linea']." ".$moneda?></p> <p><?php $opcion_selecionada = recuperar_opcion_plato_linea ($row_Recordset1['id_random']); echo recuperar_nombre_opcion($opcion_selecionada) ?></p> <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?> 

How can I get all rows from a query?

+4
source share
3 answers

When you say return $row['id_opcion']; which immediately ends the foreach loop and returns a function. Instead, you just need to return $dbh->query($sql)

Also, if all you need from your query is a single id_opcion column, you should use SELECT id_opcion instead of SELECT *

For example, let's say you still wanted to use a loop, you would do it like this:

 // create a blank results array $results = array(); foreach ($dbh->query($sql) as $row) { // add the row to the array $results[] = $row['id_opcion']; } // return the finished results array return $results; 
+4
source

Replace

 $sql = "SELECT * FROM tb_opciones_linea_comanda WHERE id_linea = '".$plato_id."'"; foreach ($dbh->query($sql) as $row) { return $row['id_opcion']; } 

FROM

 $sql = "SELECT * FROM tb_opciones_linea_comanda WHERE id_linea = '".$plato_id."'"; $return = array(); foreach ($dbh->query($sql) as $row) { $return[] = $row['id_opcion']; } return $return; 

and

 echo recuperar_nombre_opcion($opcion_selecionada) 

FROM

 foreach ($opcion_selecionadas AS $opcion_selecionada) {echo '<br />' . recuperar_nombre_opcion($opcion_selecionada);} 
+1
source
 $return = array(); while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)) == true) { array_push($return, $row_Recordset1); // or $return[] = $row_Recordset1; } return $return; 
-one
source

All Articles