我的pdo错误如果声明

时间:2014-12-30 04:39:58

标签: php pdo

我想添加到数据库user_id和fav_id。但只有他们俩在一起时才会被记录下来。 我在我的代码中做错了,因为它总是添加它。 为什么会这样?

<?php
include '../connect.php';

$fav_id = $_POST['fav_id'];
$user_id = $_POST['user_id'];

$number = $pdo-> query('SELECT COUNT(*) FROM favourites WHERE user_id = :user_id AND fav_id = fav_id ');

if ($number == 0) {
$pdo->exec("INSERT INTO `favourites` (`fav_id`, `user_id`) VALUES (" . $fav_id . "," . $user_id . ")");
}
else die();

?>

1 个答案:

答案 0 :(得分:0)

使用fetchColumn()

更多我认为您应该使用以下语句准备语句:user-id和fav_id

<?php
include '../connect.php';

$fav_id = $_POST['fav_id'];
$user_id = $_POST['user_id'];

$number = $pdo-> prepare('SELECT COUNT(*) FROM favourites WHERE user_id = :user_id AND fav_id = :fav_id ');

$number ->execute(array(':user_id' => $user_id,':fav_id'=>$fav_id));

if ($number ->fetchColumn() == 0) {
$pdo->exec("INSERT INTO `favourites` (`fav_id`, `user_id`) VALUES (" . $fav_id . "," . $user_id . ")");
}
else die();

?>