PHP mysqli prepare statements own class

755

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?

357

Answer

Solution:

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']);

People are also looking for solutions to the problem: php push to array from function

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.