Vikas Kumar Vikas Kumar - 1 month ago 6
MySQL Question

Why isn't prepare statement executing?

I'm trying bind statement to insert data to table. All I know is that connection is established but the prepare statement isn't working. Am I doing something wrong?

<?php
class connDb{
private $link;
private $host;
private $user;
private $pass;
private $dbname;
public function __construct($host, $user, $pass, $dbname){
$this->host=$host;
$this->user=$user;
$this->pass=$pass;
$this->dbname=$dbname;
$this->link=mysqli_connect($this->host, $this->user, $this->pass, $this->dbname)
OR
die("Not connected to MySQL");
}
}
?>
<?php
$conn1=new connDb("localhost", "root", "", "dbind");
$xyz=$conn1->prepare("INSERT INTO table1 VALUES(?, ?, ?)");
$x="vikas";
$y="vikas@gmail.com";
$z="123n";
$xyz->bind_param('sss', $x, $y, $z);

$xyz->execute();
?>

Answer

You need to take the MySQLi connection not your own object.

<?php
class connDb{
    private $link;
    private $host;
    private $user;
    private $pass;
    private $dbname;
    public function __construct($host, $user, $pass, $dbname){
        $this->host=$host;
        $this->user=$user;
        $this->pass=$pass;
        $this->dbname=$dbname;
        $this->link=mysqli_connect($this->host, $this->user, $this->pass, $this->dbname)
            OR
        die("Not connected to MySQL");
    }
    public function getLink() {
        return $this->link;
    }
}

$conn1=new connDb("localhost", "root", "", "dbind");
$xyz=$conn1->getLink()->prepare("INSERT INTO table1 VALUES(?, ?, ?)");
$x="vikas";
$y="vikas@gmail.com";
$z="123n";
$xyz->bind_param('sss', $x, $y, $z);

$xyz->execute();
?>
Comments