Squiggly Hl
Squiggly Hl

Reputation: 27

How can i run a mysql query on button click

I'm new to PHP so this might be something obvious I missed. Im trying to make a button which increments a value in my database:

<?php
        $alist = mysqli_query($conn, "SELECT * FROM `posts` ORDER BY `posts`.`id` DESC");
        $results = mysqli_num_rows($alist);

        if ($results > 0){
            while($row = mysqli_fetch_array($alist)) {
                echo $row['uid']. " says: ".$row['postText']."  <button onclick=".mysqli_query($conn, "UPDATE `posts` SET `postLikes` = postLikes+1 WHERE uid = ".$row['uid'])." name='likebtn'>👍</button>".$row['postLikes']."<br>";
            }
        }
        ?>

The part that makes the button is on line 6 I just want to find how I can use the mysqli_query on button click by the way, I already tried this: "https://stackoverflow.com/questions/3862462/php-mysql-run-query-on-button-press-click" but with no result

Thanks in advance

Upvotes: 0

Views: 1973

Answers (2)

Marko Kurtović
Marko Kurtović

Reputation: 41

if your current page is called first.php, put inside button

<button><a href="first.php?p=like"></a></button>

<?php
if ( isset($_GET['p']) && $_GET['p']=="like") {

do your query

}

?>

if you dont want to reload then you need ajax,

hope this was helpful. :)

Upvotes: 1

Rupesh Chaudhari
Rupesh Chaudhari

Reputation: 308

You have a syntax error here echo $row['uid']. " says: ".$row['postText']." <button onclick=".mysqli_query($conn, "UPDATE posts SET postLikes = postLikes+1 WHERE uid = ".$row['uid'])." name='likebtn'>👍</button>".$row['postLikes']."<br>";

you can either do this

$q = mysqli_query($conn, "UPDATE posts SET postLikes = postLikes+1 WHERE uid = ".$row['uid']);

echo $row['uid']. " says: ".$row['postText']." <button onclick=".$q." name='likebtn'>👍</button>".$row['postLikes']."<br>";

Upvotes: 1

Related Questions