简体   繁体   中英

PDO Ajax updating mysql database

I need help in this PHP Ajax updating mysql database using PDO. I wanted to update the database if a user checks the checkbox. Below is my code:

JS:

$('input[name=product_new]').click(function(){

    var chkbox_id = $(this).attr('alt');
    var chkbox_selected = $(this).is(':checked');

    if(chkbox_selected == true)
    {
        chkbox_selected = "checked";
    }
    else
    {
        chkbox_selected = "uncheck";
    }


    $.post({
            url: "../products_listing.php",
            type: "POST",
            data: {product_id: chkbox_id, product_new: chkbox_selected},
            cache: false,
            success: function(){}

           });

});

PHP page with PDO to update database:

$id = $_POST['product_id'];
$product_new = $_POST['product_new'];
if(isset($_POST['product_new']))
{
    try
    {
        $query = "UPDATE productinfo SET new_arrival=? WHERE id=?";
        $stmt_new_chkbox = $conn->prepare($query);
        $stmt_new_chkbox->bindParam(1, $product_new, PDO::PARAM_STR);
        $stmt_new_chkbox->bindParam(2, $id, PDO::PARAM_INT);
        $stmt_new_chkbox->execute();
    }
    catch(PDOException $e)
    {
        echo 'ERROR: ' . $e->getMessage();
    }
}

It was working when I use mysql but now I've changed it to use PDO, it won't work anymore. I can't find where went wrong. Thanks in advance guys.

Below is the old code from mysql_:

$id = mysql_real_escape_string($_POST['product_id']);
$product_new = mysql_real_escape_string($_POST['product_new']);
if(isset($_POST['product_new']))
{
    $upt_new=mysql_query("update products_list set new_arrival='$product_new' where id='$id'");
}

Ok! I know what's wrong already. The damn directory path. I took out ../ and it works! Kinda weird though.

Because my js file is in JS folder and products_listing.php is outside of the js folder. Isn't it supposed to be ../products_listing.php?

Can anyone tell me why it's not working which it is supposed to be?

Thanks in advance guys!

Just split your task into 2 parts: AJAX part and PDO part.

First of all make sure that your PDO part works well. Make a mock $_POST array, and then start playing with PDO calling this script directly, without AJAX. Ask questions here, if something goes wrong. then, as you ret it to work, move to AJAX part, the same way - first, without PDO by just by sending data to server and verifying if it's correct.

Solving 2 problems at once makes things a lot harder. Always split your task into separate parts and solve them one by one.

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