How to check if SQL query result is empty before executing other queries in PHP

I have the following PHP code which is for an application voting system. Its a Q & A application, and the user can vote for questions and answers that are published.

In my php code, I first check if the user voted for a specific question. This will exist in the QVOTES table, with the email address and the ID of the question that was voted on.

When doing this check, I'm not sure how to see if $ result is an empty set to send a user vote if they have not voted for the question yet.

How can I make this work? All help is appreciated.

<?php $con=mysqli_connect("127.2.1.1","S837","887","D887"); if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $qid = $_POST['qid']; $email = $_POST['email']; $result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = '$email'"); if (!mysqli_num_rows($result) ){ if ($result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, '$email')")) { mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid"); echo "Update successful"; } else{ echo "Update unsuccessful"; } } else{ echo "null"; } mysqli_close($con); 
+6
source share
2 answers

In fact, you are doing wrong. Try the following: -

 <?php $con=mysqli_connect("127.2.1.1","S837","887","D887"); if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $qid = $_POST['qid']; $email = $_POST['email']; $result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = $email") or die(mysqli_error($con)); // no need of extra quote if ($result->num_rows == 0 ){ // means no vote-up done till now $result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, $email)")or die(mysqli_error($con)); // insert if($result){ echo "Vote Added successfully."; } else{ echo "Error occur while adding vote.Please try again."; } } else{ $result = mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid AND EMAIL = $email")or die(mysqli_error($con)); // upddate if($result){ echo "Vote updated successfully."; } else{ echo "Error occur while updating vote.Please try again."; } } mysqli_close($con); 

Note. “I'm changing the message for a better understanding.” You can change according to your desire. thanks.

+1
source

How to find out if $ result is an empty set?

From the docs:

Returns false on error. For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries, mysqli_query () will return a mysqli_result object. For other successful queries, mysqli_query () will return TRUE ( Ref )

Use $result->num_rows if $result not FALSE ;

+1
source

Source: https://habr.com/ru/post/987840/


All Articles