有很多代码,但大部分都是无关紧要的,所以我只会发布一个代码段
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
这样可以正常工作,通过错误会话向用户发送,这会在error.php上显示错误
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
这也可以正常工作,检查数据库中是否存在“post”,如果存在,则将错误添加到变量$ error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
这是主循环,它循环我拥有的一些变量,并从exsternal网站获取帖子并将URL和error_message发送到函数fetch_posts
(我发送它,我通过参考来做这件事我认为这是保持全球的唯一方法???)
if (strlen($error_message > 0)) {
died($error_message);
}
这是循环之后的最后一个片段,如果错误消息包含任何字符,它应该将错误消息发送到函数错误,但是它没有检测到任何字符?
答案 0 :(得分:4)
你想:
strlen($error_message) > 0
不
strlen($error_message > 0)
此外,调用时间传递引用自5.3.0以来已被弃用,并且自5.4.0以来已被删除,因此不是像这样调用您的函数:
fetch_post($post_now, &$error_message);
你想要像这样定义它:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
虽然在循环中返回错误消息时,最好这样做:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}