How to Check Row Existence in a Database Using PDO
When attempting to perform an action conditional on the absence of a specific row in a database, you may encounter difficulties with using traditional methods like count($row) == 0 or if($stmt->rowCount() < 0).
A more effective approach is to directly examine the return value of the query. The following code snippet illustrates this technique:
<code class="php">$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?'); $stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if( ! $row) { echo 'nothing found'; }</p> <p>This method will return true if the row exists in the database, and false if it does not.</p> <p>For checking the existence of multiple rows, you can use the fetchAll() method:</p> <pre class="brush:php;toolbar:false"><code class="php">$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here if( ! $rows) { echo 'nothing found'; }</code>
In situations where you wish to avoid fetching data, you can configure MySQL to return a boolean value by using the following query:
<code class="php">$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1'; $stmt = $conn->prepare($sql); $stmt->execute([$_GET['id']]); if($stmt->fetchColumn()) echo 'found';</code>
This method will return a non-zero value if the row exists in the database and false otherwise.
The above is the detailed content of How Can You Check the Existence of a Row in a Database Using PDO?. For more information, please follow other related articles on the PHP Chinese website!