I want to use 'return' function with a while loop for my Mysql query, but it returns only one result.
I have this in my database :
id name author
1 foo fooo
2 foo2 fooo2
It returns only "2", but i want "1","2","3" ect..
Here's my code :
function get_thm_cat() {
require 'database.php';
$req = $bdd->prepare("SELECT * FROM sk_cat ORDER BY id ASC");
$req->execute();
if ($req->rowCount() > 0) {
while ($row = $req->fetch()) {
return '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
}
$req->closeCursor();
}
With return you stop the execution of the function, which means that when PHP iterates over your loop for the first time and reaches return, it immediately goes back to where you initially called the function. Any subsequent iterations of the while-loop are not executed and your call to $req->closeCursor(); also isn't executed when the result is more than 0 rows because of this.
The easiest way to return multiple strings after each other is to create a temporary variable that you fill up at every iteration and return after the loop, like this:
$output = '';
while ($row = $req->fetch()) {
$output .= '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $output;
return is the command to end the function and continue processing the code where it left off. You should either store the results in the while loop and return the array that holds these results, or you should echo the results in the while loop.
while ($row = $req->fetch_assoc() ) {
echo '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
or
$results = array();
while ($row = $req->fetch_assoc() ) {
$results[] = '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $results;
Related
I'm trying to GET a JSON format back when I POST a specific ID to my database. As I get more than one result I have multiple rows, which I want to get back. I do get different arrays back, but it is not a valid JSON Format. Instead of
[{...},{...},{...}]
it comes back as
{...}{...}{...}
Therefore the [...] are missing and the arrays are not separated by commas.
My code is down below. The function "getUserBookingsKl" is defined in a different php.
//get user bookings
public function getUserBookingsKl($id) {
//sql command
$sql = "SELECT * FROM `***` WHERE `hf_id`=$id AND `alloc_to`>DATE(NOW()) AND NOT `confirmation`=0000-00-00 ORDER BY `alloc_from`";
//assign result we got from $sql to $result var
$result = $this->conn->query($sql);
// at least one result
if ($result !=null && (mysqli_num_rows($result) >= 1 ))
{
while ($row = $result->fetch_array())
{
$returArray[] = $row;
}
}
return $returArray;
}
...
...
foreach($userdb as $dataset)
{
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
echo json_encode($returnArray);
# return;
}
// Close connection after registration
$access->disconnect();
It looks like you're sequentially emitting the values, not pushing into an array. You need to make an array, push into it, then call json_encode on the resulting structure:
$final = [ ];
foreach ($userdb as $dataset)
{
$returnArray = [ ];
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
$final[] = $returnArray;
}
echo json_encode($final);
Note that it's important here to not use the same variable inside the loop each time through or you're just pushing the same array in multiple times.
here i have a simple function but this show me data fom sql only in 1 div i want to show [ on div 1 show 1 data, in other div show 2 data, etc etc]...
function load_post($added_by)
{
global $Connection;
$SQL_3 = mysqli_query($Connection, "SELECT * FROM posts WHERE added_by='$added_by'");
$NumPosts = mysqli_num_rows($SQL_3);
$out['num_posts'] = $NumPosts;
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
$out['id'] = $Fetch_3['id'];
$out['text'] = $Fetch_3['text'];
$out['added_by'] = $Fetch_3['added_by'];
$out['mp4'] = $Fetch_3['mp4'];
$out['likes'] = $Fetch_3['likes'];
$out['youtube'] = $Fetch_3['youtube'];
$out['image'] = $Fetch_3['image'];
$out['date_added'] = $Fetch_3['date_added'];
return $out;
}
}
index.php.
$posts = load_post('gentritabazi');
<div class="settings_forms_content">
<?php echo $posts['text']; ?>
</div>
return finish immediately your function so only one iteration is done. You need to save your results in array and then after loop return that array, sth like this:
$out = array();
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
$out[] = $Fetch_3;
}
return $out;
and display:
$posts = load_post('gentritabazi');
foreach ($posts as $post) {
echo '<div class="settings_forms_content">';
echo $post['text'];
echo '</div>';
}
Lots to amend, so I commented the code rather than write an essay
function load_post($con, $added_by)
{
// dont use globals, use parameters
//global $Connection;
// select only what you want to see not `*`
$SQL_3 = mysqli_query($con, "SELECT id, text, added_by, mp4,
likes, youtube, image, data_added
FROM posts
WHERE added_by='$added_by'");
// not needed
//$NumPosts = mysqli_num_rows($SQL_3);
//$out['num_posts'] = $NumPosts;
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
/*
* THsi code would overwrite the last iteration of the while loop
$out['id'] = $Fetch_3['id'];
$out['text'] = $Fetch_3['text'];
$out['added_by'] = $Fetch_3['added_by'];
$out['mp4'] = $Fetch_3['mp4'];
$out['likes'] = $Fetch_3['likes'];
$out['youtube'] = $Fetch_3['youtube'];
$out['image'] = $Fetch_3['image'];
$out['date_added'] = $Fetch_3['date_added'];
*/
// now as you SELECT only what you want yo can simply do
$out[] = $Fetch_3;
//return $out; instantly terminates the function
}
return $out; // return the array
}
Now call your function
// pass the connection as a parameter
$posts = load_post($Connection, 'gentritabazi');
// if you want to know how many results were returned
$result_count = count($posts);
// process the returned array
foreach ( $posts as $post ) {
echo '<div class="settings_forms_content">';
echo $post['text'];
echo '</div>';
}
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements
$posts = load_post('gentritabazi');
foreach ($posts ['text'] as $postText){
echo "<div class='settings_forms_content'>$postText</div>";
}
first line calls your function which returns the array $posts
this array looks like:
$posts = array(
"id" => array of ids
"text" => array of texts
...
);
if you want to access the third text it would be like this:
$posts ['text'][3]
the foreach iterates to your $post array with index "text" -> which is also an array
every value in this array, $post['text'] will be referenced with $postText -> that means:
$post['text'][1] = $postText (first time looping through foreach-loop)
$post['text'][2] = $postText (secondtime looping through foreach-loop)
..
if you are familiar with loops, a foreach is just the short version for
for(var $i=0;$i<length($posts['text'];$i++){
echo "<div class='settings_forms_content'>$posts['text'][i]</div>";
}
I want to show all distinct id_did in cc_did_use
function getdidbycc($cccard_from_sipcard){
$result = mysql_query("SELECT id_did from cc_did_use where id_cc_card='$cccard_from_sipcard'");
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
return $text;
}
I have two id_cc_card="31" and one that value has id_dd="14" and another one = "13"
but result just show first one.
How I can show both of them?
and after that I have another function
function get_did ($p){
$result = mysql_query("SELECT did FROM cc_did WHERE id ='$p'");
while ($row = mysql_fetch_array($result))
{
echo $row['id_did'].'<br/>';
}
}
when I run getdidbycc function , it returns two value , 13 and 14 ,
How I can get did numbers from this two values?
You are fetching result and checking in an if condition which will execute only once.
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
You have to fetch the result until there is value in the resultant array. So try with while loop like,
while($row = mysql_fetch_array($result)) // while there are records
{
$text[] = $row['id_did']; // store the result in array $text
}
return $text; // return the array
First of all try to use mysqli or pdo instead of mysql otherwise you will face issues in updated version of php
As per your code $text value is gets over write due to loop so use an array something like this
if ($row = mysql_fetch_array($result)) {
$text[] = $row['id_did'];
}
return $text;
or you can just return complete data as return $row;
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
change the above line to this
while($row = mysql_fetch_array($result))
{
echo $row['id_did'].'<br/>';
}
Use a while loop like that : http://php.net/manual/en/function.mysql-fetch-array.php
Mysql fetch array returns the current element only
if ($row = mysql_fetch_array($result))
{
$text[] = $row['id_did'];
}
return $text; // returns both
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;
}
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