2012-11-21 41 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