Make fetch_assoc match fetch_all exactly - php

How do I match exactly the output of fetch_all with a loop using fetch_assoc? I have built code around fetch_all but my Bluehost server with PHP 5.4 isn't sufficient to run it (I'm talking to them about it). Here is what I've been using and it doesn't work:
public function getAllRecords($query) {
$results = array();
$r = $this->conn->query($query) or die($this->conn->error.__LINE__);
while ($row = $r->fetch_assoc()) {
$results[] = $row;
}
return $results;
}
EDIT
This function works but only returns one result:
public function getOneRecord($query) {
$r = $this->conn->query($query.' LIMIT 1') or die($this->conn->error.__LINE__);
return $result = $r->fetch_assoc();
}

To have $results containing the output exactly like that of of fetch_all, you can use this loop:
while ($row = $r->fetch_assoc()) {
$results[] = array_values($row);
}
or just using fetch_row in the loop:
while ($row = $r->fetch_row()) {
$results[] = $row;
}

OK, I don't know why my question was down-voted, it is legitimate. fetch_all as I was using it before, returns an array of rows as arrays. All my functions were based on parsing these arrays to their key values.
fetch_assoc returns an associative array, which is interpreted in Javascript as an object. Of course, my array-based parsing functions don't like that and that also means that fetch_assoc in a loop is NOT equivalent to fetch_all.
What is equivalent is fetch_row. The correct answer:
public function getAllRecords($query) {
$results = array();
$r = $this->conn->query($query) or die($this->conn->error.__LINE__);
while ($row = $r->fetch_row()) {
$results[] = $row;
}
return $results;
}

Related

How to return an array of objects in Json format from MySQL using php prepared-statement

I'm trying to write a function in php that will allow me to return an array of objects (in my case the objects are the rows in my database(MySQL) from phpMyAdmin) into a Json format.
Here is my function:
public function getAllCases()
{
$stmt = $this->conn->prepare("SELECT * FROM mycase ");
$stmt->execute();
$arr = []
$result = $stmt->get_result();
while($row = $result->fetch_object()) {
$arr[] = $row;
}
return $arr;
}
I couldn't find anything else online and this function is not working.
For example if my table has 4 rows, I want to be able to get 4 objects and each one of those 4 objects should represent a row from the table and it's columns.
Any help would be appreciated.
You can use json_encode and json_decode to convert array to JSON and vice versa.
return json_encode($arr)
To convert a php array into json , Use json_encode() function. And in your code, You mixed up Normal and Prepared Statements.
public function getAllCases()
{
$data = array();
$result = $this->conn->query("SELECT * FROM `mycase`");
$num_rows = $result->num_rows;
if ($num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
return json_encode($data);
}

How do I build this array to output?

I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}

Rewrite mysqli_fetch_all() to get the same result

Since the servers version is older than 5.3.0, I need to rewrite the following piece of function to do the same as it does now:
else {
$res = mysqli_query($_con, "SELECT * FROM house");
$row = mysqli_fetch_all($res, MYSQLI_ASSOC);
return $row;
}
In html I call it like this:
$results = getResults();
foreach ($results as $value) {
echo $value['Title']." / "; echo $value['Version'];
}
How can I call the results in my html the same way but with different function?
EDIT: I want to get all of the results from table "house" but without the use of function mysqli_fetch_all()
It's just a simple loop that calls mysql_fetch_array() and collects all the rows in an array.
function mysqli_fetch_all($res, $mode) {
$array = array();
while ($row = mysql_fetch_array($res, $mode)) {
$array[] = $row;
}
return $array;
}

PHP/MySQL: Why is my query only returning the first row?

Why is my method only returning the first row of my table? I can't understand why and it's driving me nuts. I'm sure it's something very simple.
public function getTitlesForRegistrationForm() {
$result = $this->_db->query("SELECT UserTitleID, UserTitleName FROM UserTitles");
$i=0;
$array[0] = "No result";
foreach($result->fetch(PDO::FETCH_ASSOC) as $row){
$array[$i] = $row;
$i++;
}
return $array;
}
Thanks.
It may be because your $result->fetch() call doesn't return an iterable value, but either a result row or FALSE. PHP's foreach only works on iterable values. Updating your code to something like this should do the trick:
public function getTitlesForRegistrationForm() {
$result = $this->_db->query("SELECT UserTitleID, UserTitleName FROM UserTitles");
$i=0;
$array[0] = "No result";
while (($row = $result->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$array[$i] = $row;
$i++;
}
return $array;
}
You need to fetch() inside a while loop. It will return only one row each time it is called.
I've also taken the liberty of refactoring away your $i counter. Instead the No result is appended onto the array in the first position (for whatever purpose you planned to use it), and subsequent rows are appended on with [].
public function getTitlesForRegistrationForm() {
$array = array();
$result = $this->_db->query("SELECT UserTitleID, UserTitleName FROM UserTitles");
// Why are you putting No Result onto the array?
// I've left it in, but it doesn't make sense to me.
$array[] = "No result";
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$array[] = $row;
}
return $array;
}
It's because you are using fetch(). You need fetchall().
http://www.php.net/manual/en/pdostatement.fetchall.php
[edit]Wow. I need to learn to type faster.
Try:
while($row = $result->fetch(PDO::FETCH_ASSOC)){
foo();
}
Try while instead of foreach. Foreach only iterates over a single row that is returned.
code:
while($row = fetch(PDO::FETCH_ASSOC)) {
$array[$i] = $row;
$i++;
}
Just replace the fetch method with fetchAll

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

Categories