我有一些接受数字的sql语句,如果该数字等于数据库中列的值,它应该返回数据库中具有相同值的所有行。不幸的是,行只返回值为0的blog_post_id。
这是我的代码:
<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id']
: '';
$pdo=new PDO("mysql:dbname=db;host=localhost","username","password",
$options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id =
'$blog_post_id'");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
if ($json)
echo $json;
else
echo json_last_error_msg();
?>
答案 0 :(得分:0)
您实际上忽略了使用函数prepare()
的重点,您需要检查查询是否确实返回任何结果..
<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id'] : '';
$pdo = new PDO("mysql:dbname=db;host=localhost", "username", "password", $options);
$statement = $pdo->prepare("SELECT * FROM comment WHERE blog_post_id = ?");
$statement->execute([$blog_post_id]);
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = array();
if (count($results) > 0) {
foreach ($results as $row) {
$json[] = array(
'id' => $row['blog_post_id'],
'Field' => $row['Column'],
'AnotherField' => $row['AnotherColumn'],
'AnotherField1' => $row['AnotherColumn1'],
'ETC' => $row['AnotherColumnName']
);
}
echo json_encode($json);
} else {
echo "no data found";
}
?>
答案 1 :(得分:0)
你应该像这样进行变量绑定:
$pdo=new PDO("mysql:dbname=db;host=localhost","username","password", $options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id = :blog_post_id");
$statement->execute(['blog_post_id' => $blog_post_id]);
这也将阻止第一级SQL注入,如下所述:Are PDO prepared statements sufficient to prevent SQL injection?