简体   繁体   English

检查MySQL中是否存在表

[英]Check if a table exists in mysql

I am trying to check if a table exists, and in that table if a record is available, using mysql in codeigniter. 我正在尝试在codeigniter中使用mysql检查表是否存在以及该表中是否有记录。 Here is the function I tried but, id doesn't work. 这是我尝试过的功能,但id不起作用。

function isRowExist($table, $id)
{
    if(mysqli_query("DESCRIBE {$table}")) {
        $query = $this->db->query("SELECT * FROM {$table} WHERE id = '{$id}'");
    }
    return $query->num_rows();
}

Any help would be appreciated. 任何帮助,将不胜感激。

You can try this codeigniter function to check table already exist. 您可以尝试使用此codeigniter函数来检查表是否已存在。

   if ($this->db->table_exists('tbl_user')) {
        // table exists (Your query)
    } else {
        // table does not exist (Create table query)          
    }

You can check whether table exists or not by this function : 您可以通过此功能检查表是否存在:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

Use this code to check table exists or not in codeigniter 使用此代码检查表在codeigniter中是否存在

$this->db->table_exists();

You can use this with with conditional statements. 您可以将其与条件语句一起使用。

if ($this->db->table_exists('table_name'))
{
     // some code...
} else {
     // not exist
}

This code may help: 此代码可以帮助:

include 'connection.php';
function createSignupTable()
{
  $conn = $GLOBALS['conn'];
  $error = array('message1' =>'Table created successfuly' , 'message2'=>'Problem creating the table');
  if($conn == true)
  {
    $result = $conn->query("SHOW TABLES LIKE 'signuptable'");
    if($result->num_rows == 1){
        echo "table exists";
    }else{  
        $create_table1 = 'CREATE TABLE signuptable(
            cs_user_id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
            firstname VARCHAR(200) NOT NULL,
            lastname VARCHAR(200) NOT NULL,
            username VARCHAR(200) UNIQUE KEY NOT NULL,
            AKA VARCHAR(200) UNIQUE KEY NOT NULL,
            password VARCHAR(200) NOT NULL,
            email VARCHAR(200) NOT NULL,
            phone_number VARCHAR(200) NOT NULL,
            Date_signed_up TIMESTAMP
        )';
        $query_1 = $conn->query($create_table1);
        if($query_1 == true){
            echo $error["message1"];
        }else{
            die($conn->error);
        }
    }
  }
}
createSignupTable();

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

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