3

I want to create table by app if there's no such table. But doing it for the first time... Need some help, tho

 //connecting...
$mysqli = new mysqli($db_params['host'], $db_params['login'],   $db_params['pass'], $db_params['name']);

if ($mysqli->query("SHOW TABLES LIKE `products`")){
echo ' YES';
} else echo 'no'; 

It always says NO.

4 Answers4

5

Read their documentation? https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html Seems like you can do that easily:

CREATE TABLE IF NOT EXISTS `products`

This way you don't have to check first whether a table exists or not, you just create one if it doesn't.

And it seems like you have a syntax error, which is probably the reason why your code keeps returning "no". This should work:

SHOW TABLES LIKE 'products';

Just use single or double quotes, no backticks like `.

You use backticks (`) for table and column names, single (') or double quotes (") for strings, in this case you are giving a string so you should use single or double quotes.

Erik van de Ven
  • 4,747
  • 6
  • 38
  • 80
2

Use PHP DESCRIBE statement.

if(mysql_query("DESCRIBE `table_name`")) {
    // Exists
}
Hiren Makwana
  • 1,976
  • 2
  • 13
  • 28
1

In order to create a table if it not exists, you can use

CREATE TABLE IF NOT EXISTS
jophab
  • 5,356
  • 14
  • 41
  • 60
-1

This solution works for me JUST FINE:

<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');

// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

// SQL query
$sql = "SHOW TABLES IN `tests`";

// perform the query and store the result
$result = $conn->query($sql);

// if the $result not False, and contains at least one row
if($result !== false) {
  // if at least one table in result
  if($result->num_rows > 0) {
    // traverse the $result and output the name of the table(s)
    while($row = $result->fetch_assoc()) {
      echo '<br />'. $row['Tables_in_tests'];
    }
  }
  else echo 'There is no table in "tests"';
}
else echo 'Unable to check the "tests", error - '. $conn->error;

$conn->close();
?>

For a complete and more examples, here the source : http://coursesweb.net/php-mysql/check-table-exists-database_t

Soufiane ROCHDI
  • 1,543
  • 17
  • 24