簡體   English   中英

如何在PHP函數中執行SQL查詢

[英]How to execute SQL query inside a PHP function

我正在嘗試執行此功能:

<?php
function registerDevice(){

        $query = "INSERT INTO devices (device,username) VALUES (:device,:username)";

         $query_params = array(
        ':device' => $_POST['device'],
        ':username' => $_POST['username'],
    );


        try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
        $response["success"] = 0;
        $response["result"] = "Error154";
        die(json_encode($response));

    }



    }
registerDevice();
?>

如果在函數外部時未調用該方法,則說明該方法成功運行:

<?php
$query = "INSERT INTO devices (device,username) VALUES (:device,:username)";

             $query_params = array(
            ':device' => $_POST['device'],
            ':username' => $_POST['username'],
        );


            try {
            $stmt   = $db->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch (PDOException $ex) {
            $response["success"] = 0;
            $response["result"] = "Error154";
            die(json_encode($response));

        }
?>

但是,當我調用該函數時,該函數根本不起作用。 我希望你們能幫助我。 謝謝

關鍵是$db變量。 您永遠不會顯示它是如何初始化的:我假設它是由一些外部( require )文件創建的,這些文件負責創建與DB的連接並將其存儲到$db var中。 由於文件邊界未在PHP中創建單獨的作用域,因此該變量保留在全局作用域中。

這不是一個好習慣,但是當使用$db的代碼也放在全局范圍內時,它就可以工作。 但是,當代碼移入一個函數時,它就中斷了,該函數引入了一個新的,隔離的作用域。

我建議您檢查此問題及其答案,它解釋了很多有關PHP的復雜性;並且相信我,有一些問題

解決這種混亂的一種可能方法是將$db變量的值顯式傳遞給registerDevice函數作為其參數。 顯然,這需要更改簽名:

function registerDevice($db) {
  // ... the rest of the code is the same    
}
registerDevice($db);

請注意, $_POST變量是另一種野獸。 實際上,還有更多的東西- $_GET$_SERVER等等,這些瘋狂的東西也被稱為PHP superglobals 無論是否引入新的作用域,您都可以在代碼的任何部分中安全地(某種程度上)使用它們。 畢竟,這就是為什么它們被稱為超全局變量。

盡管如此,即使可以使用所有功能,調整功能使其不依賴任何魔術也是一個好主意:

function registerDevice($db, $deviceId, $username) {
  // ... the code is the same    
}

if (isset($_POST['device'], $_POST['username'])) {
  registerDevice($db, $_POST['device'], $_POST['username']);
}
else {
  // something is not right with the request
}

所做的更改似乎微不足道,但是現在您的功能可以從任何來源獲取輸入,從而使它離真正的自治實體更近了一步。 除其他外,它使您能夠:1)隔離測試此功能; 2)在您的應用程序的其他部分重用此功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM