Error with SQL statement prepared using PHP

3

So far I have never used the prepared statements but from what I have read they are necessary when avoiding SQL injection as it could happen, for example, from a web form. To test them I wrote the following code:

A function to connect to the database:

function connectDB2(){
   $con = new mysqli("localhost", "root", "root", "eventos");
    if($con->connect_error){
       die("La conexión ha fallado, error número " . $con->connect_errno . ": " . $con->connect_error);
    }else{
       // echo 'Conexión establecida con éxito';
    }

    return $con;   
}

Another function to register a new event in the database through a prepared query:

function new_event($title,$color,$start){
    $conexion = connectDB2();
    mysqli_set_charset($conexion, "utf8"); //formato de datos utf8
    $conexion->prepare("INSERT INTO eventos(titulo,color,comienzo) VALUES(?,?,?)");
    $conexion->bind_param('sss',$title,$color,$start);
    $conexion->execute();
    $conexion->close();
}

From another PHP file that includes the container file of the previous functions, I call the function new_event() with the data to insert:

new_event("Evento de prueba 3","purple","2016-05-07");

PHP returns the following error:

Fatal error: Call to undefined method mysqli::bind_param()

What can I be doing wrong?

    
asked by Hechi 20.05.2016 в 10:22
source

1 answer

4

Solved, apparently the object that called the methods prepare() and bind_param() was incorrectly instantiated. Then I leave the solution regarding my code:

function new_event($title,$color,$start){
    $conexion = connectDB2();
    mysqli_set_charset($conexion, "utf8"); //formato de datos utf8
    $stmt = $conexion->prepare("INSERT INTO eventos(titulo,color,comienzo) VALUES(?,?,?)");
    $stmt->bind_param('sss',$title,$color,$start);
    $stmt->execute();
    $stmt->close();
    $conexion->close();
}
    
answered by 20.05.2016 / 12:01
source