I am trying to select a value from the database. The select query is returning a 1
or 0
. I want to echo 'yes' if the returned value is 1
and echo 'no' if the returned value is 0
.
When I run the script I always get 'Yes'.
Does someone know what is wrong with my script?
Here is my PHP script:
$sql = "SELECT row FROM table WHERE id='". $_GET['id'] ."'";
$result = $conn->query($sql);
if ($result == 1){
echo 'yes';
}
else
{
echo 'No';
}
$conn->close();
For the answer it is important to know which Database API you use. For most APIs
$result
will be a kind of result object which represents your result. Normally a collections of rows. You can call some kind of fetch function to get a row from a result, and then you would check whether this row contains 1 or 0. You should read the documentation of your API for more details. PHP gives always Yes, because the == Operator tries to do type conversion, and I suppose it converts both values to true. http://php.net/manual/de/language.types.type-juggling.php
If you just want to know if the id exists, you can use a COUNT(*)
expression. That way the query will be guaranteed to return exactly one row, whether the count is 0 or 1.
You should get into the habit of using parameters instead of creating SQL injection vulnerabilities by concatenating $_GET
variables into your query.
And check for errors after every database function that may return an error.
$sql = "SELECT COUNT(*) FROM table WHERE id=?";
if (($stmt = $conn->prepare($sql) === false) {
error_log($conn->error);
die("Database error");
}
// assuming mysqli, but if you use PDO, binding is done differently
if ($stmt->bind_param('i', $_GET['id']) === false) {
error_log($stmt->error);
die("Database error");
}
if ($stmt->execute() === false) {
error_log($stmt->error);
die("Database error");
}
if (($result = $stmt->get_result()) === false) {
error_log($stmt->error);
die("Database error");
}
$row = $result->fetch_row();
$count = $row[0];
if ($count >= 1){
echo 'yes';
}
else
{
echo 'No';
}
$stmt->close();
$conn->close();