17

我有以下代码:

$db_host = 'localhost';
$db_port = '3306';
$db_username = 'root';
$db_password = 'root';
$db_primaryDatabase = 'dsl_ams';

// Connect to the database, using the predefined database variables in /assets/repository/mysql.php
$dbConnection = new mysqli($db_host, $db_username, $db_password, $db_primaryDatabase);

// If there are errors (if the no# of errors is > 1), print out the error and cancel loading the page via exit();
if (mysqli_connect_errno()) {
    printf("Could not connect to MySQL databse: %s\n", mysqli_connect_error());
    exit();
}

$queryCreateUsersTable = "CREATE TABLE IF NOT EXISTS `USERS` (
    `ID` int(11) unsigned NOT NULL auto_increment,
    `EMAIL` varchar(255) NOT NULL default '',
    `PASSWORD` varchar(255) NOT NULL default '',
    `PERMISSION_LEVEL` tinyint(1) unsigned NOT NULL default '1',
    `APPLICATION_COMPLETED` boolean NOT NULL default '0',
    `APPLICATION_IN_PROGRESS` boolean NOT NULL default '0',
    PRIMARY KEY  (`ID`)
)";

if(!$dbConnection->query($queryCreateUsersTable)){
    echo "Table creation failed: (" . $dbConnection->errno . ") " . $dbConnection->error;
}

哪个输出...

Table creation failed: (1050) Table '`dsl_ams`.`USERS`' already exists

我不明白的是:IF NOT EXISTS如果该表已经存在,不应该取消 SQL 查询的执行吗?换句话说,如果表存在,它不应该退出该 if 语句并且根本不回显任何内容,并且不尝试执行查询吗?

只是试图找到“如果表不存在则创建表”而不向用户输出任何内容的最佳方法。

4

5 回答 5

23

尝试这个

$query = "SELECT ID FROM USERS";
$result = mysqli_query($dbConnection, $query);

if(empty($result)) {
                $query = "CREATE TABLE USERS (
                          ID int(11) AUTO_INCREMENT,
                          EMAIL varchar(255) NOT NULL,
                          PASSWORD varchar(255) NOT NULL,
                          PERMISSION_LEVEL int,
                          APPLICATION_COMPLETED int,
                          APPLICATION_IN_PROGRESS int,
                          PRIMARY KEY  (ID)
                          )";
                $result = mysqli_query($dbConnection, $query);
}

这将检查表中是否有任何内容,如果返回则表示NULL您没有表。

BOOLEANmysql 中也没有数据类型,您应该INT在插入表时将其设置为 1 或 0。您也不需要在所有内容中加上单引号,仅当您将数据硬编码到查询中时。

像这样...

$query = "INSERT INTO USERS (EMAIL, PASSWORD, PERMISSION_LEVEL, APPLICATION_COMPLETED, APPLICATION_IN_PROGRESS) VALUES ('foobar@foobar.com', 'fjsdfbsjkbgs', 0, 0, 0)";
于 2013-05-15T00:19:20.723 回答
4

为避免输出任何内容,请在尝试创建表之前在 php 中测试该表。例如,

$querycheck='SELECT 1 FROM `USERS`';

$query_result=$dbConnection->query($querycheck);

if ($query_result !== FALSE)
{
 // table exists
} else
{
// table does not exist, create here.
}
于 2013-05-15T00:14:34.817 回答
1

这篇旧帖子只是展示了不良做法和不一致的答案。遗憾的是,将其作为骗子关闭不会对公众关闭,它会继续执行其虚假信息任务。

简短的事实核查:

  • 如果您的系统没问题,那么CREATE TABLE IF NOT EXISTS 应该可以工作。
  • 万一有鬼表,参考这个帖子解决办法
  • 检查表是否存在,永远不要从表中选择任何东西,这会导致错误
    • (但是,与许多评论中表达的错误概念相反,空表不会返回空结果。空结果意味着错误。要检查您的查询是否返回任何行,您必须获取它们)
  • 相反,运行一个SHOW TABLES LIKE 'Users'查询,将该行提取到一个变量中并查看它是否为空。
于 2020-06-11T10:53:26.787 回答
-1

这将连接到 mysql 检查数据库是否存在。如果是,它将检查表是否存在。如果它们都不存在,它将自动创建它。

$servername = "hostname";
    $username = "username";
    $password = "password";
    $dbname = "database_name";
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }

// Create database
$sql = "CREATE DATABASE IF NOT EXISTS database_name";
if ($conn->query($sql) === TRUE) {
  $conn = new mysqli($servername, $username, $password, $dbname);
  // Check connection
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }
  $sql1 = "CREATE TABLE IF NOT EXISTS Users (ID int(11) AUTO_INCREMENT,
                      EMAIL varchar(255) NOT NULL,
                      PASSWORD varchar(255) NOT NULL,
                      PERMISSION_LEVEL int,
                      APPLICATION_COMPLETED int,
                      APPLICATION_IN_PROGRESS int,
                      PRIMARY KEY  (ID))";
  if($conn->query($sql1) === TRUE) {
    echo "Database and Table Online";
  }else{
    echo "Database and Table Offline" . $conn->error;
  }
} else {
  echo "Error creating database: " . $conn->error;
}

$conn->close();
于 2020-06-11T10:33:50.570 回答
-2

如果错误号不是 1050,您如何只显示错误?

if(!$dbConnection->query($queryCreateUsersTable)){
  if($dbConnection->errno != 1050){
    echo "Table creation failed: (" . $dbConnection->errno . ") " . $dbConnection->error;
  }
}
于 2016-11-02T14:28:46.357 回答