function db_execute($sql,$db,$array)
{
require(getcwd() . '/config/config.php');
if (empty($array))
{
$array = "";
print "Something wrong";
}
$connection = db_connect($db_host,$db_username,$db_password,$db);
$q = $connection->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$q ->execute(array($array));
if(!$q)
{
die("Error! " . $connection->errorInfo());
}
$result = $q -> fetchAll();
return $result;
}
$sql = "SELECT VALUE FROM users WHERE :id = :idnum";
$array = array(':id' => 'USER_ID', ':idnum' => '2');
printFormattedArray($array);
printFormattedArray(db_execute($sql,"user_db",$array));
出于某种原因,我无法从此函数中获得任何结果以返回任何结果。但是当我用
替换查询时$sql = "SELECT VALUE FROM users WHERE USER_ID = 2";
它给了我所需的结果。我做错了什么?
答案 0 :(得分:1)
基本上,你有2个选择。
0.1。不要在查询中使用动态标识符 所以,请进行第二次查询。
$sql = "SELECT VALUE FROM users WHERE USER_ID = :idnum";
$array = array(':idnum' => '2');
$data = db_execute($sql, $array);
0.2。如果您需要动态标识符,则还需要一个不同的占位符 所以,你的代码就像
$sql = "SELECT VALUE FROM users WHERE ?n = ?i";
$data = db_execute($sql, 'USER_ID', 2);
另外,
在连接
后添加此代码$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );