I am trying to make a wrapper for the select query, but I don’t understand how to pass empty variables to the functions, there is the following code:

<?php $mysqli = new mysqli("localhost", "root", "", "testdb"); $query = "SELECT id, first_name FROM test"; if ($stmt = $mysqli->prepare($query)) { $stmt->execute(); $stmt->bind_result($id, $first_name); while ($stmt->fetch()) { echo $id; echo $first_name; } $stmt->close(); } $mysqli->close(); ?> 

If I understand correctly:

 $stmt->bind_result($id, $first_name); 

assigns to variables:

 $id, $first_name 

values: id, first_name, from DB

In this example, everything works!

But how on the basis of this to make a class? Rather, I did, but how to pass variables to:

 $stmt->bind_result(Сюда); 

Please forgive, maybe the question is stupid or not entirely clear, but I'm still learning.

The class itself, or rather the sketch:

 <? class mysqliAction { public function __construct($mysqli_server, $mysqli_user, $mysqli_password, $mysqli_database) { $this->s = $mysqli_server; $this->u = $mysqli_user; $this->p = $mysqli_password; $this->d = $mysqli_database; } protected function connect() { return new mysqli($this->s,$this->u,$this->p,$this->d); } public function mysqliSelect($query) { $mysqli = $this->connect(); $stmt = $mysqli->prepare($query); $stmt->execute(); /* Определить переменные для результата */ $stmt->bind_result($id, $first_name); while ($stmt->fetch()) { echo $id; echo $first_name; } $stmt->close(); } } $mysqli = new mysqliAction($mysqli_server, $mysqli_user, $mysqli_password, $mysqli_database); $query = 'SELECT id, first_name FROM test'; $mysqli->mysqliSelect($query); ?> 

So everything works, but how to pass arguments to:

  $stmt->bind_result($id, $first_name, и так далее); 
  • @BOPOH, added class. - Vadim Pedchenko

1 answer 1

You can create your own parameters in the following way: $$name_var

In your case, you can submit an array with a list of fields and call the callback function

 call_user_func_array(array($stmt, 'parent::bind_result'), array("\$id","\$first_name")); 
  • Thanks, but you can show by the example of this code, if not difficult, read about call_user_func_array , but somehow I can’t understand ... - Vadim Pedchenko
  • And how bad is this option? php.net/manual/ru/mysqli-result.fetch-assoc.php - Vaflan
  • I read that prepared queries are more secure and productive (correct if I am mistaken), I want to make a wrapper class for SELECT, INSERT, and so on. - Vadim Pedchenko
  • but you are already losing performance, you are constantly calling connect (a new connection to the database), rather than keeping its link, which can be created in the constructor. - Vaflan
  • So it is created in the constructor, and called when the request ... Or did I misunderstand something? And it seems we have moved away from the topic))) Still, how do I use call_user_func_array in my code? Poke your nose) - Vadim Pedchenko