Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO/PHP - Check if row exist

Tags:

php

pdo

row

I want to have a condition that will perform some action when the row doesn't exist at all.

$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?'); $stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); 

Tried if (count($row) == 0) and if($stmt->rowCount() < 0) but none of them works.

like image 810
xperator Avatar asked Aug 15 '12 18:08

xperator


People also ask

How to check number of rows in PDO?

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of matching rows.

How do you check whether a record exists or not in PHP?

You can set the specific columns in your database as primary key and then the insert will success only if you don't have the record already. In this way, you don't event need to check if record exists. Show activity on this post.


1 Answers

You can just check the return value directly.

$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'; }  /* $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here if( ! $rows) {     echo 'nothing found'; } */ 

If you are asking about checking without fetching then simply have MySQL return a 1 (or use the COUNT() command).

$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1'; //$sql = 'SELECT COUNT(*) from table WHERE param = ?'; // for checking >1 records $stmt = $conn->prepare($sql); $stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT); $stmt->execute();  if($stmt->fetchColumn()) echo 'found'; 
like image 58
Xeoncross Avatar answered Oct 02 '22 05:10

Xeoncross