php mysqli插入变量查询

这个问题在这里已经有了答案:

  • 我如何防止PHP中的SQL注入? 28个答案

  • 对于任何可能仍需要完成原始问题中提出的问题的人,你好。

    某人可能不想使用预先准备的语句的原因 - 来自:http://www.php.net/manual/en/mysqli.quickstart.statements.php

    “使用准备好的语句并不总是最有效的执行语句的方式,只执行一次准备好的语句会导致比未准备好的语句更多的客户端 - 服务器往返。”

    //you will want to clean variables properly before inserting into db
    $username = "MyName";
    $password = "hashedPasswordc5Uj$3s";
    
    $q = "INSERT INTO `users`(`username`, `password`) VALUES ('".$username."', '".$password."')";
    
    if (!$dbc->query($q)) {
        echo "INSERT failed: (" . $dbc->errno . ") " . $dbc->error;
    }    
    echo "Newest user id = ",$dbc->insert_id;
    

    干杯!


    由于上面有一些讨论,我认为id在pdo和mysqli中提供了下面的例子进行比较:

    MySQLi

    $connection = new mysqli('localhost', 'user', 'pass', 'db'); 
    
    $username = "test";
    
    if ($connection->errno) {
        printf("Connect failed: %sn", $connection->error);
        exit();
    }
    
    $username = 'test';
    
    $stmt = $connection->prepare("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES (?,'test', 'test', 'test', 'test', 'test')");
    
    $stmt->bind_param('s', $username_value);
    $username_value = $username; // not we could simply define $username_value = 'test' here
    
    if ($result = $stmt->execute()){
    
      echo "success";
      $stmt->free_result();
    
    }
    else {
      echo "error";
    }
    
    $connection->close();
    

    PDO

    try {
    
    $db = new PDO($dsn, $user, $pass);
    $username = 'test';
    
    $stmt = $db->prepare("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES (?,'test', 'test', 'test', 'test', 'test')");
    
    $stmt->execute(array($username));
    
    echo 'Success';
    }
    catch(PDOException $e)
    {
      echo $e->getMessage();
    }
    

    在这种情况下,查看问题的上下文,最好为用户名变量分配一些数据,如$username=$_POST['username'];

    这可能有帮助...否则,请避免使用双引号,并放下$username

    链接地址: http://www.djcxy.com/p/16741.html

    上一篇: php mysqli insert variables query

    下一篇: Best use and practice of escaping strings