0

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

1
  • You can call AJAX Request on Button click. (onClick) function not working directly in server script, So you need to write ajax function and call PHP Query. Commented Jul 7, 2020 at 20:23

2 Answers 2

1

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. :)

Sign up to request clarification or add additional context in comments.

Comments

1

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>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.