Tonner Mààn Tonner Mààn - 5 months ago 17
MySQL Question

How to save a mysql query result table into a php array?

I need to save the result table of a query into an array var in php so I can use it for later queries freely,

You may ask why don't I just make everything in one query, I prefer it this way as it will be clearer to arrange things in my script as it would be very complicated to make that mixed query, but of course if I can't find a solution I'll try to do it but lets seek the easier way first.

Here is what I've done so far:

$pdo = Database::connect();
$sql = "SELECT * FROM image where ImageFolder not like 'Profile%' order by ImgTimeStamp asc LIMIT 10";
$i = 0; //to use later in loops.
$imgdata = array();
foreach ($pdo->query($sql) as $row)
$imgdata[][] = array("ImageID"=>$row['ImageID'],"ImageFolder"=>$row['ImageFolder'],"ImageExtention"=>$row['ImageExtention'],"ImageDescription"=>$row['ImageDescription'],"UserID"=>$row['UserID'],"RatesNumber"=>$row['RatesNumber'],"SumRates"=>$row['SumRates'],"ImgTimeStamp"=>$row['ImgTimeStamp'],"Tags"=>$row['Tags']);

Yet when I try to use that array with this code
it gives me these errors:
Notice: Undefined index: UserID in C:\wamp\www\DrawingArt\Accueil.php on line 34

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: no parameters were bound' in C:\wamp\www\DrawingArt\Accueil.php on line 34

PDOException: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound in C:\wamp\www\DrawingArt\Accueil.php on line 34


When you don't specify the key in assigning to an array, PHP assigns one for you, based on the next available highest integer key. Each time you add square brackets [] to the array in assignment, you're pushing to another dimension in that array.

So this code...

$arr[][] = ["UserID" => "foo"];


Gives you...

  array(1) {
    array(1) {
      string(3) "foo"

Notice to access the value "foo" here you need $arr[0][0]["UserID"] and not $arr[0]["UserID"]. If you want the latter and not the former then use $arr[] = ["UserID" => "foo"] instead when you assign the values in your loop.