In PHP, what would be the best way of seeing if a table exists?
This is what I am using so far
public function TableExists($table) {
$res = $this->Query("SELECT 1 FROM $table");
if(isset($res->num_rows)) {
return $res->num_rows > 0 ? true : false;
} else return false;
}
What you posted is going to throw an error if the table doesn't exist. Try this instead:
SHOW TABLES LIKE 'tablename';
And ensure that you get exactly one row back.
Colin has the right solution -- to use SHOW TABLES LIKE. Here is what it would look like using your code:
public function TableExists($table) {
$res = $this->Query("SHOW TABLES LIKE $table");
return mysql_num_rows($res) > 0;
}
For seeing, if [table name] exist
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
An alternative to the SHOW TABLES approach from other answers is using the INFORMATION_SCHEMA like this:
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'your_database_name' AND TABLE_NAME = 'tablename';
$con = mysqli_connect($hostname,$username,$password,$database);
if(mysqli_num_rows(mysqli_query($con,"SHOW TABLES LIKE 'accman'"))) {
echo "DB EXIST";
} else {
echo "DB Not Exist";
}
Related
I am working on an Android app that connects to an sql database through php files. Currently I am having problems with the like function on one of my queues.
Here is the code of the file where the problem is:
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
$like = $_REQUEST['like'];
$sql_q = mysqli_query($con,"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '$like'");
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
}
if($output)
{
print(json_encode($output));
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "\n";
}
mysqli_close($con);
?>
This code works with this query - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '11/02/__/00/%' - and returns:
[{"ID":"11\/02\/00\/00\/00\/0\/0\/0","Value":"Tradicionais","Value_Complete":""},
{"ID":"11\/02\/01\/00\/00\/0\/0\/0","Value":"Caipis","Value_Complete":""},
{"ID":"11\/02\/02\/00\/00\/1\/0\/0","Value":"Daiquiri","Value_Complete":""},
{"ID":"11\/02\/03\/00\/00\/1\/0\/0","Value":"Gin Tonico","Value_Complete":""},
{"ID":"11\/02\/04\/00\/00\/1\/0\/0","Value":"Long Island Ice Tea","Value_Complete":""},
{"ID":"11\/02\/05\/00\/00\/1\/0\/0","Value":"Manhattan","Value_Complete":""},
{"ID":"11\/02\/06\/00\/00\/1\/0\/0","Value":"Margarita","Value_Complete":""},
{"ID":"11\/02\/07\/00\/00\/1\/0\/0","Value":"Martini Seco","Value_Complete":""},
{"ID":"11\/02\/08\/00\/00\/1\/0\/0","Value":"Black Russian","Value_Complete":""},
{"ID":"11\/02\/09\/00\/00\/1\/0\/0","Value":"White Russian","Value_Complete":""},
{"ID":"11\/02\/10\/00\/00\/1\/0\/0","Value":"Sex on the Beach","Value_Complete":""},
{"ID":"11\/02\/11\/00\/00\/1\/0\/0","Value":"Sidecar","Value_Complete":""},
{"ID":"11\/02\/12\/00\/00\/1\/0\/0","Value":"Sakerinha","Value_Complete":""},
{"ID":"11\/02\/13\/00\/00\/1\/0\/0","Value":"Tequila Sunrise","Value_Complete":""},
{"ID":"11\/02\/14\/00\/00\/0\/0\/0","Value":"Vodka","Value_Complete":""}]
The same query returns this in phpMyAdmin:
However, the same code does not work with the query - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '$like'. It returns an empty result set but in phpMyAdmin returns:
I just can't figure out the issue here... Even this - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '%'- returns nothing, when it should return everything.
Could you help me? Thanks.
try to change your query:
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
$like = $_REQUEST['like'];
$sql_q = mysqli_query($con,"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '%".$like."%'");
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
}
if($output)
{
print(json_encode($output));
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "\n";
}
mysqli_close($con);
?>
Basically like in something work as equal to (=) but it give you the flexibility to use wild card. % wild card use to define in sql query that there is something but not matter.
If you are not use % with your query it means you are searching same string that is stored in $like variable.
In phpmyadmin you don't need to use %. Because phpmyadmin is designed to the make the use of database easy. So when you select like in search option it automatically add % before applying query on database.
Due to this reason you see these difference.
Add % to the variable
"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '$like%'"
Please try this this complete solution according to your requirements
SELECT tablename FROM id WHERE FIND_IN_SET('/',$column name);
It uses the find_in_Set mysql function which takes 2 parameters, one is the separator and the other is the column name.
I want to take the column names from a table and display them, so i can compare them later.
To get the names, i tried:
$entry = mysqli_query($con, 'SHOW COLUMNS FROM table');
and
$entry = mysqli_query($con, "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '$db' AND TABLE_NAME = 'table'");
I don't know whether this runs correctly or not, since i don't get an error message there.
If i try to print the contents of $entry via echo, i keep getting errors.
Previously in my code, i print other entries using:
$test = mysqli_query($con, 'SELECT DISTINCT LK_Release FROM table');
while($row = mysqli_fetch_object($test))
{
echo "Releasename: " . "$row->LK_Release". "<br>";
... }
This output works for me.
What i tried to output the columnnames:
while($row = mysqli_fetch_object($entry))
{
echo $row;
}
Any ideas?
Your query is already correct. But you lack something in the fetching:
while($row = mysqli_fetch_object($entry))
{
echo $row->Field . '<br/>';
// ^ access the objects properties
}
The following SQL statements are nearly equivalent:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
You can use DESCRIBE:
DESCRIBE my_table;
Or in newer versions you can use INFORMATION_SCHEMA:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
Or you can use SHOW COLUMNS:
SHOW COLUMNS FROM my_table;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
MySQL check if a table exists without throwing an exception
I have a dynamic mysql query builder in my project that creates select queries from different tables.
I need to check if the current processing table exists or not.
Imagine that my tables are table1, table2, and table3. My code is something like this:
<?php
for($i = 1 ; $i <= 3 ; $i++) {
$this_table = 'table'.$i;
$query = mysql_query("SELECT * FROM $this_table");
// ...
}
?>
How can I do this check (Please tell me the simplest way).
Updated mysqli version:
if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
if($result->num_rows == 1) {
echo "Table exists";
}
}
else {
echo "Table does not exist";
}
Original mysql version:
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1)
echo "Table exists";
else echo "Table does not exist";
Referenced from the PHP docs.
Taken from another post
$checktable = mysql_query("SHOW TABLES LIKE '$this_table'");
$table_exists = mysql_num_rows($checktable) > 0;
$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"');
$tablesExists = array();
while( null!==($row=mysqli_fetch_row($query)) ){
$tablesExists[] = $row[0];
}
$result = mysql_query("SHOW TABLES FROM $dbname");
while($row = mysql_fetch_row($result))
{
$arr[] = $row[0];
}
if(in_array($table,$arr))
{
echo 'Table exists';
}
Use this query and then check the results.
$query = 'show tables like "test1"';
You can try this
$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error());
or this
$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!");
or this
$query = mysql_query("SELECT * FROM $this_table");
if(!$query)
echo "The ".$this_table." does not exists";
Hope it helps!
MySQL way:
SHOW TABLES LIKE 'pattern';
There's also a deprecated PHP function for listing all db tables, take a look at
http://php.net/manual/en/function.mysql-list-tables.php
Checkout that link, there are plenty of useful insight on the comments over there.
I know this isn't so complicated but I can't remember how to do.
I just need to know the next auto increment.
$result = mysql_query("
SHOW TABLE STATUS LIKE Media
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
...but i won't work for me, what am I doing wrong?
$result = mysql_query("
SHOW TABLE STATUS LIKE 'Media'
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
The name of the table needed to be wrapped with single quotes like this: 'table_name'
So it works just fine now.
:)
The query should look like this:
SHOW TABLE STATUS WHERE `Name` = 'Media';
Another way, but slow, is:
SELECT AUTO_INCREMENT FROM information_schema.`TABLES` T where TABLE_SCHEMA = 'myScheme' and TABLE_NAME = 'Media';
The information_schema is mostly usefull for getting data from many schemes.
You can also use this function
function getNextValue(){
$query = "SHOW TABLE STATUS LIKE 'vendors'";
dbconnect();
$results=mysql_query($query);
if(mysql_errno() != 0) {
$result['count'] = -1;
$result['error'] = "Error: ".mysql_error();
} else {
$result['count'] = mysql_num_rows($results);
for($counter=0;$counter<$result['count'];$counter++) {
$result[$counter] = mysql_fetch_assoc($results);
}
}
return $result[0]['Auto_increment'];
mysql_close();
}
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "database_name"
AND TABLE_NAME = "table_name";
if you need to know the next auto_increment, then it's 99% likely you're doing it wrong. instead of the getting the next auto_increment, you should just do the insert you're about to do, then use SELECT LAST_INSERT_ID() to get the auto_increment value from that insert.
if you try to guess the next auto_increment value and you have multiple users doing it at the same time, you'll frequently get the wrong value.
What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) without throwing an exception. I do not feel like parsing the results of "SHOW TABLES LIKE" et cetera. There must be some sort of boolean query?
Querying the information_schema database using prepared statement looks like the most reliable and secure solution.
$sql = "SELECT 1 FROM information_schema.tables
WHERE table_schema = database() AND table_name = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$tableName]);
$exists = (bool)$stmt->fetchColumn();
If you're using MySQL 5.0 and later, you could try:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
Any results indicate the table exists.
From: http://www.electrictoolbox.com/check-if-mysql-table-exists/
Using mysqli I've created following function. Assuming you have an mysqli instance called $con.
function table_exist($con, $table){
$table = $con->real_escape_string($table);
$sql = "show tables like '".$table."'";
$res = $con->query($sql);
return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by #jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table var is clean or even better use parameterised queries.
This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.
For mysql* I used :
if (mysqli_num_rows(
mysqli_query(
$con,"SHOW TABLES LIKE '" . $table . "'")
) > 0
or die ("No table set")
){
In PDO I used:
if ($con->query(
"SHOW TABLES LIKE '" . $table . "'"
)->rowCount() > 0
or die("No table set")
){
With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.
Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.
delimiter $$
CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
DECLARE _exists TINYINT(1) DEFAULT 0;
SELECT COUNT(*) INTO _exists
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = _table_name;
RETURN _exists;
END$$
SELECT TABLE_EXISTS('you_table_name') as _exists
As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result
$tableExists = mysqli_query("DESCRIBE `myTable`");
$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
foreach( $row as $key => $value )
{
if ( $value = BTABLE ) // BTABLE IS A DEFINED NAME OF TABLE
echo "exist";
else
echo "not exist";
}
}
Zend framework
public function verifyTablesExists($tablesName)
{
$db = $this->getDefaultAdapter();
$config_db = $db->getConfig();
$sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'";
$result = $db->fetchRow($sql);
return $result;
}
If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job. Until I discovered this, I used the 'DESCRIBE' method above. More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050
Why you make it so hard to understand?
function table_exist($table){
$pTableExist = mysql_query("show tables like '".$table."'");
if ($rTableExist = mysql_fetch_array($pTableExist)) {
return "Yes";
}else{
return "No";
}
}