MySQL Injection by LIKE operator

This question already has an answer here:

  • How can I prevent SQL injection in PHP? 28 answers

  • Any operator can be injected without binding.

    $_POST['search'] = "1%'; DROP TABLE myTable LIKE '%";
    

    Would make

    .... AND tags,title,text LIKE '%1%'; DROP TABLE myTable LIKE '%%'
    

    Read on how to bind parameters.


    Of course this can be injected, you need to sanitize your input. Right now you are taking raw post data and inserting it into your SQL statement.

    You should run your POST data through some sort of data sanitization, something like mysql_real_escape_string or the like

    Or at least prepared statements. let server side code do the work for you.


    Never, ever, use database queries like that, don't construct a string with variables and use it for database activities.

    Construct a string that will later on be prepared and executed, by inserting the variables into the string, making them not act like "commands" but as "values".

    You can do it like this:

    $query = "SELECT * from products WHERE shop_id = :shopId;"; // An example, you can finish the rest on your own.
    

    Now, you can prepare the statement (I recommend using PDO for this).

     $statement = $db->prepare($query); // Prepare the query.
    

    Now you can execute variables into the prepared query:

    $statement->execute(array(
        ':shopId' => $_SESSION['shop_id']
    ));
    

    If you're inserting or updating, then you would have wanted to do:

    $success = $statement->execute(array(
        ':shopId' => $_SESSION['shop_id']
    ));
    

    which stores a boolean in $success, or you can fetch the values from a result if you're SELECTing:

    $statement->execute(array(
        ':shopId' => $_SESSION['shop_id']
    ));
    $result = $statement->fetch(PDO::FETCH_ASSOC);
    if($result )
    {
        // You can access $result['userId'] or other columns;
    }
    

    Note that you should actually make that be a function, and pass $shopId into the function, but not the session itself, and check if the session actually exists.

    I recommend googling on how to use PDO, or take a look on one of my examples: How to write update query using some {$variable} with example

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

    上一篇: 使这个查询安全吗?

    下一篇: LIKE运算符的MySQL注入