我在将值与 PDO 和 PHP 绑定时遇到了一些问题。当我用变量替换值时,脚本会返回正确的结果,但由于某种原因,我无法让它工作。
// Connect to database in function on different page
function db1() {
try {
$pdo = new PDO("mysql:host=localhost;dbname=**********", '**********', '**********');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
$pdo = null;
} catch (PDOException $e) {
die($e->getMessage());
}
}
// Scrit with problems
$db = db1();
$query = $db->prepare("SELECT column1, column2, column3, column4 FROM table_name WHERE (column4=2 OR column4=3) AND column5=:col1 AND column6=:col2"); // Prepare the statement to prevent any SQL injection
$query->bindValue(':col1', $var1, PDO::PARAM_INT);
$query->bindValue(':col2', $var2, PDO::PARAM_STR);
$query->execute();
// I also tried the following.
// $query->execute(array(':col1' => $var1, ':col2' => $var2));
// Fetch result row
$row = $query->fetch(PDO::FETCH_ASSOC);
有任何想法吗?
UPDATE 查询前后是否有 var_dump。var1 = string(1) "2" 和 var2 = string(1) "1"
删除 $pdo = null;