Error bindParam (); PHP

0

For this class Conexion ...

  class Conexion{
    private $host;
    private $user;
    private $pass;
    private $bbdd;
    private $connect;

    public function __construct(){
      $this->host = "localhost";
      $this->user = "usuario";
      $this->pass = "";
      $this->bbdd = "test";
      $this->connect = new mysqli();
    }

    public function connectBD(){
      $this->connect->connect($this->host, $this->user, $this->pass, $this->bbdd);
    }

    public function getConexion(){
      return $this->connect;
    }

I perform a simple task of adding data to my DB, import the file and initialize the Connection object.

require("Conexion.php");
        $conexion = new Conexion();
        $conexion->connectBD();

        $connect = $conexion->getConexion();

I insert a datum

$sql = "INSERT INTO test(id, nombre) VALUES(:id, :nombre)";

                    $stmt = $connect->prepare($sql);

                    $stmt->bindParam(':id', $_POST['id']);
                    $stmt->bindParam(':nombre', $_POST['nombre']);

                    $stmt->execute();
                    $stmt->close();

And an error occurs that says:

 Fatal error: Call to a member function bindParam() on boolean

I understand that the error says that you can not call the function bindParam () on a boolean, which means that the variable $ stmt comes as false to bindParam (); then an error occurs in the prepare ... but what happens? I've given it a lot of laps and there's no way.

However, if I do it this way ... there is no problem:

$sql = "INSERT INTO test (id, nombre) VALUES (?, ?)";
                $stmt = $connect->prepare($sql);
                $stmt->bind_param("is", $_POST['id'], $_POST['nombre']);
                $stmt->execute();
                $stmt->close();
    
asked by Tygreton 15.06.2018 в 01:03
source

1 answer

1

Extending comment MySQLI does not support named parameters, PDO yes.

That's why the prepare returns false.

$sql = "INSERT INTO test(id, nombre) VALUES(:id, :nombre)";
$stmt = $connect->prepare($sql);

would be valid if $connect were a PDO , and then you could do:

$stmt->bindParam(':id', $_POST['id']);

in MySQLI the second way works because it uses placeholders ( ? ) and also calls the correct method ( bind_param )

    
answered by 15.06.2018 в 01:58