Jump to content

Check if table exists


Morsusy2k

Recommended Posts

Okay I got a headache because of this :D

So basically I am trying to get if table exists in my DB,if yes echo '1'; and if not echo '0';

 

This one keeps loading forever:

<?php	include 'connect.php';	$mytable = 'c27';	$table ='select * from c27';        //$table ='show tables';	while ($row = mysql_query($table)) { 		if ($row == $mytable) { 			echo "1"; 		} else {			echo '0';		}	}?>

This fails too:

$sql2 = "select * from 'c27'";echo $sql2."<br/>";$result2 = mysql_query($sql2);echo $result2."<br/>";//this is line 84while ($row2 = mysql_fetch_assoc($result2)){echo '1';}						if (!$result2) {echo "0";} else {echo "1";}

In this test first loop (while) gives this error:

select * from 'c27'Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ......./page.php on line 85

As you can see echoing result outputs nothing...

 

And in the second loop (if) it always ends up with echoing 0.

 

'c27' table really exists in my DB and I can detect it in SQL query box but not in php..

 

F1,thanks :)

Edited by Morsusy2k
Link to comment
Share on other sites

This is going to fail because c27 is wrapped in aspostrophes when it shouldn't be:

$sql2 = "select * from 'c27'";

 

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ......./page.php on line 85

 

About this error, we have a thread dedicated to it: http://w3schools.invisionzone.com/index.php?showtopic=44106

It means MySQL encountered an error. Using SELECT on a table that doesn't exist probably would make mysql send an error message.

 

If you want to know if a table exists, do the following query:

SHOW TABLES LIKE c27

If the you can fetch any rows from that query then the table exists, otherwise the table doesn't exist.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...