-3

I´m trying to convert this foreach to all looops for printing the array from the msyql consult in screen.

$con = mysqli_connect("localhost", "root" ,"" ,"base");
if($con->connect_error)
{
    die($con->mysqli_connect_error());
}

print_r ("conexion exitosa");

$sql = "SELECT code, name, grade FROM teachers WHERE status = 1 ";
$result = $con->query($sql); 
$row = mysqli_fetch_array($result); //array

**foreach ($result as $row) //array as value
    {
        print_r($row); //print value
    }**
?> ```

  • @ASDFGerte Right. I removed that tag; thanks. – Funk Forty Niner Nov 27 '19 at 17:15
  • Could you explain a little bit more what you would like to do? Your code could work only if the result has more than 1 row. What loop do you need? – Dharman Nov 27 '19 at 17:37
  • I want to print the variable $row in every possible loop, but only the array. – Carlos Mtz Nov 27 '19 at 17:44
  • Do you mean to say that you want to loop on the result multiple times or just that you would like to see how the same code can be written using other loops? – Dharman Nov 27 '19 at 17:45
  • If you have a problem with explaining in English what you want, could you use translate.google.com to translate it into English? We need better description. – Dharman Nov 27 '19 at 17:54

1 Answers1

0

You need one more step in order to convert the MySQL returned row(s) into an array.

while ($row = mysqli_fetch_assoc($result)) { var_dump($row); }

You can also echo each element from a row. For example:

echo $row['myfield']; inside your while loop.

Paulo Hgo
  • 834
  • 1
  • 11
  • 26
  • Could you explain how does this help and what problem does it solve? – Dharman Nov 27 '19 at 17:38
  • My understanding is that he'd like to be able to easily manipulate the results. It could be a for or while loop. The solution proposed here is basic and simple but it solves his problem to the extent I understood it. `mysqli_query()` will return an object that is harder to manipulate. Hence, the extra step? Not sure I understood your question. – Paulo Hgo Nov 27 '19 at 17:43
  • That's the thing, your loop is doing exactly the same things as the loop in question. – Dharman Nov 27 '19 at 17:45
  • 1
    Yeah, I noticed now that he is converting it to an array before looping, hadn't seen that before. So I can't answer your question to be honest with you but you are correct, this solution doesn't do anything else other than an example on how to echo individual values from the row. – Paulo Hgo Nov 27 '19 at 17:51
  • Yeah this is only for academic porpuses, I don´t want to do anything especial with it. I´m having trouble with the "for" loop, can anyone help me here? ty. – Carlos Mtz Nov 27 '19 at 18:09
  • @CarlosMtz What do you mean you have trouble with `for` loop? Show us what you tried. – Dharman Nov 27 '19 at 18:12