0

I'm writing a program that must check if a row with a unique "id" value exists or not in a table, and to either fetch the data from it if it does exist, or create the row if it does not exist.

I am relatively new to the MySQL syntax, and it causes me trouble so far.

What I tried to do is this:

Connect to the database;

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}          

I attempt to check whether a row with a particular unique value of one of the columns exists

 $sql = "SELECT EXISTS(SELECT * FROM employee WHERE id=300)";
 $result = mysqli_query($conn, $sql) or die("error to check the existence of the row");
 if ($result = 1){echo "A row with current date does exist";}
 else {echo "A row with current date does not exist";}

The problem with this check is that whether such a "42" value exists in the table or not, or any other value, for that matter, it always seems to return "1".

Obviously, this does not work. But how is it supposed to be done?
Sorry if the question is stupid.

Petro
  • 11
  • 2
  • It seems like you do not execute that query. Is some part of your code missing? – GMB Feb 28 '20 at 22:44
  • @GMB Added the "$result" line that, I believe, must execute the query, and updated the consequent code accordingly. Still, it returns "1". – Petro Feb 28 '20 at 22:53
  • Does this answer your question? [How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)](https://stackoverflow.com/questions/22252904/how-to-check-if-a-row-exists-in-mysql-i-e-check-if-an-email-exists-in-mysql) – Dharman Feb 29 '20 at 00:27
  • Note that the accepted answer is fundamentally flawed. For an explanation as to why, see about race conditions. – Strawberry Feb 29 '20 at 07:12

1 Answers1

0

You need to fetch the row from the query result.

$row = mysqli_fetch_row($result);
if ($row[0]) {
    echo "A row with current date does exist";
} else {
    echo "A row with current date does not exist";
}

BTW, you're checking for an ID, not a date, so the messages don't seem to match the query.

You also had a typo in your code

if ($result = 1)

is assigning the variable, not testing it; comparisons use ==.

Barmar
  • 741,623
  • 53
  • 500
  • 612