PHP cookie不是在ajax处理脚本中创建的


PHP cookie is not creating in ajax processing script

我试图执行mysql更新查询,如果cookie没有创建。

我是这样尝试的:

// 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处理脚本。

谁能告诉我这是什么问题?

希望有人能帮助我。

谢谢。

问题是您正在为(id,views)编写值(1,1)的插入查询,但id是您的主键。因此值1不能被赋值两次。因此,查询的后一部分每次都在运行。尝试通过查询只插入(视图)列。然后您将发现您的cookie是否已设置