php-mysqlHow to check if a record exists in PHP and MySQL?
To check if a record exists in PHP and MySQL, you can use the SELECT
statement. For example, the following code will check if a record with the id
of 1
exists in the users
table:
$sql = "SELECT * FROM users WHERE id = 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "Record exists";
} else {
echo "Record does not exist";
}
Output example
Record exists
Code explanation
$sql
: This is the SQL query that will be used to check if the record exists.$result
: This is the result of the query.mysqli_query($conn, $sql)
: This is a function that will execute the query and return the result.mysqli_num_rows($result)
: This is a function that will return the number of rows in the result.if
statement: This is used to check if the number of rows in the result is greater than 0.
Helpful links
More of Php Mysql
- How to use a variable in a MySQL query using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to check the result of an insert in PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to fetch data from MySQL in PHP?
- How to get a single value from query in PHP MySQL?
- How to get the first row of a result in MySQL using PHP?
- How to update to null value in MySQL using PHP?
- How to use a MySQL union in PHP?
- How to generate a UUID in MySQL using PHP?
See more codes...