我已经制定了以下PHP代码,它以下列方式处理表单中的数据:
$emailFrom = "";
$emailTo = "";
$subject = "Booking(s) for Workshop";
$body = "The following people have booked their workshops:" . "\n\n";
$row_count = count($_POST['name']);
if ($row_count > 0) {
mysql_select_db($database, $connection);
$name = array();
$workshop = array();
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name[$i] = mysql_real_escape_string(ucwords($_POST['name'][$i]));
$workshop[$i] = mysql_real_escape_string($_POST['workshop'][$i]);
}
$names = "('".implode("','",$name)."')";
$query = "SELECT 1 FROM conference WHERE Name In $names";
$result = mysql_query($query);
if ($result) {
$rowcount = mysql_num_rows($result);
if ($rowcount == 0) {
$errorString = "No bookings found";
}
else {
for($i = 0; $i < $row_count; $i++) {
$sql = "UPDATE conference SET Workshop = '$workshop[$i]' WHERE Name LIKE '$name[$i]'";
mysql_query($sql);
}
}
}
}
include 'workshops.php';
// send email
$success = mail($emailTo, $subject, $body, "From: <$emailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks-workshop.html\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
//}
我现在面临的问题是如何添加更复杂的错误检查。我希望PHP检查表单上提交的每个名称。如果找到所有名称,请将数据提交到研讨会列。如果找不到任何名称,则会显示错误消息“在我们的数据库中找不到以下名称:[名称列出]”。然后,在提交表单之前,用户将被迫输入正确的名称或删除有问题的名称。尽管如此,我还是想弄清楚如何实现这个目标。
我是否应该在每个名称的第一个循环上运行单独的查询,然后如果在表中找不到该名称,请将该名称添加到变量中,然后该变量将包含在错误消息中?然后,如果在所有循环之后错误变量为“”,则可以提交表单(因为已找到所有名称),但如果没有,则错误消息将显示需要修改的名称?
这是最好的方法,还是有更好的方法?
答案 0 :(得分:1)
我需要说抱歉。我以为你是通过POST发送所有名字的。
这是第二种解决方案,试试吧:
$not_in = Array();
// lets say all names doesn't exist in `conference`
foreach($name as $value) {
// names in array are keys, not values
$not_in[$value] = true;
}
$query = mysql_query("SELECT Name FROM conference WHERE Name IN $names");
while(list($dbname) = @mysql_fetch_row($query)) {
// delete those name from $not_in who exists
unset($not_in[$dbname]);
}
// names in $not_in array are keys, not values
$not_in = array_keys($not_in);
if(empty($not_in)) {
// its ok, all names have been found. do the magic.
}else{
$errorString = 'The following names have not been found on our database: '.join(', ',$not_in);
}
答案 1 :(得分:0)
在SQL查询中使用NOT IN ()
表达式:
$query = mysql_query("SELECT Name FROM conference WHERE Name NOT IN $names");
$not_in = Array();
while(list($name) = @mysql_fetch_row($query) {
$not_in[] = $name;
}
if(empty($not_in)) {
// its ok, all names have been found. do update.
}else{
$errorString = 'The following names have not been found on our database: '.join(', ',$not_in);
}
一切都与逻辑有关:
“如果找到所有名称,(...)”
你应该这样思考:
“如果不找到所有名称,(...)”