以下代码未将任何值返回到$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;
}
答案 0 :(得分:1)