使用PDO运行mySQL查询时出现问题

时间:2015-04-03 19:40:43

标签: php mysql pdo

以下代码未将任何值返回到$result变量中。数据库连接很好。但它似乎没有返回$result变量的任何值。

我的player表中有数据,表中的player_id值为1和2。

跑步时打印回声是这样的。将整数1和2传递给函数时。

连接数据库

SELECT * 
FROM player 
WHERE player_id = 1

结果不是数组。

连接数据库

SELECT * 
FROM player 
WHERE player_id = 2

结果不是数组。

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;
}

1 个答案:

答案 0 :(得分:1)

PDO查询返回一个对象,而不是一个数组。

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

失败时返回false,只需检查

if ($result) {
   ...