Answer the question
In order to leave comments, you need to log in
Fetching data from a database using MySQLi and prepared expressions?
Now many people recommend using the new MySQLi extension for database queries, which promises us support for all the new features of MySQL, more convenience and faster performance.
One thing is not clear to me: why didn’t they come up with a method for such a “new” and “cool” extension that allows, after executing a prepared expression, to receive a previously unknown number of fields? I mean the selection of the form:
It is not even possible to pass one array variable, the keys and values of which would become the result of the selection, to the function of preparing the result of the expression.
As a result, if we have a table like:SELECT * FROM table;
Field | Type |
---|---|
id | INT(10) |
field1 | VARCHAR(20) |
field2 | VARCHAR(20) |
$stmt = $mysqli->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param('i', $itemid);
$stmt->execute();
$stmt->bind_result($id, $field1, $field2);
$stmt->fetch();
Answer the question
In order to leave comments, you need to log in
Faced with a similar problem, I used the crutch from the zvirusz comment for a long time. But recently I came across information about PDO . PDO allows you to:
1) Easily change the SQL platform when using compatible queries;
2) Use prepared statements
3) Get the associated array without crutches using PDO::FETCH_ASSOC
The code turns out to be something like
$stmt = $db->prepare("SELECT * FROM foo WHERE a = ?"); $stmt->execute(array($a)); $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
One thing is not clear to me: why didn’t they come up with a method for such a “new” and “cool” extension that allows, after executing a prepared expression, to receive a previously unknown number of fields?
Why is this done?
The new extension brings new possibilities. You have selected the "SQL prepared" mode, i.e. at the first execution, the SQL statement is compiled and stored in the compiled form in the SQL cache as a query. This saves compilation time and improves performance.
If you have changed the structure of the table, then your compiled expression will no longer fit the new structure. Hence the error. Conclusion:
either set all fields, or do not use "prepared expressions"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question