Search code examples
phpmysqlarraysreview

Why does this code only show 1 ID


I am having a problem. I know I am using deprecated MySQL, but I am working on a website for school and security is not necessary(as long as it works). I am trying to get all the Id's from a table called Reviews. This should be stored in a array. For some reason it only shows the first one. How to get all of them stored in 1 array? This is my code which is not working:

$sql1 = "SELECT Klanten_id FROM Reviews";
$res1 = mysql_query($sql1);
$r = mysql_fetch_assoc($res1)['Klanten_id'];

Solution

  • 1.Don't use outdated mysql_* library.Turn to mysqli_* or PDO.

    2.mysql_fetch_assoc: Fetch a result row as an associative array. So you need to apply loop to get all data

    Like below:-

    $ids = array(); //created an array
    while ($row = mysql_fetch_assoc($res1)) {
        $ids[] = $row['Klanten_id']; // assign each id to the array
    }
    print_r($ids);// print array
    

    3.To start working on mysqli/PDO check basic example here:- mysqli/PDO example