2013-04-11 129 views
1

我試圖用MYSQLi在數據庫中插入數據。如果我使用以下查詢,則插入數據;SQLi INSERT語句

"INSERT INTO table (Name, Phone, Location) VALUES ('test', 'test', 'test')" 

而不是值'測試',我需要插入一個變量的值。但以下方法無效。

$test = 'xxx'; 
if ($stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (". $test.", 'aaa', 'bbb')")) { 
    $stmt->execute(); 
    $stmt->close(); 
} 

我試過「bind_param」命令,但它沒有工作。

$stmt->bind_param("ss", $name, $phone, $location); 

如何直接插入變量?謝謝。

回答

2

在你的情況下,代碼應該是這樣的:

$test = 'xxx'; 

$stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (?, 'aaa', 'bbb')"); 
$stmt->bind_param("s", $test); 
$stmt->execute(); 
$stmt->close(); 

如果你想擁有此查詢3個變量:

$name = "My name"; 
$phone = "My phone number"; 
$location = "My location"; 

$stmt = $mysqli->prepare("INSERT INTO table (Name, Phone, Location) VALUES (?, ?, ?)"); 
$stmt->bind_param("sss", $name, $phone, $location); 
$stmt->execute(); 
$stmt->close(); 
+1

所以這是我一直在做的錯誤。我需要三個「s」,因爲有三個字符串。非常感謝。將盡快接受答案。 – user1334130 2013-04-11 09:52:56