Hi there,

I am trying to populate a page with multiple rows from a mySQL database.

To grab the data, I am using:

for ($i=1; $i < 5; $i++) {

        $query = 'SELECT * FROM table WHERE column = ?';
        $statement = $mySQL_con->prepare($query);

        try {
            $statement->execute(array($i));
        }

        catch (PDOException $error) {
            echo 'Sorry, we failed to load this page: ' . $error->getMessage();
        }

        $row = $statement->fetch();
        $results[] = $row;
}

That creates a mutil-dimensional array. However, when I try to access that data things go a bit weird.

For example,print_r($results[2][name]); should output the name from the third row I grabbed using the mySQL query (third because PRIMARY KEY > 0). Instead, I get the error message: "Use of undefined constant blog_id - assumed 'blog_id'"

The strange thing is that directly underneath that error message, I get the name value from the array I wanted.

Have you executed this query in the mysql client or phpmyadmin

I have created the connection through PHP:

//mySQL Credentials
$mySQL_username = 'username';
$mySQL_password = 'password';
$mySQL_host = 'localhost';
$mySQL_database = 'database';

//Attempt mySQL Connection
    try {
        $mySQL_con = new PDO('mysql:host='.$mySQL_host.'; dbname='.$mySQL_database.'', $mySQL_username, $mySQL_password);
        }

    catch (PDOException $error)
        {
        echo "Unable to connect: " . $error->getMessage();
        }

The query itself works, since the data from the array is complete when displayed with the print_r function.

Hello James,
PHP associative arrays (that are the one returned by PDO fetch PDO::FETCH_ASSOC @see http://php.net/manual/en/pdostatement.fetch.php ) need quotes if the key is string . e.g. $results[2]["blog_id"] . If you don't have quotes PHP will search for the constant with name blog_id , that this is your case here (you didn't define @see http://php.net/manual/en/function.define.php so you have that message). That doesn't happen only for arrays resulted by PDO fetch but for any PHP array.

Except for that I am not quite sure I understand what you are trying to do , e.g. why you have a query inside a for loop. Maybe there is a reason for that but I guess that you want actually to do something different from what you wrote. If you want you can explain further what you are trying to do to fix that also.

Hey Jkon,

Thanks for that - that was my mistake, I forgot to put the quotations round the string. Sorted now.

You're right about the for loop. At the time, I was thinking that was the only way to grab multiple rows of data from mySQL, because when I tried with a query that returned multiple rows for some reason the array was only storing the information from the first row.

I realise now it was because I needed to push the data from each row into the array. So I can ditch the for loop and instead use $results[] = $row;

Thanks for your advice!