Jeremiah Thompson
Jeremiah Thompson

Reputation: 11

Problems running a mySQL query with PDO

This code below is not returning any value into my $result variable. The database connection is good. But it doesn't appear to be returning any values for the $result variable.

I do have data in the player table and there is a player_id value of 1 and 2 in said table.

The print out of the echos when run is this. when passing the integers 1 and 2 into the function.

Database connected

SELECT * 
FROM player 
WHERE player_id = 1

Results not an array.

Database connected

SELECT * 
FROM player 
WHERE player_id = 2

Results not an array.

function displayName($player_id)
{
    // setting database variables
    $dsn = 'mysql:dbname=dbName;host=localhost';
    $username = "username";
    $password = "password";

    // try to make connection
    try 
    {
        $conn = new PDO($dsn, $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Database connected <br>";
    }
    catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }

    //  create, print, and execute the query
    $sql = "SELECT * FROM player WHERE player_id = $player_id";
    echo "$sql <br>";
    $result = $conn->query($sql);

    //if the query returned an array
    if (is_array($result))
    {
        // if the array has data
        if ($result->num_rows > 0)
        {
            Echo "Result is an array and has values. <br>";
            Echo "$result[0] $result[1]. <br>";
            return $result;
        }
        else
        {
            echo "No results. <br>";
        }
    }
    else
    {
        echo "Results not an array. <br>";
    }
    //close the database connection.
    $conn = null;
}

Upvotes: 0

Views: 59

Answers (1)

Peter Bowers
Peter Bowers

Reputation: 3093

PDO query returns an object, not an array.

http://php.net/manual/en/pdo.query.php

It will return false on failure so just check

if ($result) {
   ... 

Upvotes: 1

Related Questions