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.ifstatement: 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 output XML from MySQL using PHP?
- How to generate a UUID in MySQL using PHP?
- How to get the first row of a result in MySQL using PHP?
- How to insert a null value in MySQL using PHP?
- How to use a variable in a MySQL query using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get table column names in PHP MySQL?
- How to get the version of MySQL using PHP?
- How to use a MySQL union in PHP?
- How to write an update query in MySQL using PHP?
See more codes...