【问题标题】:How to properly run and check parameterized database queries with PHP/MySQLi如何使用 PHP/MySQLi 正确运行和检查参数化数据库查询
【发布时间】:2014-08-27 03:40:46
【问题描述】:

在阅读了有关参数化查询的相关问题后,我意识到它们是完全(好吧,除非您插入表值或其他东西)防止 SQL 注入的方法,即使它们在某种程度上(好吧,非常很多)冗长和重复。但是,我一直想知道如何正确测试它们的错误处理,以及在某些情况下是否需要进行错误处理。

对不起,如果这是一个新手问题,但是 PHP 和 MySQL 不是安装在同一台服务器上吗?除非有人关心连接查询的语法或数据库连接代码或其他什么,否则我不完全确定是否有必要检查每个语句的错误,例如:

if ($stmt->bind_param('s',$logon)) {
   if ($stmt->execute()) {
      if ($stmt->bind_result()) {

      } else { return 'bat'; }
   } else { return 'bar'; }
} else { return 'foo'; }

// or else:

$stmt->bind_param('s',$logon)) or trigger_error('Could not bind parameters!',E_USER_ERROR);

// etc.

附带说明,如果$stmt 连接由于某种原因没有关闭,而mysqli 连接却是,这是否会导致某种内部服务器错误?还是关闭实际的mysqli 连接也能解决问题?为什么要关闭$stmt

无论如何,感谢您的回复。

更新:MySQL Parameterized Queries - Cache Duration [duplicate] // 没有必要关闭 $stmt,因为 PHP 最终会这样做。

注意事项$stmt -> prepare(...) 与服务器交互。

【问题讨论】:

    标签: php mysqli error-handling parameterized-query


    【解决方案1】:

    非常有用的AND 运算符可以帮助简化所有这些if-else 语句。虽然我确信还有其他更好的方法可以同时防止多个未捕获的异常,但这有望帮助其他正在寻找一种相当简单的方法来编写参数化查询的人,或者实际上是一般的嵌套查询:

    // Procedural style:
    
    $con = mysqli_connect('localhost','blah','foo','bar');
    $query1 = "SELECT xyz FROM blah WHERE xyz = ?";
    $username = 'ABC';
    
    
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
    } else {
        if (($stmt =
            mysqli_stmt_init($con) ) and
            mysqli_stmt_prepare($stmt,$query1) and
            mysqli_stmt_bind_param($stmt,'s',$username) and
            mysqli_stmt_execute($stmt) and
            mysqli_stmt_bind_result($stmt,$name) and
           ( mysqli_stmt_fetch($stmt) !== FALSE) ) { 
              // Be careful of the functions that can return null
              var_dump($name);
           }
    }
    
    // Object Oriented Style:
    
    $con = new mysqli('localhost','blah','foo','bar');  
        if ($con->connect_errno) {
            printf("Connect failed: %s\n", $con->connect_error);
        } else {
            if ( ($stmt = $con->prepare($query1)) and 
                $stmt->bind_param('s',$username) and 
                $stmt->execute() and
                $stmt->bind_result($name) and 
                ($stmt->fetch() !== FALSE)) {
                 var_dump($name);
    
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-11
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      相关资源
      最近更新 更多