Hi. I try this code: $Data = new Conection(); $sql = "SELECT fiel1, field2 FROM mytable WHERE condicion"; if ($stm = $Data->query($sql)) { echo "There are records"; } else { echo "No Records"; } PHP: I want to show "There are records" if mytable are records. I want to show "No Records" if mytable is empty. But always show "There are records" Why?
Because your if is checking to see if the query is run - which, as long as there are no errors, it is. Hence, it will always return "There are records", regardless of how many records is found.
The correct way to do all this would first be to fix all the spelling errors, then use whatever method of rowCount() you have available. In PDO this would be something like this: $data = new Connection(); //you never START a variable with a capital letter $stmt = $data->query("SELECT field1, field2 FROM mytable WHERE condition"); if ($stmt->rowCount() > 0) { echo "There are records"; } else { echo "There are no Records"; } PHP:
But In PHP manual, says: http://php.net/manual/en/pdostatement.rowcount.php (in Example #2 Counting rows returned by a SELECT statement).
Well... depends on the database. MySQL supports rowCount() on select. Ref: "If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications." (same page)