Check if MySQL table exists or not [duplicate] - php

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.

Related

MySQL - Execute Select and Delete in different queries?

I was wondering how would go about executing two different queries like this:
if ($uresult->num_rows >0) {
while($urow = $uresult->fetch_assoc()) {
$rresult = mysqli_query($con,"SELECT * FROM allid WHERE postid='$oldid' AND spaceid='$newid'");
$rresult = mysqli_query($con,"DELETE FROM allid WHERE postid AND spaceid IS NULL");
$lrow = mysqli_fetch_assoc($rresult);
$tem = $lrow['postid'];
$ujson = json_encode($tem);
echo $ujson;
}
} else {
}
I know mysqli_fetch can't hold no more than one query and there are similar questions, but I can't seem to understand the answers from the other questions. If there is a question that solves this question, I apologize and will delete this one.
all other things being equal, simple dont overwrite the $rresult from select with delete:
if ($uresult->num_rows >0) {
while($urow = $uresult->fetch_assoc()) {
$rresult = mysqli_query($con,"SELECT *
FROM allid
WHERE postid='$oldid'
AND spaceid='$newid'");
mysqli_query($con,"DELETE FROM allid
WHERE postid AND spaceid IS NULL");
$lrow = mysqli_fetch_assoc($rresult);
$tem = $lrow['postid'];
$ujson = json_encode($tem);
echo $ujson;
}
} else {
}
If you have multiple queries that either rely on a result of a previous query or need to be run in order and each successfully run, you could use transactions. With transactions if one of the queries fails, you can roll back the transaction.

Remote MySQL : I Can Read Database Tables Names, But Can't Read The Rows

I just create a Remote MySQL access from my other database server (remote) and I can see tables in it :
// SHOW ALL TABLES NAME
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]} <br>" ;
}
I can also see what columns name on each tables by using this :
// SHOW COLUMNS NAME OF A TABLE
$sql = 'DESCRIBE wp_ps_product_sku';
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
echo "Column: {$row[0]} <br>" ;
}
but why I can't see any rows inside each table?
$sql = 'SELECT * wp_ps_product_sku';
$result = $conn->query($sql);
print_r($result);
it always gives me an empty result. for any tables. same result. it's always empty. what did I missed here? is it possible that server just give me an access to read the database structure only, but not the data?
thank you.
On your select statement, you are missing the 'from' clause.
select * from wp_ps_product_sku;

run insert query after select query mysql in php

i am trying to insert into multi table after select query return 0 (not found raws) select query working and insert query never done when submite "displayid" and there is no any syntax error
code:
<?php
if ($_POST["displayid"] == TRUE) {
$sqlid = "SELECT * FROM doc1 WHERE idnum ='$pidnum' AND stats='$ok'";
$result = mysqli_query($conn, $sqlid);
if (mysqli_num_rows($result) > 0) {
$sqlup = "UPDATE doc1 SET m_phone='$pm_phone', seen='$dataseen' WHERE idnum ='$pidnum'";
mysqli_query($conn, $sqlup);
$found = 1;
} else {
$found = 0;
$sqlfail = "INSERT INTO fail(fname,lname,tname,funame,idnum,m_phone,reg_date)
VALUES ('$pfname','$plname','$ptname','$pfuname','$pidnum','$pm_phone','$todaydate')";
$conn->query($sqlfail)
}
}
?>
Use this code:
$sqlfail = "INSERT INTO fail(fname,lname,tname,funame,idnum,m_phone,reg_date)
VALUES ('".$pfname."','".$plname."','".$ptname."','".$pfuname."','".$pidnum."','".$pm_phone."','".$todaydate."')";
make similar changes for update command as well
you actually have one error
$conn->query($sqlfail)
should be
$conn->query($sqlfail);
AND stats='$ok'";
i can't see a variable with this name i think you mean AND stats='ok'";

search entire table except date fields using mysql and php

I have a large table and would like to search all of the fields in one go but some of the fields are dates so the search I have created falls over when it hits those fields.
Is there a way to exclude certain types of fields when using this type of search?
$table = 'accounts';
$condition = 'tracey';
$sql = "SHOW COLUMNS FROM accounts";
$result = mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0)
{
$i=0;
while ($row = mysqli_fetch_array($result))
{
if($i==0)
{
$q="select * from ".$table." where ".$row[0]." LIKE %".$condition."%";
}
else
{
$q.=" or ".$row[0]."="." LIKE %".$condition."%";
}
$i++;
}
}
$sql = $q;
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
$row = mysqli_fetch_array($result);
$answer = $row['phone_office'];
echo '<br><br>answer = '.$answer;
Or perhaps someone can suggest a better way of searching all of the fields in a table in one go?
To exclude certain types of fields You need to change the query SHOW COLUMNS FROM accounts with this one:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE (table_name=".$table.")AND(NOT(DATA_TYPE IN ('field_type_1','field_type_2',...)));
Where field_type_i is the name of an excluded type (for example 'timestamp')

Simple mysql Query to check if row exist

I want to show user if he liked a image or not..
for that I am creating php code
$userid=$_COOKIE['userid'];
$sql = "SELECT * FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
if($row){
echo "unlike";
}
else{
echo "like";
}
I can not do this for everything like 'tags', 'shares', 'comments', 'favourites' ...many
Isn't there anything simpler than this...?
Like say $row_check=mysqli_check_exist($table,$column_name,$userid);
use mysql fetch row method
$num_row = mysqli_num_rows($query);
if($num_row>0)
{
//add your code
}
else
{
//add your code
}
There are a lot of ways of doing this really but if you arnt going to use any more information then weither or not the user has liked it doing select * is a bad idea. The reason why is that you are asking the database to return the value of every column in that table.
Assuming its a small database its probably not a problem no but as your database gets bigger you are puting more load on it then you need you should try and only select the columns you need and intend to use. Ok in this case the userid is probably indexed and its only one row, but if you get in the habit of doing it here you may do it else where as well.
try this instead.
$userid=$_COOKIE['userid'];
$sql = "SELECT count(user_id) as total FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
if( $row ['total'] > 0){
echo "unlike";
}
else{
echo "like";
}
This way we are just getting the total. simple and elegant
Use mysqli_num_rows($query) if > 0 exist
You simply need to count the available records using
mysqli_num_rows($query);
This will return a number (count) of available records
So simple put a check like this :
$userid=$_COOKIE['userid'];
$sql = "SELECT * FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$count = mysqli_num_rows($query);
if($count>0){
echo "unlike";
}
else{
echo "like";
}

Categories