2016-11-07 54 views
2

我想知道如何將變量合併到PHP語句中以檢查表是否存在。出於某種原因,查詢不接受該變量。以下是我有:檢查現有表使用變量

<?php 
$servername = "localhost"; 
$username = "***"; 
$password = "***"; 
$dbname = "stavacom_students"; 

// Create connection 
$conn = mysqli_connect($servername, $username, $password, $dbname); 
// Check connection 
if (!$conn) { 
    die("Connection failed: " . mysqli_connect_error()); 
} 

$id = "1"; 
echo $id; 
$query101 = 'select 1 from "$id" LIMIT 1'; 
$val = mysqli_query($conn, $query101); 
if($val !== FALSE){ 

echo "no"; 

} else { 
?> 

what? 

<?php 
}; 
?> 
+0

你想查詢數據庫中的表是否存在? –

+0

更改''選擇1從「$ id」LIMIT 1';'到'「從$ id LIMIT 1中選擇1」;'並且它可能工作。 –

+0

而在變量'$ id'的地方,你應該使用你的表名。 –

回答

1

的語句需要to sandwich the variable because my table names were numbers. Here is the final statement: $query101 = "select 1 from $ id` LIMIT 1" ;

-1

改變這一狀況,希望它的工作

$query101 = 'select 1 from "$id" LIMIT 1'; 

這個

$query101 = 'select 1 from "'.$id.'" LIMIT 1'; 
0

您可以使用mysql以兩種方式實現此功能,第一種是簡單的SELECT FROM查詢類型:

<?php 
function mysql_table_exists(mysqli $conn, $table) 
{ 
     $res = @$conn->query('SELECT 1 FROM `' . $conn->real_escape_string($table) . '`'); 

     if($res) 
     { 
       $res->free(); 

       return true; 
     } 

     return false; 
} 
?> 

您也可以通過下面的語句執行在INFORMATION_SCHEMA檢查做到這一點:

SELECT 1 FROM information_schema.tables WHERE table_schema = '<database name>' AND table_name = '<table name>' LIMIT 1; 

最後,你可以調用SHOW TABLES LIKE '<table name>';並解析了比賽的結果,類似的概念第一個例子。

0

使用雙引號( 「...查詢...」)編輯您的查詢

$query101 = 'select 1 from "$id" LIMIT 1'; 

進入

$query101 = "select 1 from '".$id."' LIMIT 1"; 

OR

$query101 = "select 1 from $id LIMIT 1";