我试图在插入之前检查记录是否存在。我的检查代码是:
$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 );
}
}
我的问题是我的错误消息无效。当我提交我的表格并且记录存在时,即使未插入,也会保存。谁能告诉我哪里出错了?
答案 0 :(得分: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上移植代码。
答案 1 :(得分:0)
你的代码中有很多意大利面条。看看PHP PDO扩展。减少90%的线路。 不要运行PHP函数内联SQL查询。
您的查询有错误。从变量名称中删除括号
$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.";
}