继续查询,但显示错误

时间:2015-02-01 18:30:15

标签: php mysql key unique

目前我有以下代码:

$editsystem_exists = "UPDATE `tbl` SET `system_customer`='{$system_customer}', `system_id`='{$system_id}' WHERE `id`='".$systemid_safe."'";
$result_editsystem_exists = mysql_query($editsystem_exists);

if (!$result_editsystem_exists) {
    echo '<font color="#66990F"><B><center>Changes Saved</B><BR>The System ID has not changed.<BR></center></font>';
    echo mysql_error();
} else {
    echo '<font color="#66990F"><B><center>Changes Saved</B><BR></center></font>';
}

system_id是一个唯一的密钥。我的问题是,即使发生错误,我希望查询继续,但如果它是重复的,则显示错误而不更新system_id。我尝试过使用@但它没有做任何事情。无论我尝试过什么,如果它显示错误,查询将停止,并且不会更新任何内容。我只是想让它跳过system_id,但只有在system_id重复时才更新其他所有内容。如果它不重复,请更新所有内容。

注意:我正在开发一个不支持mysqli或PDO的模块。我被困在使用mysql _

编辑:这是我的原始代码

在我开始玩这个之前,这是我的原始代码

    #Begin checking for an existing system id
    $system_id_check = "SELECT `system_id` FROM `tbl` WHERE `system_id`='".$system_id."'";
    $search_system_id = mysql_query($system_id_check);
    $result_check = mysql_num_rows($search_system_id);

    if($result_check !== 0){

    #Connect to the DB to get the System ID
    $query_sysid = "SELECT `id`, `system_id` FROM `tbl` WHERE `id`='".$systemid_safe."'";
    $result_sysid = mysql_query($query_sysid); if (!$result_sysid) { die('Invalid query: ' . mysql_error());}
    $row0 = mysql_fetch_array($result_sysid);

    #Update all but the System ID if it already exists
    $editsystem_exists = "UPDATE `tbl` SET `system_customer`='{$system_customer}' WHERE `id`='".$systemid_safe."'";

    mysql_query($editsystem_exists); echo '<font color="#66990F"><B><center>Changes Saved</B><BR>The System ID has not changed.</center></font>';

} else {  

    #Connect to the DB to get the System ID
    $query_sysid = "SELECT `id`, `system_id` FROM `tbl` WHERE `id`='".$systemid_safe."'";
    $result_sysid = mysql_query($query_sysid); if (!$result_sysid) { die('Invalid query: ' . mysql_error()); }
    $row0 = mysql_fetch_array($result_sysid); 

    #Update the system if the System ID does not exist  
    $editsystem = "UPDATE `tbl` SET `system_customer`='{$system_customer}', `system_id`='{$system_id}' WHERE `id`='".$systemid_safe."'";

    #Success Message
    mysql_query($editsystem); echo '<font color="#66990F"><B><center>Changes Saved</B><BR>The System ID was updated.</center></font>'; }}

我只是不想为完成的任何更新显示“未更改”或“已更改”消息。如果系统ID已存在,则不会更新“系统ID”字段。我没有看到“未更改”,而是希望能够说明为什么它没有被更改,因此上面代码中的if命令。上面的示例是找到系统ID。

1 个答案:

答案 0 :(得分:0)

IMO你应该使用select语句检查system_id是否存在。

if (mysql_query("SELECT 1 FROM tbl WHERE system_id = {$system_id}")) {
    $editsystem_exists = "UPDATE `tbl` SET `system_customer`='{$system_customer}' WHERE `id`='" . $systemid_safe . "'";
} else {
    $editsystem_exists = "UPDATE `tbl` SET `system_customer`='{$system_customer}', `system_id`='{$system_id}' WHERE `id`='" . $systemid_safe . "'";
}