简体   繁体   中英

PHP cookie is not creating in ajax processing script

I am trying to execute an mysql update query if cookies is not created.

This is how I tried it:

// 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();   

My problem is this cookie is not creating. update query always working.

NOTE: this is a ajax processing script.

Can anybody tell what is the problem of this?

Hope somebody may help me out.

Thank you.

The problem is you are writing insert query with values (1,1) for (id,views) but id is your primary key. Hence value 1 cannot be assigned twice. Therefore the later part of the query is running every time. Try to insert only (views) column by your query. You will then find whether your cookie is set or not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM