如果在php中的sql中插入名称超过5次,如何抛出错误?
$sql = mysql_query("INSERT INTO `transfer`(`t_id`, `agent_id`, `agent_name`, `date`, `name`, `phone`, `email`, `tname`, `tphone`, `temail`, `status`) VALUES (NULL,'$agent_id','$agent_name','$date','$name','$phone','$email','$tname','$tphone','$temail','$cmmnt','$status')");
答案 0 :(得分:3)
试试这个
$sql = mysql_query("SELECT * FROM transfer HAVING COUNT(name) > 5");
if (mysql_num_rows($sql) != 0) {
// There are more than 5 - print an error.
echo 'Error - More than 5';
}else{
// No Error - Insert
$insert_query = "INSERT INTO `transfer`(`t_id`, `agent_id`, `agent_name`, `date`, `name`, `phone`, `email`, `tname`, `tphone`, `temail`, `status`) VALUES (NULL,'$agent_id','$agent_name','$date','$name','$phone','$email','$tname','$tphone','$temail','$cmmnt','$status')";
$insert_result= $mysqli -> query($insert_query);
}
答案 1 :(得分:0)
Please, don't use mysql_* functions in new code. 它们不再被维护,deprecation process已经开始了。看到 red box? 了解prepared statements, 并使用PDO或 MySQLi - 这个 article会 帮你决定哪个。
请参阅上述说明 - 我建议您使用mysqli_
函数,因为mysql_
函数已被弃用。
$mysqli = new mysqli('localhost', 'username', 'password', 'db');
$query = "SELECT * FROM transfer HAVING COUNT(name) > 5";
$result = $mysqli -> query($query);
$num = $result -> num_rows();
if($num != 0){
// There are more than 5 - print an error.
echo 'Error - More than 5';
}else{
// No Error - Insert
$insert_query = "INSERT INTO `transfer`(`t_id`, `agent_id`, `agent_name`, `date`, `name`, `phone`, `email`, `tname`, `tphone`, `temail`, `status`) VALUES (NULL,'$agent_id','$agent_name','$date','$name','$phone','$email','$tname','$tphone','$temail','$cmmnt','$status')";
$insert_result= $mysqli -> query($insert_query);
}
答案 2 :(得分:0)
注释使用mysqli *而不是mysql * API的重要性非常重要,不应该被忽略,但是因为你已经开始使用mysql *我将继续使用相同的路径...
我相信之前的答案(使用HAVING ...
)并未回答您的实际问题。请尝试下面的代码。
$sql = mysql_query("SELECT * FROM transfer WHERE name = '$name'");
if (mysql_num_rows($sql) >= 5) {
echo "Error - Too many occurrences of $name";
} else {
$insert_query = "INSERT INTO `transfer`(`t_id`, `agent_id`, `agent_name`, `date`, `name`, `phone`, `email`, `tname`, `tphone`, `temail`, `status`) VALUES (NULL,'$agent_id','$agent_name','$date','$name','$phone','$email','$tname','$tphone','$temail','$cmmnt','$status')";
$insert_result= $mysqli -> query($insert_query);
}