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";
}
}
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 have this query I can run against my db and it works fine. However when I try it in the PHP version I get 0 results. I'm missing something fundamental, I just can't tell what it is.
Query
SELECT *
FROM table_admin_20
WHERE column1 = '0607'
PHP
$store_info_query = "SELECT * FROM '".$table_name."' WHERE 'column1' = '".$store_number."'";
if ($query_run = mysql_query($store_info_query)) {
if (mysql_num_rows($query_run) == NULL) {
$response["success"] = 0;
echo json_encode($response);
echo 'nope';
} else {
while ($row = mysql_fetch_assoc($query_run)) {
$store_info = $row['column1'];
echo '1111111';
echo $store_info;
}
}
} else {
echo 'fail';
}
I know I have 0 protection against SQL injection, I'm merely trying to pull data, this is in no way live yet. Anyways, I get the 'fail' response each time. Thanks for any help.
Don't add security as an afterthought, just switch to PDO or mysqli and use prepared statements so that you don't have to worry about the values any more. In case of table- or column names, you would need to use white-lists though.
The cause of your problem is that you are quoting your table- and field names. If you need to escape them, use backticks:
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
You've to replace ' with ` for the table and column names. ' is just for values. Try this:
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
Please avoid using * and rethink your security-strategies. As already mentioned, take a look at PDO: http://php.net/manual/en/book.pdo.php
You are putting wrong quotes around table name and column name. Try this
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
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";
}
I am trying to add a column by checking if it exists. If not it should give message that it already exists with the code below.
$prefix = 'vm_';
$col_name = 'checking';
$col = "SELECT ".$col_name." FROM ".$prefix."users";
if (!$col){
$insert_col = "ALTER TABLE ".$table." ADD ".$col_name." DATETIME NOT NULL";
mysql_query($insert_col);
echo $col_name.' has been added to the database';
} else {
echo $col_name.' is already exists';
}
But it doesn't add any column and directly displays message that the column already exists.
You never execute your query, your condition is instead your query string:
if (!$col) { //always false, since a nonempty string is always truthy
Here is the final code. There was stupid mistake; I didn't use mysql_query for $col
$prefix = 'vm_';
$col_name = 'checking';
$col = mysql_query("SELECT ".$col_name." FROM ".$prefix."users");
if (!$col){
//$insert_col = "ALTER TABLE ".$table." ADD ".$col_name." DATETIME NOT NULL";
mysql_query("ALTER TABLE ".$prefix."users ADD ".$col_name." DATETIME NOT NULL");
echo $col_name.' has been added to the database';
} else {
echo $col_name.' is already exists';
}
You have to run your query before you check statements with it. It's like you can't see whether the box is empty of not (i.e. result of your query) without opening the box (i.e. running the query)
Replace your line 04 with this
$col = mysql_query("SELECT ".$col_name." FROM ".$prefix."users");
Then your problem will be solved
For more information on mysqli, please read this article
You might consider moving on to PDO statements as well.
Hope this helps
You haven't executed your query. First execute your query, then check the condition on it.
This is what I did and it works:
$db= new mysqli('host','user','password','db');
$query = "SHOW COLUMNS FROM tablename LIKE 'columnname'";
$db->query($query);
if(empty(empty($db->num_rows)) {
$alter = "ALTER TABLE tablename ADD columnname varchar(50) NOT NULL";
$db->query($alter);
} else {
echo 'column exists';
}
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.