-2

I am trying to check whether a table exists in my database but I am always getting "You are in!" as output. The output of the if statement is not being displayed in the browser.

I appreciate any help.

  $con = new mysqli ( 'localhost', 'root', '', 'bustracker' );
    echo "You are in!";
             if($con->connect_errno){
        die ( "connection problem!".$con->connect_error);
             }

          //check whether route's table exists.
          $results = $con->query("SHOW TABLES LIKE '".$route."'");

           if( ($results->num_rows) == 1){
             echo "Table exist";
           }else{
            echo "table does not exist";
           } 
benz
  • 693
  • 1
  • 9
  • 29

2 Answers2

3
SELECT 1 FROM tablename LIMIT 1;

If there's no error, table exists.

Or, if you want to be correct, use INFORMATION_SCHEMA.

SELECT * 
FROM information_schema.tables
WHERE table_schema = 'yourdb' 
AND table_name = 'your_table_name'
LIMIT 1;

Alternatively, you can use SHOW TABLES

SHOW TABLES LIKE 'your_table_name';

If there is a row in the resultset, table exists

Praveen Dabral
  • 2,449
  • 4
  • 32
  • 46
  • Yes I found this answer somewhere too and I tried it: http://stackoverflow.com/questions/8829102/mysql-check-if-table-exists-without-using-select-from but no output – benz Apr 27 '15 at 11:22
  • Yes you answer is right but the error in my code was the if statement which block the code. When I put the code in the else if-statement parts it works – benz Apr 27 '15 at 12:00
-3
<?php
 
$con = @new mysqli('localhost', 'root', '', 'bustracker');
echo "You are in!";
if ($con->connect_errno) {
    die("connection problem!" . $con->connect_error);
} else {
    $results = $con->query("SHOW TABLES LIKE '" . $route . "'");

    if (($results->num_rows) == 1) {
        echo "Table exist";
    } else {
        echo "table does not exist";
    }
}
Sujeet Kumar
  • 159
  • 6