doubo1871 2016-10-25 20:10
浏览 51

SQL注入:试图避免它但是出错了

So this is only a part of my code but the only relevant thing:

if ($check == 0) {     
                    $host = "localhost";
                    $user = "root";
                    $pass = "";
                    $db = "myfirstdb";
                    $connect = new mysqli($host,$user,$pass,$db);
                    if ($connect->connect_error){ 
                        die("Connection failed: " . $connect->connect_error);
                    } else {
                        echo "Connected successfully!";
                    }

                    //$sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES (:fname, :lname, :phone, :email, :date)";
                    $secure = $db->prepare("INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES (:fname, :lname, :phone, :email, :date)");
                    $secure->bindParam(':fname' , $firstname);
                    $secure->bindParam(':lname' , $lastname);
                    $secure->bindParam(':phone' , $phone);
                    $secure->bindParam(':email' , $email);
                    $secure->bindParam(':date' , $date);
                    $secure->execute();
                    /*if ($connect->query($sql) === TRUE) {
                        echo "New record created successfully";
                    } else {
                        echo "Error: " . $sql . "<br>" . $connect->error;
                    }*/

                    $connect->close(); 

The problem i have is whenever i execute the code an error pops out:

Fatal error: Uncaught Error: Call to a member function prepare() on string in C:\xampp\htdocs\example\Index.php:206 Stack trace: #0 {main} thrown in C:\xampp\htdocs\example\Index.php on line 206

I'm trying to avoid the SQL injection by using this code but I'm not sure whether I understood it.

  • 写回答

2条回答 默认 最新

  • doutun1362 2016-10-25 20:18
    关注

    You aren't preparing the statement on the correct variable. You need to do:

    $connect->prepare("INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES (:fname, :lname, :phone, :email, :date)");
    

    EDIT:

      $db = "myfirstdb";
      $connect = new mysqli($host,$user,$pass,$db);
    

    Your Object is the vaiable you set as a "new class", so in this case your object is $connect which is a new mysqli class instance. Your original script (causing the error) was using the $db variable which is a string not an Object.

    You can only ->prepare (and use the -> syntax) on Objects .

    评论

报告相同问题?