skip to Main Content

I am using PHP and MySQL (mysqli) in XAMPP, I have a drop down, and the user must choose one, then a query is used to find the id of the value that has been chosen but it does not work. I have already done this three more times and it worked but this one doesn’t.

    $sql = "SELECT foo_id FROM foo_table
WHERE foo_name = 'bar';";
    $res = $conn->query($sql);
    for ($i = 0; $i < 500; $i++) {
        $row = $res->fetch_assoc();
        echo $row[row["foo_id"]]
    }

The problem is that fetch_assoc does not return anything even though the $res variable returns true.

Edit: I forgot to mention that running the query in phpmyadmin returns results normally.

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution, the problem is that the real database used greek characters in the records and the database had to be set to utf8-bin, after doing so, it worked.


  2. I am not sure why you are iterating over 500 times? this doesn’t make sense.

    Best practice to retrieve the data from DB is

    $sql  = "SELECT foo_id FROM foo_table
              WHERE foo_name = 'bar'";
    $res = $conn->query($sql);
    if ($res->num_rows > 0) {
       // output data of each row
       while($row = $res->fetch_assoc()) {
          echo $row["foo_id"];
       }
     }
    

    OR

     $foo_id = ''
     if ($res->num_rows > 0) {
       // output data of each row
       while($row = $res->fetch_assoc()) {
          $foo_id = $row["foo_id"];
       }
     }
     for ($i = 0; $i < 500; $i++) {
        echo $foo_id;
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search