· 6 years ago · Jul 04, 2019, 07:34 AM
1select 1 from your_table
2
3/**
4 * Check if a table exists in the current database.
5 *
6 * @param PDO $pdo PDO instance connected to a database.
7 * @param string $table Table to search for.
8 * @return bool TRUE if table exists, FALSE if no table found.
9 */
10function tableExists($pdo, $table) {
11
12 // Try a select statement against the table
13 // Run it in try/catch in case PDO is in ERRMODE_EXCEPTION.
14 try {
15 $result = $pdo->query("SELECT 1 FROM $table LIMIT 1");
16 } catch (Exception $e) {
17 // We got an exception == table not found
18 return FALSE;
19 }
20
21 // Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
22 return $result !== FALSE;
23}
24
25SHOW TABLES LIKE 'some_table_of_mine';
26
27SELECT TABLE_NAME FROM ALL_TABLES
28
29SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'mydbname'
30
31$tableExists = gettype($dbh->exec("SELECT count(*) FROM $table")) == 'integer';
32
33@$this->load->database();
34$v = @$this->db->version()
35$tables = @$this->db->list_tables();
36
37function DB_table_exists($db, $table){
38 GLOBAL $db;
39 try{
40 $db->query("SELECT 1 FROM $db.$table");
41 } catch (PDOException $e){
42 return false;
43 }
44 return true;
45}
46
47$string = "CREATE TABLE IF NOT EXISTS " .$table_name . " int(11) NOT NULL AUTO_INCREMENT,
48 `id` int(3) NOT NULL,
49 `blabla` int(2) NOT NULL,
50 `blabla1` int(2) NOT NULL,
51 `blabla3` varchar(3) NOT NULL,
52 PRIMARY KEY (`id`),
53 UNIQUE KEY `id` (`id`)
54) ENGINE=InnoDB DEFAULT CHARSET=latin1
55AUTO_INCREMENT=1 ";
56
57$sql = $conection->prepare("$string");
58$sql->execute();
59
60/**
61 * This function checks if the table exists in the passed PDO database connection
62 * @param PDO $pdo - connection to PDO database table
63 * @param type $tableName
64 * @return boolean - true if table was found, false if not
65 */
66function tableExists(PDO $pdo, $tableName) {
67 $mrSql = "SHOW TABLES LIKE :table_name";
68 $mrStmt = $pdo->prepare($mrSql);
69 //protect from injection attacks
70 $mrStmt->bindParam(":table_name", $tableName, PDO::PARAM_STR);
71
72 $sqlResult = $mrStmt->execute();
73 if ($sqlResult) {
74 $row = $mrStmt->fetch(PDO::FETCH_NUM);
75 if ($row[0]) {
76 //table was found
77 return true;
78 } else {
79 //table was not found
80 return false;
81 }
82 } else {
83 //some PDO error occurred
84 echo("Could not check if table exists, Error: ".var_export($pdo->errorInfo(), true));
85 return false;
86 }
87}
88
89$table_name = 'your_table_here';
90$test = "SELECT 1 FROM " . $table_name . " LIMIT 1";
91$test = $db->query($test); //$db needs to be PDO instance
92
93if($test)
94{
95 return 1; //Table exists
96}
97else
98{
99 return 0; //No table in database
100}