下面的代碼不會將任何值返回到我的$result
變量中。數據庫連接是好的。但它似乎沒有返回$result
變量的任何值。使用PDO運行mySQL查詢時出現問題
我確實有player
表中的數據,並且在所述表中存在1和2的值player_id
。
運行時打印回聲是這樣的。當將整數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;
}
'的var_dump($結果);' - 這是什麼生產? – 2015-04-03 19:43:24
object(PDOStatement)#2(1){[「queryString」] => string(40)「SELECT * FROM player WHERE player_id = 1」} – 2015-04-03 19:49:12