I want to validate if the table exists, if that is true, check if there are records or not. I have this code, but the system show this message in query line whe the table is not exists. (Using PHP/PDO). Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 <?php require ('includes/configure.php'); $db = new connection(); $sql = "SELECT cod, nom FROM table"; $stm = $db->query($sql); if (!$stm){ echo "There are problems"; } else { if ($stm->rowCount() > 0) { echo "There are records"; } else { echo "There are not records"; } } ?> PHP: What is the mistake?
Code snippet that you have posted doesn't say much. Either you are looking for the wrong table or .. you are looking for the wrong table (in most of the cases).
Hi. Of course, I try to validate is wrong table, is that true the code should show "There are problems", but doesnt do that.
If that is what is being returned if you try to do stuff to a query with a non-existing table, your DB-code is crap. It should just return an error, not a fatal error - my class would return the following: <p class="messagebox error visible">Attempt to execute on boolean - check logs for errors SELECT * FROM table</p> Code (markup): Granted, the code being output is controlled by the DB-class, and the error-output is custom.
Mi db conection is this: <?php class connection extends PDO { public function __construct () { try { parent:: __construct('mysql:host=localhost;dbname=mydb', user, password); parent:: setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (Exception $ex) { die ('Data base doesnt exists'); } } function __destruct(){ } } ?> PHP:
Remove the parent:: setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Code (markup): That will remove the fatal error - then handle the error properly.
<?php require ('includes/configure.php'); $db = new connection(); $sql = "SELECT cod, nom FROM table"; $stm = $db->query($sql); if (!$stm){ echo "There are problems"; } else { if ($stm->rowCount() > 0) { echo "There are records"; } else { echo "There are not records"; } } ?> In this if you table name is table then you need to do like this SELECT cod, nom FROM `table` If you will use direct table it will give error because its a default syntax.
The mistake is that you are running a query on a non-existent table. Here's the code I use. Its for mysqli $result = $mysqli->Query(" SHOW TABLES LIKE 'my_table_name' "); if( $result->num_rows >0 ){ // table exists run other queries }else{ echo ' no table '; }