如果没有创建cookie,我正在尝试执行mysql更新查询。
这是我尝试的方式:
// Sanitize and validate the data passed in
// Check for the ID, comes from ajax:
$count = (int)$_POST['count'];
// Get existing views:
$prep_stmt = "SELECT views FROM phone_number_views";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($existing_views);
// Fetch all the records:
$stmt->fetch();
}
// Close the statement:
$stmt->close();
unset($stmt);
$n='';
$n=$existing_views+$count;
echo $n;
//if no such cookie exists, assume that its their first time viewing.
if(!isset($_COOKIE['number_viewed'])){
$q = "INSERT INTO number_views (id, views) VALUES (1, 1)
ON DUPLICATE KEY UPDATE views = $n";
// Prepare the statement:
$stmt = $mysqli->prepare($q);
// Bind the variables:
//$stmt->bind_param('i', $n);
// Execute the query:
$stmt->execute();
// Print a message based upon the result:
if ($stmt->affected_rows == 1) {
//set cookie saying they've viewed this number.
setcookie( 'number_viewed', $n, time()+600, '/');
// Print a message and wrap up:
$messages = array('success'=>true, 'totalViews'=>$n);
}
// Close the statement:
$stmt->close();
unset($stmt);
}
echo json_encode($messages);
// Close the connection:
$mysqli->close();
我的问题是这个cookie没有创建。更新查询始终有效。
注意:这是一个ajax处理脚本。
有人可以说出这是什么问题吗?
希望有人可以帮助我。
谢谢。
答案 0 :(得分:1)
问题是您正在为(id,views)编写带值(1,1)的插入查询,但id
是您的主键。因此,值1不能分配两次。因此,查询的后面部分每次都在运行。尝试通过查询仅插入(视图)列。然后,您将找到您的cookie是否已设置