更新查询有效但不插入查询

时间:2015-01-23 06:42:46

标签: php mysql

我在将信息插入数据库时​​遇到问题。奇怪的是,更新查询有效,但不是插入查询。我在提交时没有收到任何错误,它会正确完成并且回复帐户已保存但未插入任何内容。我错过了什么或做错了什么。请协助

if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';

unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);

$notmust = array("email" , "skip" , "comments" , "firstmod");

foreach($_POST as $key=>$val){
    if(!trim($val) && !in_array($key , $notmust)) {
        $err = 1;
        $empty = "$key";
        break;
    }
    $qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);

if(!$err){
    $chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
    if($chk >0){
        $err = 2;
    }
}

if(!$err){
    if(!$accountid){
        $q = "INSERT into accounts SET $qpart ";
        mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
        $accountid = mysql_insert_id();
    }else{
        $q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
        mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
    }
}

3 个答案:

答案 0 :(得分:3)

这是因为INSERT命令具有不同的语法:

INSERT into accounts SET $qpart "

不常见,你可以这样写:

INSERT into accounts (column names) VALUES your values"
  

13.2.5 INSERT Syntax

答案 1 :(得分:0)

你有两倍if(!$err){。你想要两个(!$err)合而为一吗?如果第一个(!$err)用于插入第二个if(!$err){ $chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'")); if($chk >0){ $err = 2; // if(!$err){ again ... if(!$accountid){ $q = "INSERT into accounts SET (column1) VALUES ($var1)"; mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q); $accountid = mysql_insert_id(); } else{ $q = "UPDATE accounts SET $qpart WHERE id = '$accountid'"; mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q); } } } else{ //other code to handle if ($err) } 指示符,则无法将函数 SELECT 置于函数 INSERT 间接之上。

试试这个:

{{1}}

注意:我更喜欢使用PDO来处理数据库,它是如此简单的脚本,此外,它不再受支持

答案 2 :(得分:0)

您必须了解mysql函数已被弃用。使用mysqli或pdo将是更好的选择,但如果你绝对必须使用mysql作为解决方案,我建议不要将表单发布到自己,而是发布到另一个php文件,因为你将有更少的问题。在我的环境中似乎在我们重写所有内容以使用mysqli时,作为一个临时解决方案工作得很好。如果它去了,请告诉我。