2017-02-22 117 views
0

我想检查一个表是否存在,并在该表中是否有可用的记录,在codeigniter中使用mysql。 这是我试过的功能,但是,id不起作用。检查一个表是否存在于mysql中

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

任何帮助,将不胜感激。

+1

的可能的复制[MySQL的 - 检查表是否存在,而无需使用 “从选择”(http://stackoverflow.com/questions/8829102/mysql- check-if-table-exists-without-using-select-from) – jitendrapurohit

+0

如果一个表没有被定义,它将不会进入循环,并且它会抛出错误undefined query ..让它通过然后查询可能会因ID而失败。 –

回答

2

你可以试试这个codeigniter函数来检查表是否已经存在。

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

您可以检查此功能表是否存在:

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

使用此代码来检查表存在或不笨

$this->db->table_exists(); 

您可以用条件语句使用。

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

此代码可以帮助:

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();