2015-11-27 81 views
0

我試圖插入數據庫某種形式發佈數據,但它顯示了錯誤:PHP表單數據插入在MySQL

Error: INSERT INTO user_data (name, age, gender,happy,sad,angry) VALUES (Sourav,23,male,3.5,2.75,1.5) 
Unknown column 'Sourav' in 'field list' 

我使用的查詢:

$sql = "INSERT INTO user_data (name, age, gender,happy,sad,angry) 
VALUES (" . $name . "," . $age . "," . $gender . "," . $happyness . "," . $sadness . "," . $angryness . ")"; 
+0

永遠不要直接將用戶輸入到數據庫中查詢。至少使用某種參數轉義或mysqli/pdo來避免mysql注入。 – Sven

回答

3

你有將字符串值放在引號內。如下更新代碼。

$sql = "INSERT INTO user_data (name, age, gender,happy,sad,angry) 
VALUES ('" . $name . "','" . $age . "','" . $gender . "','" . $happyness . "','" . $sadness . "','" . $angryness . "')"; 

此外,您的代碼是不安全的。插入表單數據時使用轉義字符串。

+0

怎麼樣mysql注入? – Sven

+0

這就是爲什麼我在我的答案中提到如果插入表單數據/用戶輸入時使用轉義字符串 – AeJey

0

使用'''Sourav'

INSERT INTO user_data (name, age, gender,happy,sad,angry) 
VALUES ('Sourav','23','male','3.5','2.75','1.5') 

或類似的

$sql = "INSERT INTO user_data (name, age, gender,happy,sad,angry) 
VALUES ('$name','$age','$gender','$happyness','$sadness','$angryness')"; 
0

試試這個..,

$sql = "INSERT INTO user_data (name, age, gender,happy,sad,angry) 
VALUES ('" . $name . "','" . $age . "','" . $gender . "','" . $happyness . "','" . $sadness . "','" . $angryness . "')"; 

希望這有助於..

1

更改您的查詢:

$sql = "INSERT INTO user_data (name, age, gender,happy,sad,angry) 
VALUES ('$name','$age','$gender','$happyness','$sadness','$angryness')"; 
0

你真的應該看看和mysqli或pdo擴展 - 或者至少是使用某種類型的引用您的參數,像mysql_real_escape_string。直接將用戶輸入傳遞給數據庫查詢可以很容易地用於mysql注入。

使用PDO你可以寫你這樣的代碼:

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password'); 
$name = 'BOB'; 
$password = 'badpass'; 
$stmt = $db->prepare("INSERT INTO table(`hexvalue`, `password`) VALUES(HEX(?), PASSWORD(?))"); 
$stmt->execute(array($name, $password));