2011-12-28 72 views
2

我不明白为什么这不起作用。它说“添加备注”,但它实际上并没有将其添加到数据库中。mysql插入故障

<?php 

    $notetitle = $_POST['title']; 
    $notebody = $_POST['body']; 

if ($notetitle && $notebody){ 
mysql_query("insert into notes values 
('$user_id', '', '$subject', '$notetitle', '$note_type' '$notebody')"); 

echo "Note \"" . $notetitle . "\" added."; 
} 

>

+1

请注意,一旦它进入if($ notetitle ...),它将始终执行回显,即使它没有被插入。 – Nobita

+0

不要忘记保护自己免受mysql注入(使用mysql_real_escape_string()http://php.net/manual/en/function.mysql-real-escape-string.php)。 – s3v3n

回答

7

你错过了一个逗号:

('$user_id', '', '$subject', '$notetitle', '$note_type', '$notebody')"); 
+0

这样做。谢谢! –

0

你的SQL查询是不是很有效的 - 你还必须添加到它要设置列名?通过INSERT

mysql_query("insert into notes (id, smth, subject, ... etc) values 
('$user_id', '', '$subject', '$notetitle', '$note_type', '$notebody')"); 
+0

如果您为所有列提供值,则不是强制性的。 – s3v3n

+0

@ s3v3n - 你是对的,但在我看来**明显优于暗示** – user1118250

+0

是的,我同意你的看法,明确的更好。只是想提一下,你说“你还必须补充”,这意味着“强制性”而不是“更好”(即使它是)。无论如何,我认为我们清理了足够的东西。 – s3v3n

1

你有一些mista kes在你的代码中。使用下面的代码并检查它。之前在你的MySQL查询“$ notebody”你忘了逗号

<?php 

$notetitle = $_POST['title']; 
$notebody = $_POST['body']; 

if ($notetitle != '' && $notebody !='') { 
    $myQuery = mysql_query("INSERT INTO notes VALUES 
          ('$user_id', '', '$subject', '$notetitle', 
          '$note_type', '$notebody')"); 

    // verify your database query and then show the message below 
    if (mysql_affected_rows()) { 
     echo "Note \"" . $notetitle . "\" added."; 
    } 
} 

?> 

讲究:我已经添加了更多的东西,以确保你的数据的准确性。

0

如果您检查是否插入工作,并报告了失败,那么你就会知道为什么它不工作的错误....

if ($notetitle && $notebody){ 
     $qry="insert into notes values 
      ('$user_id', '', '$subject', '$notetitle', '$note_type' '$notebody')"; 
     if (mysql_query($qry)) { 
      echo "Note \"" . $notetitle . "\" added."; 
     } else { 
      print "Failed: $qry\n" . mysql_error(); 
     } 
} 

不处理错误和异常是非常不好的编程。不要在插入语句中声明您的列是非常不好的做法。不使用明确的数据库句柄是凌乱的。不评论你的代码是不好的做法。

0

你已经错过之间“‘$ note_type’‘$ notebody’”一个逗号,

在更好的方法,你应该写这样的:=

$notetitle = $_POST['title']; 
    $notebody = $_POST['body']; 

if ($notetitle && $notebody){ 
mysql_query("insert into notes 
set userid='$user_id', 
subject = '$subject', 
notetitle = '$notetitle', 
note_type = '$note_type', 
notebody = '$notebody' "); 

} 

其实也不会发生冲突的列名称和值。 :)