2014-10-26 65 views
0

我有这个代码,但我不能让它插入我的SQL表中的任何东西? 回声部分工作正常..插入表不工作

/* We have succesfully resized and created thumbnail image 
We can now output image to user's browser or store information in the database */  
$s_id = $_GET['id']; 
$conn = mysqli_connect('localhost', 'user', 'pass', 'table'); 
$query = "INSERT INTO table (sp_s-id, sp_thump, sp_orig) VALUES 
('$s_id', '$thumb_save_folder', '$image_save_folder')"; 
//added $conn variable in order to connect to our database. 
mysqli_query($conn, $query); 
mysqli_close($conn); 
echo '<div align="center">'; 

echo '<img src="uploads/'.$thumb_prefix . $new_file_name.'" >alt="Thumbnail">'; 
echo '<br />'; 
echo '<img src="uploads/'. $new_file_name.'" alt="Resized Image">'; 
echo $s_id; 
echo '</div>'; 
imagedestroy($image_res); //freeup memory 
+3

这是连字符'sp_s,id' - SQL将其翻译为“sp_s ** MINUS ** id” - 在列名称周围使用反引号。将'或者死(mysqli_error($ conn))'添加到'mysqli_query()'中,你会明白我的意思。另外,我希望'table'不是真正的/实际的名字。如果是这样,也可以用反引号包起来;这是一个保留字。 – 2014-10-26 13:50:38

+1

你的专栏真的叫做“sp_thump”而不是“sp_thumb”? – Ali 2014-10-26 13:52:22

+0

^^^可能是一个错字,从来不知道。我没有为此回答这个问题。在评论中保持安全。 – 2014-10-26 13:52:57

回答

1

替换此:

$query = "INSERT INTO table (sp_s-id, sp_thump, sp_orig) VALUES 
    ('$s_id', '$thumb_save_folder', '$image_save_folder')"; 

有了这个:

$query = "INSERT INTO `table` (`sp_s-id`, `sp_thump`, `sp_orig`) VALUES 
    ('$s_id', '$thumb_save_folder', '$image_save_folder')"; 

SQL服务器(以及PHP或大多数其他语言)不能用减号处理列/表/变量名( - ),所以你需要把它们放在引号/蜱中。尽管遵循规则[_A-Za-z][0-9_A-Za-z]*的列/表格/变量名称(仅表示数字,字符(A-Z)和下划线,但不以数字开头),但强烈推荐。

此外,你应该总是验证或类型转换用户的输入,像这样(验证):

$s_id = $_GET['id']; 
if (!is_numeric($s_id)) { 
    // invalid input/possible hacking attempt? 
} 

还是这个(类型强制转换):

$s_id = (int) $_GET['id']; 
+2

欢迎使用我在['我的评论'](http://stackoverflow.com/questions/26573657/insert-into-table-doesnt-work#comment41765108_26573657)中所说的“为什么”它失败了,为什么OP不检查错误。 – 2014-10-26 13:55:13

+1

回复赞助商@ Fred-ii- – Kypros 2014-10-26 13:56:51

+0

@Kypros LOL!好一个:)爱它。 – 2014-10-26 13:57:21

-2

你的语法错了。尝试这个。

如果你不使用面向对象的模式,我建议在mysqli上使用mysql。

$conn = mysql_connect('localhost', 'username', 'password'); 
$db = mysql_select_db('databasename', $conn); 



$query ="INSERT INTO tablename (sp_s-id, sp_thump, sp_orig) VALUES ('{$s_id}', '{$thumb_save_folder}', '{$image_save_folder}')"; 

$result = mysql_query($query); 

mysql_close($conn); 

试试这个。它应该插入到表中。确保在双引号内使用变量时{}。

+0

他的语法很好。让你的PHP挺直。 :P – Ali 2014-10-26 13:51:22

+0

我认为它不是,它也适用于xampp也用单引号围绕变量在双引号中加上一个变数 – 2014-10-26 13:53:21

+0

nope did not帮助 – 2014-10-26 13:53:46