0

我正在尝试在插入之前检查记录是否存在。我的检查代码是:

$query = "SELECT * FROM firm WHERE ( name = '" . mysql_real_escape_string( $name ) . "' AND area = '" . mysql_real_escape_string( $areaname ) . "' )";
$rs = mysql_query( $query );

    if ( !$rs ) {
       echo "The firm for this area already exist.";
       trigger_error( mysql_error() );
    } else {
       echo "Saved.";
    }

我的插入代码是:

$result = array(); 
mysqli_autocommit( $dbc, FALSE );

$sql1 ="INSERT INTO `firm`(name, area, VAT, active) VALUES ('$name', '$areaname', '$VAT', '$active')"; 
//echo $sql1;
$result[] = mysqli_query( $dbc, $sql1 ) ;

$sql2 = "INSERT INTO `area`(name, hub_name, fk_hub_id) VALUES ('$areaname'
         ,(SELECT `name` from hub WHERE name = '$hub_name')
         ,(SELECT `id` from hub WHERE name = '$hub_name'))
        ";
//echo $sql2;
$result[] = mysqli_query($dbc,$sql2);       
$success = true;

if ( is_array( $results ) ) {
    foreach( $results as $result ) {
       if ( !$result ) {
           $success = false;
       }
    }
    if ( !$success ) {
       mysqli_rollback( $dbc );
    } else {
       mysqli_commit( $dbc );
    }
}

我的问题是我的错误消息不起作用。当我提交我的表格并且记录存在时,即使它没有插入,它也会说已保存。谁能告诉我哪里出错了?

4

2 回答 2

0

您的代码中有很多意大利面。看看 PHP PDO 扩展。减少 90% 的生产线。不要在 SQL 查询中运行 PHP 函数。

您的查询有错误。从变量名中删除括号

$name = mysql_real_escape_string($name);
$area = mysql_real_escape_string($areaname);

$query = "SELECT * FROM firm WHERE name = '$name' AND area = '$area'";
$rs = mysql_query($query);

if (!$rs) {
        echo "The firm for this area already exist.";
        trigger_error(mysql_error());
    }
else {
 echo "Saved.";
}

于 2013-08-08T09:01:12.383 回答
0

使用 mysql_num_rows() 来计算你的结果。

$query = "SELECT * FROM firm WHERE (name = '" . mysql_real_escape_string($name) . "' AND area = '" . mysql_real_escape_string($areaname) . "' )";
    $rs = mysql_num_rows(mysql_query($query));

    if ($rs != 0) {
            echo "The firm for this area already exist.";
            trigger_error(mysql_error());
        }
    else {
     echo "Saved.";}

请注意,不推荐使用 mysql_* 函数

看看PDO

http://php.net/manual/de/book.pdo.php

并尝试尽快将您的代码移植到 PDO 上。

于 2013-08-08T08:46:12.190 回答