User0101
User0101

Reputation: 13

PHP mysqli prepare statements own class

I want to write a method for adding records to the database.

My method:

final public function newData($sql, $placeholder, $array) {
  $stmt = $this->db->prepare($sql);
  $stmt->bind_param($placeholder, implode(",", $array));
  return $stmt->execute();
}

..................

// Code---Example
$sql = "INSERT INTO table (name, data) VALUES (?,?)";

$placeholder =  "ss";

final public function newData($sql, $placeholder, [$array]) {
  $stmt = $this->db->prepare($sql);
  $stmt->bind_param($placeholder, implode(",", $array));
  return $stmt->execute();
 }

My problem is if I want to save several values with this method. I get a warning

Warning: mysqli_stmt:: bind_param (): Number of elements in type definition string doesn't match number of bind variables in ##

What am I doing wrong?

Upvotes: 1

Views: 696

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

You can't use $stmt->bind_param() that way. You would need to do argument unpacking because bind_param requires type and then each value as an argument.

final public function newData($sql, $placeholder, $array) {
    $stmt = $this->db->prepare($sql);
    $stmt->bind_param($placeholder, ...$array);
    return $stmt->execute();
}

Then use like:

$sql = "INSERT INTO table (name, data) VALUES (?,?)";

$result = $theDbClass->newData($sql, 'ss', ['foo', 'bar']);

Upvotes: 1

Related Questions