When should I use prepared statements?

后端 未结 4 1320
感动是毒
感动是毒 2020-11-22 05:22

Originally I used mysql_connect and mysql_query to do things. Then I learned of SQL injection, so I am trying to learn how to use prepared statemen

4条回答
  •  借酒劲吻你
    2020-11-22 05:50

    There is a two solution for this-

    01- Use Prepared Statements

    To prevent SQL injections we will have to use something called prepared statements which uses bound parameters. Prepared Statements do not combine variables with SQL strings, so it is not possible for an attacker to modify the SQL statement. Prepared Statements combine the variable with the compiled SQL statement, this means that the SQL and the variables are sent separately and the variables are just interpreted as strings, not part of the SQL statement.

    02- Prepared Statements with mySQLi.

    Using the methods in the steps below, you will not need to use any other SQL injection filtering techniques such as mysql_real_escape_string(). This is because with prepared statements it is not possible to do conventional SQL injection.

    eg -

    $name = $_GET['username'];
    
    if ($stmt = $mysqli->prepare("SELECT password FROM tbl_users WHERE name=?")) {
    
        // Bind a variable to the parameter as a string. 
        $stmt->bind_param("s", $name);
    
        // Execute the statement.
        $stmt->execute();
    
        // Get the variables from the query.
        $stmt->bind_result($pass);
    
        // Fetch the data.
        $stmt->fetch();
    
        // Display the data.
        printf("Password for user %s is %s\n", $name, $pass);
    
        // Close the prepared statement.
        $stmt->close();
    
    }
    

    You can find more about this form - http://www.wikihow.com/Prevent-SQL-Injection-in-PHP

提交回复
热议问题