Home >Backend Development >PHP Tutorial >How to Efficiently Check for the Existence of a Row in MySQL?
Verifying the Existence of a Row in MySQL
In cases where you need to determine the presence of a row within a MySQL database, there are various approaches available. Specifically, you may wish to check if an email address exists in the database.
Using Prepared Statements
To enhance security and prevent SQL injection, prepared statements are a recommended approach:
MySQLi (Legacy)
$query = "SELECT 1 FROM `tblUser` WHERE email=?"; $stmt = $dbl->prepare($query); $stmt->bind_param("s", $email); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc(); $emailExists = (bool)$row;
MySQLi (Modern - PHP 8.2 )
$query = "SELECT 1 FROM `tblUser` WHERE email=?"; $result = $dbl->execute_query($query, [$email]); $row = $result->fetch_assoc(); $emailExists = (bool)$row;
PDO
$stmt = $conn->prepare('SELECT 1 FROM `tblUser` WHERE email = :email'); $stmt->execute([":email" => $_POST['email']]); $row = $result->fetch(); $emailExists = (bool)$row;
General Considerations
Additional Resources
The above is the detailed content of How to Efficiently Check for the Existence of a Row in MySQL?. For more information, please follow other related articles on the PHP Chinese website!