简体   繁体   中英

PHP prepared statement update form

I will break this question into paragraphs for easier refering;

  1. I have a website with a button which plusses a current number from a database with 1.

  2. I have now used an "update" form in order to plus the number in the database. I have used prepared statements to do so:

     <?php require_once('connectvars.php'); $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (mysqli_connect_errno()) { echo 'Cannot connect.' . mysqli_connect_error(); exit(); } if ($stmt = $mysqli->prepare('UPDATE `javascriptbutton` SET `clicks`=? WHERE `id`=?')) { $stmt->bind_param('ii', $clicks, $id); $clicks = $_POST['clicks'] + 1; $id = 1; $stmt->execute(); $stmt->close(); } else { echo 'Woops, something went wrong.: ' . $mysqli->error; } 

    ?>

  3. When the user presses a button in html, it calls a script containing Ajax which refers to the php script above.

  4. Everytime the button is pressed, this php file has to get the current "clicks" from the database column "clicks" where id=1 and plus it with 1 and insert it back into the database.

  5. I have been researching and looking on my code a lot and I can conclude that it has to do with:

    $clicks = $_POST['clicks'] + 1;

The $_POST['clicks'] should be the current number in the database, and get plussed by 1.

Question: Do I have to create a select form to get the current clicks out of the database? Or how can I plus the current clicks with 1 and put the new number back into the database till next time a person presses the button?

If there are any of the 5 steps you want to deepen, please tell me.

You can just use:

$mysqli->prepare("UPDATE `javascriptbutton` SET `clicks`=`clicks`+1 WHERE `id`=?")

EDIT Full code:

    if ($mysqli->prepare("UPDATE `javascriptbutton` SET `clicks`=`clicks`+1 WHERE `id`=?")) { 

        $stmt->bind_param('i', $id);
        $id = 1;

        $stmt->execute();

        $stmt->close();

    } 

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