2016-02-08 25 views
0

我遇到了一件很奇怪的事情。php函數中的SQL查詢500服務器錯誤

這拋出500服務器錯誤:

function writeMsg() { 

$id='0000000625'; 
$translation = 'word'; 
try { 
    $stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?"); 
    $stmt->execute(array($translation,$id)); 
    $response["success"] = 1; 
    } catch(PDOException $e) { 
    echo 'ERROR: ' . $e->getMessage(); 
    $response["success"] = 0; 
    } 
    echo 'RESPONSE: '.$response["success"]; 

} 
writeMsg(); 

這種精細運行:

$id='0000000625'; 
$translation = 'word'; 
try { 
    $stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?"); 
    $stmt->execute(array($translation,$id)); 
    $response["success"] = 1; 
    } catch(PDOException $e) { 
    echo 'ERROR: ' . $e->getMessage(); 
    $response["success"] = 0; 
    } 
    echo 'RESPONSE: '.$response["success"]; 

我僅除去第一個和最後2行。 有沒有人對此有過解釋?

+0

請告訴我們'$ conn'的定義 – Ohgodwhy

+0

耶可能需要一個 - global $ conn; –

+0

只需在您的函數中添加'global $ conn;' – 0x13a

回答

0

你可能已經錯過了$conn變量的作用域

function writeMsg() { 

    global $conn; 

    $id = '0000000625'; 
    $translation = 'word'; 

    try { 

     $stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?"); 
     $stmt->execute(array($translation, $id)); 
     $response["success"] = 1; 

    } catch(\PDOException $e) { 
     echo 'ERROR: ' . $e->getMessage(); 
     $response["success"] = 0; 
    } 

    echo 'RESPONSE: ' . $response["success"]; 

} 

writeMsg(); 

只需使用global $conn檢索來自全球範圍內$conn變量。查看更多關於http://php.net/manual/en/language.variables.scope.php的問題global關鍵字

+0

我不知道這件事。謝謝! – erdomester