简体   繁体   English

如何在函数中运行我的 SQL 查询?

[英]How can I run my SQL query within a function?

I am constructing a PHP application and I want to be able to log every sql queries in the site.我正在构建一个 PHP 应用程序,我希望能够记录站点中的每个 sql 查询。 Therefore, I wrote a function to execute the sql queries and log the information.因此,我编写了一个函数来执行 sql 查询并记录信息。 The problem I have now is that for some reason, the only time where the query runs successfully is when it is returned.我现在遇到的问题是,由于某种原因,查询成功运行的唯一时间是返回时。 But it does not seem to work within the function itself.但它似乎在函数本身内不起作用。 $conn->error always remains empty. $conn->error 始终保持为空。 Indicating that that the query ran successfully.表示查询运行成功。 But if ($conn->query($query) !== TRUE) returns FALSE.但是if ($conn->query($query) !== TRUE)返回 FALSE。 Any help would be much appreciated.任何帮助将非常感激。

Here is my function where $conn is my sql connection, $site is the site settings and $alerts contains all the errors that may occur on the site.:这是我的函数,其中 $conn 是我的 sql 连接,$site 是站点设置,$alerts 包含站点上可能发生的所有错误。:

function SQLLogger($query,$username = null){
    global $conn,$site,$alerts;
    if($username == null){$username=$_SESSION[$site['id']];}
    if(strpos($query, 'INSERT INTO') !== false){
        $action = "inserting";
    } elseif(strpos($query, 'UPDATE') !== false){
        $action = "updating";
    } elseif(strpos($query, 'SELECT') !== false){
        $action = "selecting";
    } elseif(strpos($query, 'DELETE') !== false){
        $action = "deleting";
    }
    if ($conn->query($query) !== TRUE){
        $status = "Error";
        $error = array(
            'type' => 'error',
            'title' => 'Logger has reported an error',
            'body' => 'Error '.$action.' row: '.$conn->error,
        );
        array_push($alerts,$error);
    } else {
        $status = "Success";
    }
    $ip = $_SERVER['REMOTE_ADDR'];
    $query2 = "INSERT INTO logs (created, modified, `user`, `query`, `error`, `action`, `status`, `ipv4`) VALUES ( '".date("Y-m-d H:i:s")."', '".date("Y-m-d H:i:s")."', '".$username."', '".str_replace("'", "\\'", $query)."', '".$conn->error."', '".$action."', '".$status."', '".$ip."' )";
    if ($conn->query($query2) !== TRUE) {
        $error = array(
            'type' => 'error',
            'title' => 'Logger has reported an error',
            'body' => 'Error inserting row: '.$conn->error,
        );
        array_push($alerts,$error);
    }
    return $conn->query($query);
}

INSERT/UPDATE/DELETE 查询将返回 TRUE 或 FALSE 但 SELECT 查询返回一个 Mysqli_Result 对象,该对象绝对不是布尔值,因此永远不可能是=== TRUE=== FALSE!== false因为这些测试需要数据类型匹配.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM