I have a PHP class for querying the database and taking results. I need to be able to loop through multiple rows, but I can't figure out how I'd do that with my current function. My function is:
$data = mysqli_query($this->connectDB(), $query);
$row = mysqli_fetch_array($data);
return $row;
but there's no way to loop through rows that I've tried that doesn't crash the script. I've also tried return mysqli_fetch_array($data);, but that doesn't work either. Is it possible?
You could use:
while ($row = mysqli_fetch_array($data)) {
$array[] = $row;
}
return $array;
php manual: mysql_fetch_array
Related
I am developing a web service using PHP. I am having some trouble while executing the select query. This is the code I'm using.
DB_Functions.php
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
return mysql_fetch_array($result,true);
} else {
return false;
}
}
GetCompanies.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$companies = array();
//$rows = $db->getCompanies();
while ($row = $db->getCompanies()) {
echo $row['companyName'];
$rowArr = array();
$rowArr['CompanyName'] = $row['companyName'];
$rowArr['CompanyID'] = $row['companyId'];
//array_push($companies, $rowArr);
$companies[] = $rowArr;
}
header('Content-Type: application/json');
$response=array("Companies"=>$companies);
$json = json_encode($response);
echo $json
?>
But the problem is in GetCompanies.php file the while loop is runs endless. The code appears to be ok. Any help would be appreciated.
When you do while ($row = $db->getCompanies()) { you are running the entire query over again and returning the 1st row each time. mysql_fetch_array returns one row.
What you need to do is have getCompanies() loop over all the rows and return an array.
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
$ret = array();
while($row = mysql_fetch_assoc($result)){
$ret[] = $row;
}
return $ret;
} else {
return false;
}
}
Now, getCompanies() will return you an array that you can just foreach over:
$rows = $db->getCompanies();
foreach($rows as $row){
// ...
}
Change your while loop declaration to something like
foreach($rows as $row) {}
And as Pavlin said, move the function call to getCompanies() outside the loop.
Also, how about modifying the query to select a particular set of fields from the database and directly sending them as the response without doing any additional processing?
Since you are implementing Select query without any condition(where clause). And since the company table has data it would always return true in the while loop this makes the while loop an infinite loop. For while to work properly the condition should become false to exit the loop.
Its not a programming flaw its a logical one.
The php docs have all the information you need. You're using the wrong function:
mysqli_fetch_array — Fetch a result row as an associative, a numeric
array, or both
vs
mysqli_fetch_all — Fetches all result rows as an associative array, a
numeric array, or both
Just change your return statement to
return mysqli_fetch_all($result);
or
return mysqli_fetch_all($result, MYSQLI_ASSOC);
to get an associative array.
And of course, you need to move your getCompanies call outside of the loop.
NOTE
php mysql_* functions have been depricated since version 5.5.* and are going to be removed from the language soon. You should look into mysqli_* or PDO.
These are my two methods for querying a database.
This is my first method that saves all the results in an array. Then i use a foreach loop to loop through the array.
public function query($query) {
$rows = array();
if ($result = $this->mysqli->query($query)) {
if($result->num_rows > 1) {
while ($item = $result->fetch_assoc()) {
$rows[] = $item;
}
//jo else sepse nxjerr error kur ska asnje row i ben fetch kur ska row.
} else if($result->num_rows == 1) {
$rows = $result->fetch_assoc();
}
return $rows;
} else {
echo "error";
}
}
Then to output I use:
$run_query = $db->query($query);
foreach ((array)$runk_query as $data) {
....
This is my second method:
$query = $db->query("SELECT * FROM ...");
while($run_query = mysqli_fetch_array($query)) {
//OUTPUT data.
....
}
I notice that in many cases I need to output the results so I think using the first method is bad because I use once the while loop and then I use again a foreach loop so the work is done twice but the second way is not very OOP.
Can anyone suggest me the best method of this or if possible another better method?
You can likely replace you entire first function with a call to mysqli_fetch_all() instead of iterating through each record with fetch_assoc(). This way you don't have to build your array result by result.
You can then run through all the results with your second foreach as per usual.
See: http://www.php.net//manual/en/mysqli-result.fetch-all.php
Alternatively if you were using PDO you could use fetchAll()
See: http://www.php.net/manual/en/pdostatement.fetchall.php
Is it possible to extract a value from mysqli_result without fetching a row i.e. without modifying the result set as I need it in full later in my code?
You can also point the iterator back to the beginning. ie..
$result = $mysqli->query($query);
while($row = $result->fetch_assoc())
{
//do stuff with the result
}
//back to the start
mysqli_data_seek($result,0);
now the pointer is returned to the beginning. mysqli_data_seek
You can get all and store in an array…
$results = [];
$sql = mysqli_query($con,"SELECT * FROM WHATEVER");
while ($row = mysqli_fetch_array($sql)) {
array_push($results, $row);
}
//Now $results is fully populated
I have a MySql class and I fetch the Mysql rows by returning them as a method:
public function fetch_assoc($result_set){
return mysql_fetch_assoc($result_set);
}
For some reason it only return one result when I try to iterate through an method return through the object I have instantiated.
while ($row = $a->fetch_assoc($result_set){
...
}
While doing the old fashion ways works, and gives me all the rows
while($row = mysql_fetch_array($result_set)){
$row['0'];
}
Any ideas?
That is because mysql_fetch_assoc return only one result and moves the pointer to the next. So at each iteration it returns moves the pointer and returns false when it reaches the end of the results.
You can modify your method this way to make it work:
public function fetch_assoc($result_set){
$resultArray = array();
while ($row = mysql_fetch_assoc($result_set){
$resultArray[] = $row;
}
return $resultArray;
}
And you can use the data as so:
foreach ($obj->fetch_assoc($result_set) as $row){
echo $row['stuff'];
}
Note that in this case $obj->fetch_assoc($result_set) returns all the results, and i am just looping through it using a foreach loop;
I am getting only one row, can someone please tell me how to get all the data from the table column of my database table ?
public function getCategories(){
$result = $this->db->query('SELECT * FROM newscat');
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
return $rows;
}
}
You're returning from within the loop. That will break it in the first round.
return outside the loop.
do the minor change
public function getCategories(){
$result = $this->db->query('SELECT * FROM newscat');
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
return $rows;
}
Your problem is the return $rows;. It should reside after the while. The thing is that it will enter the while, put the first row in the array, and then immediately return it. What you want is to let the while do its thing, and after the it finished, return the array.
If you are using mysqli.
Then you can use its apiFfetch_all to get all the rows at once.
For example :
$array=$result->fetch_all(MYSQLI_ASSOC);
The above code will get all associated rows in the corresponding array.