2013-03-26 89 views
0

有代碼了很多,但大部分是不相關的,所以我將只發佈一個片段返回必須從函數更新的變量,不返回?

$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(); 
} 

這工作得很好,有一個錯誤的會話,它顯示了錯誤的錯誤向用戶發送了。 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; 
    } 
} 

這也能正常工作,檢查「後」存在於數據庫中,如果這樣做,將誤差變量$ 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 
} 

這是主循環,它循環我有一些變量,並從外部網站提取帖子,並將URL和error_message發送到函數fetch_posts

(我發送它,我通過引用來做它我asume這是爲了保持它的全球???)

if (strlen($error_message > 0)) { 
    died($error_message); 
} 

的唯一途徑,這是最後的片段中的循環之後,它應該是錯誤味精發送到功能錯誤,如果錯誤味精中含有任何字符,但它沒有檢測到任何字符?

回答

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 
} 
+0

我遲鈍....非常非常遺憾 – 2013-03-26 21:08:07

+0

謝謝,IL編輯我的代碼 – 2013-03-26 21:24:12

+0

沒問題。如果這是正確的答案,那麼您可以勾選它以將其標記爲已接受。 – MichaelRushton 2013-03-26 21:49:48