2012-11-21 88 views
3

我已經嘗試多次插入數據庫。這些值包含單引號 - 關閉了魔術引號,addslashes()和mysql_real_escape_string()都會轉義字符,但腳本在不添加數據庫的情況下死亡。我也手動逃脫,但也失敗了。但是,即使刪除撇號,腳本仍然死亡。MYSQL_INSERT不能正常工作

錯誤是:無法插入工作人員:您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'11,Hazel,Blonde,從未錯過任何一天的工作,使用正確的語法,從伯克利畢業,服務'在線2 任何人都看到任何問題?

<?php 
include('header.php'); 

$amount = 1; 
$staffnum = '0101'; 
$height = array("5'11", "5'4", "6'2","5'5", "6'4"); 
$eye = array("Blue","Green","Hazel","Brown"); 
$hair = array("Brown", "Black", "Blonde", "Red"); 
$about1 = "Has never missed a day of work"; 
$about2 = "Graduated from Berkley"; 
$positions = array('Server, Bartender', 'Bartender, Host', 'Sever, Host, Bartender', 'Cocktail Server, Bartender, Server'); 
$img = "none"; 
// arrays 
$times = 1; 


while($times <= 50) { 
$staffnum ++; 
$heighta = mysql_real_escape_string($height[array_rand($height)]); 
$eyea = mysql_real_escape_string($eye[array_rand($eye)]); 
$haira = mysql_real_escape_string($hair[array_rand($hair)]); 
$positionsa = mysql_real_escape_string($positions[array_rand($positions)]); 
$about1 = mysql_real_escape_string($about1); 
$about2 = mysql_real_escape_string($about2); 
$img = mysql_real_escape_string($img); 
$staffnum = mysql_real_escape_string($staffnum); 

$insert_staff = "INSERT INTO staff (staffnum, img_link, height, eye, hair, abt1, abt2, titles) 
VALUES ($staffnum, $img, $heighta, $eyea, $haira, $about1, $about2, $positionsa)"; 

$insert_query = mysql_query($insert_staff); 

if($insert_query) { 
    ?> 

<center> 
    Member # <?php echo $staffnum; ?> has been added to the database.<br /> 
    <?php 
} else { 

    die('Could not insert staff: ' . mysql_error()); 

} 

$times ++; 
} 

include('footer.php'); 
?> 
    <a href="staff_insert.php?page=1">Return To Staff Insert</a> 
</center> 
+1

你需要引用您的非數字字段。但是你一定要看看使用PDO或者mysqli--它們都會幫你編寫更安全的代碼。 – andrewsi

+0

請遠離'mysql_query'。不要使用這個危險的,不贊成使用的界面編寫代碼。 [PDO](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/)需要三十分鐘才能完成,而且相當可觀更容易和更安全的使用。 – tadman

回答

2

你需要把你插入字符串變量各地報價:

$insert_staff = "INSERT INTO staff (staffnum, img_link, height, eye, hair, abt1, abt2, titles) 
VALUES ('$staffnum', '$img', '$heighta', '$eyea', '$haira', '$about1', '$about2', '$positionsa')"; 
+1

菜鳥錯誤:)非常感謝! –

-1

時要與基本的mysql_query要找這麼多的變量,這是一個有點複雜。 你應該嘗試PDO或mysqli的,但如果你需要使用你的代碼,它應該更像

$insert_staff = "INSERT INTO staff (staffnum, img_link, height, eye, hair, abt1, abt2, titles) 
VALUES ('".$staffnum."', '".$img."', '".$heighta."', '".$eyea."', '".$haira."', '".$about1."', '".$about2."', '".$positionsa."')"; 
+0

這將起作用,但Elec已經在所有要插入的值上使用了'mysql_real_escape_string()',所以不需要使用雙引號來保護包含單引號的字符串。這就是說,PDO或mysqli當然會是一個更好的方法。 – sgroves

+0

如果你只是在進行字符串連接,讓雙引號爲你做他們的事情。這是需要消滅的反模式。 – tadman