0

I am trying to check if a table exists, and in that table if a record is available, using mysql in codeigniter. Here is the function I tried but, id doesn't work.

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.

skm
  • 1,192
  • 1
  • 11
  • 23
  • 1
    Possible duplicate of [MySQL - check if table exists without using "select from"](http://stackoverflow.com/questions/8829102/mysql-check-if-table-exists-without-using-select-from) – jitendrapurohit Feb 22 '17 at 06:04
  • If a table is not defined .. it won't get in the loop and it will throw error undefined query.. lets day it pass then the query may fail because of id. – M A SIDDIQUI Feb 22 '17 at 06:04

4 Answers4

5

You can try this codeigniter function to check table already exist.

   if ($this->db->table_exists('tbl_user')) {
        // table exists (Your query)
    } else {
        // table does not exist (Create table query)          
    }
Tejas Soni
  • 551
  • 3
  • 10
2

Use this code to check table exists or not in 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
}
Shashank Sharma
  • 585
  • 3
  • 14
1

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";
}
prakash tank
  • 1,269
  • 1
  • 9
  • 15
1

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();
zx485
  • 28,498
  • 28
  • 50
  • 59