简体   繁体   English

PHP和MySQLi检查表是否存在以及是否不创建表

[英]PHP and MySQLi check to see if the table exists and if it doesn't create it

Attempting to use this to check to see if the table exists and if it doesn't create it 尝试使用此方法检查表是否存在以及是否不创建表

if ( !f_tableExists($table, DB_NAME) ) {
    $sql = "CREATE TABLE $table (
        ID int NOT NULL AUTO_INCREMENT,
        PRIMARY KEY(ID),
        timestamp int NOT NULL,
        ip int NOT NULL
    )";

    $result = mysqli_query($sql);

    if (!$result) {
        die('Invalid query: ' . mysqli_error());
    }

}

where f_tableExists does the following to check if it exists. f_tableExists执行以下操作以检查其是否存在。

function f_tableExists($tablename, $database = false) {

if(!$database) {
    $res = mysqli_query("SELECT DATABASE()");
    $database = mysqli_data_seek($res, 0);
}

$res = mysqli_query("
    SELECT COUNT(*) AS count
    FROM information_schema.tables
    WHERE table_schema = '$database'
    AND table_name = '$tablename'   
");

return mysqli_data_seek($res, 0) == 1;
}

Getting the result 'Invalid query:' 获取结果“无效查询:”

No table is being made and hence I assume some of my mysqli query code (CREATE TABLE....ip int NOT NULL) or (SELECT COUNT...= '$tablename') or another bit is wrong and/or not working? 没有表被创建,因此我假设我的某些mysqli查询代码(CREATE TABLE .... ip int NOT NULL)或(SELECT COUNT ... ='$ tablename')或其他位是错误的和/或不起作用? I don't know which bit or why? 我不知道是哪一位,为什么?

Just use query with IF NOT EXISTS without checking 只需将查询与IF NOT EXISTS而不检查

http://dev.mysql.com/doc/refman/5.5/en/create-table.html http://dev.mysql.com/doc/refman/5.5/en/create-table.html

  $sql = "CREATE TABLE IF NOT EXISTS $table (
        ID int NOT NULL AUTO_INCREMENT,
        PRIMARY KEY(ID),
        timestamp int NOT NULL,
        ip int NOT NULL
    )";

Also, need pass connection into mysqli_query 另外,需要将连接传递到mysqli_query

PS relative joke: http://www.bash.org/?725783 PS相对笑话: http : //www.bash.org/?725783

hey this how you could have done it: 嘿,这本来可以做到的:

create a mysqli php connection: 创建一个mysqli php连接:

<?php
$__DATABASE__='centralfeed_feed';
$__USER__='root';
$__PASSWORD__='';
$__HOST__='localhost';

$con=mysqli_connect($__HOST__,$__USER__,$__PASSWORD__,$__DATABASE__);

?>

then make the mysqli request to database: 然后向数据库发出mysqli请求:

<?php

     if(mysqli_query($con,"DESCRIBE  users ")){
        echo "exists";
    }else{
        echo "dont exists";
    }
    mysqli_close($con);
    exit;
 ?>

then your done !! 然后你完成了!

Always remember to close connection when ever your done using them or note using them connections not just in php mysqli but all the time(in other languages as well). 永远记得在使用完它们后关闭连接,或者注意使用它们的连接不仅在php mysqli中,而且始终(在其他语言中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM