我是PDO的新手,并试着这个
function ExecuteSqlQuery($connection, $sqlQuery, $paramsArray)
{
try
{
$sql = $connection->prepare($sqlQuery);
$sql->setFetchMode(PDO::FETCH_ASSOC);
$sql->execute($paramsArray);
$result = $sql->fetchall(PDO::FETCH_ASSOC);
}
... etc
$result
总是一个空数组。
有人能告诉我我做错了吗?
$connection
有效(我检查(未显示),但如果不是则会抛出异常)
paramsArray = array('modem_id' => '1');
$sqlQuery = "SELECT vehicle_id FROM vehicles WHERE modem_id=":modem_id"
[更新] 根据要求,这里是更详细的代码。
function ExecuteSqlQuery($connection, $sqlQuery, $paramsArray)
{
try
{
$sql = $connection->prepare($sqlQuery);
$sql->setFetchMode(PDO::FETCH_ASSOC);
$sql->execute($paramsArray);
$result = $sql->fetchall(PDO::FETCH_ASSOC);
}
... etc Nothing matters after this point in the function,
as things have already gone wrong - $result is NULL
catch (Exception $e)
{
echo $e->getMessage(); // This code is not reached
}
} // ExecuteSqlQuery()
$connection = ConnectToDatabase(); // Do you need the code for that? It works, my IDE shows a PDO object
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$queryParams = array('modem_id' => "1");
$sqlQuery = 'SELECT vehicle_id FROM ' . DATABASE_NAME . '.vehicles WHERE modem_id=":modem_id"';
$result = ExecuteSqlQuery($connection, $sqlQuery, $queryParams);
答案 0 :(得分:0)
你不应该像你一样引用参数:
$sqlQuery = 'SELECT vehicle_id
FROM ' . DATABASE_NAME . '.vehicles
WHERE modem_id=":modem_id"';//remove quotes
将其更改为以下内容:
$sqlQuery = 'SELECT vehicle_id
FROM ' . DATABASE_NAME . '.vehicles
WHERE modem_id=:modem_id';