Hello i am trying to make function with while loop in php but cant getting write here is my code
function mail_detail($mail_detail){
$data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
while ($result= mysql_fetch_array($data)){
return $result;
}
}
and out put is
$mail_detail= mail_detail($userid)
echo '<li class="read">
<a href="#">
<span class="message">'. $mail_detail['title'].'</span>
<span class="time">
January 21, 2012
</span>
</a>
</li>';
i am not getting all values just getting one value please help
thx
The return statement is terminating your loop and exiting the function.
To get all values, add them to an array in the loop, and then return the array. Like this:
$results = array();
while ($result = mysql_fetch_array($data)) {
$results[] = $result;
}
return $results;
on the side that receives the array
$msgArray = mail_detail($mail_detail);
foreach($msgArray as $msg) {
//use $msg
}
To add on, a function is only able to return once (except for some special circumstances that you should not worry about). Therefore, the first time your function comes across a return statement, it returns the value and exits.
This functionality of return can often be used to your advantage. For example:
function doSomething($code = NULL)
{
if ($code === NULL) {
return false;
}
//any code below this comment will only be reached if $code is not null
// if it is null, the above returns statement will prevent control from reaching
// this point
writeToDb($code);
}
function mail_detail($mail_detail){
$returnArr = array();
$data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
while ($result= mysql_fetch_array($data)){
$returnArr[] = $result;
}
return $returnArr;
}
This way you return everything returned because you push it in one array and as your loop finishes, the whole array wil be returned. Because just like xbones said, a return breaks your loop!
harinder,Function(mysql_fetch_array($data)) return an array. That means your $result is an array, so when you recevie the $result at view page you have to extract it using foreach look
like this:
foreach($result as $item)
{
echo $item->user(<-here you have to write the column name ,that you want to retrieve)
}
Hence you can get your all results in array.
Related
I have an small piece of PHP code that needs to put every file in the current directory into an array.
I have done this by making reading the dir with glob() and when it meets another dir it will loop.
My code I have as of now:
<?php
$find = '*';
$result = array();
function find($find)
{
foreach (glob($find) as $entry)
{
$result[] = $entry;
echo $entry.'<br>';
if (is_dir($entry)){
$zoek = ''.$entry.'/*';
find($zoek);
}
}
return $result;
}
print_r(find($find));
?>
When I execute the code the echo print exactly what I want. But the printed array doesn't give me the values I want, it only gives the values in the first dir it will come by then it seems to stop adding the value in the array.
What am I doing wrong?
You need to actually preserve the results you produce in the recursive callings to your function:
<?php
function listNodesInFolder($find) {
$result = [];
foreach (glob($find) as $entry) {
$result[] = $entry;
if (is_dir($entry)) {
$result = array_merge($result, find($entry.'/*'));
}
}
return $result;
}
print_r(find('*'));
Once on it I also fixes a few other issues with your code:
$result should be declared as an array inside your function, that that even if it does not loop you still return an array and not something undefined.
indentation and location of brackets got adjusted to general coding standards, that makes reading your code much easier for others. Get used to those standards, it pays out, you will see.
no need for an extra variable for the search pattern inside the conditional.
a speaking name for the function that tells what it actually does.
you should not name variables and functions alike ("find").
You need to add the result of find() to the array
Edit added array_merge - Cid's idea
<?php
$find = '*';
function find($find)
{
$result = array();
foreach (glob($find) as $entry)
{
$result[] = $entry;
echo $entry.'<br>';
if (is_dir($entry)){
$zoek = ''.$entry.'/*';
$result = array_merge($result, find($zoek));
}
}
return $result;
}
print_r(find($find));
?>
I'm trying to set up a PHP callback function for use in our application. It needs to pull data from a SQL server, and while I can get it to work initially, it's not quite doing what I want.
Code:
//Callback function for passing queries
function queryCallback($conn, $query) {
$response = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($response)){
if ($row === false) {
die(print_r(sqlsrv_errors(), true));
}
$responseData[] = $row;
}
foreach($responseData as $v) {
$output[key($v)] = current($v);
}
$responseDataJSON = JSON_encode($output, 128);
return $responseDataJSON;
}
In the above, $conn represents our server creds, as passed to sqlsrv_connect(), and $query is the string containing the query passed to SQL. Both have been verified as working.
Issue:
This code contacts the server correctly, and runs the query, but it only returns one result. This is obviously a problem with how the loops are set up, but I just can't spot it
My feeling is that the following $row = sqlsrv_fetch_array($response) is fetching the whole row as an array, but your usage of $output[key($v)] = current($v) is only returning the first column with the same key, and overwriting the $output index with every iteration.
foreach($responseData as $v) {
$output[key($v)] = current($v);
}
lets say you instead perform
foreach($responseData as $k => $v) {
$output[$k] = $v;
}
At which point this is redundant as $responseData[] already is this structure.
You may actually want this if you plan to extract just the first column out of your row.
foreach($responseData as $v) {
$output[] = current($v);
}
I want to use a function to load my news feed on my website dynamically from my database, I have created a function with variables for the type of post, from a specific user etc, and I want to run a while() loop to return each and every post as you would usually, how can this be done within a function though? I tried running the loop and setting the content I want to display in a single variable, which it then returns within that loop, I was hoping it would then run a return each time within the loop and the function would echo each out one by one, when I think about it logically, that obviously wouldn't happen, so could someone explain how this would be achieved?
Example (similar) code:
Accessing the function:
<?php echo getNews(); ?>
The function:
<?php function getNews(){
//query stuff
while($row = mysql_fetch_array($result)){
$return = "Looped data";
return $return;
}
?>
Return stops function executing. You could try something like
function getNews(){
$html = null;
//query stuff
while($row = mysql_fetch_array($result)){
$return = "Looped data";
$html .= $return;
}
return $html;
}
The return should be used out side of the loop
Try this function
<?php function getNews()
{
$return =array()
while($row = mysql_fetch_array($result))
{
$return[] = "Looped data";
}
return $return;
}
?>
With the first return the function breaks and so only the first row is fetched. You can temporarily save the data in an array and return it. When echoing you can then implode() it.
function getNews(){
//query stuff
$result = array();
while($row = mysql_fetch_array($result)){
$result[] = "looped data";
}
return $result;
}
echo implode("<br>\n", getNews());
Getting an array returned can be more useful in the future. Also the function name is more descriptive in my opinion. It doesn't say concat/etc, only get.
You can't use function to return with each loop. Alternatively either you can save the result created in loop to a variable or an array and return the variable/array. Example using variable is:
<?php function getNews() {
//query stuff
$return = "";
while($row = mysql_fetch_array($result)) {
$return .= "Looped data";
}
return $return;
}
?>
If your purpose is just echo the result than do it in function itself without using variable. Array would be better if you want to process something with result.
I am having trouble in returning all rows from while loop. When checking with print_r($item) it's returning all rows but when I user return in while loop it is only returning first row. I think that is because it is return the loop at the first time.
So how can I return all rows.. here is what I am trying
while($item = db_assoc($query)){
return '<p>'.$item['title'].'</p>';
}
The while loop is within the class method and I have to return the value so can't use echo
Thanks a lot....
Like you say, you're returning after the first row. Try the following:
$output = '';
while ($item = db_assoc($query)) {
$output .= "<p>{$item['title']}</p>";
}
return $output;
try to Create New Array Or Create format for you want inside the While-loop
And Return it..
"return" it stops execution loop.
while ($item = db_assoc($query)) {
$output .= "<p>{$item['title']}</p>";
}
return $output;
You should use
while($item = mysql_fetch_array($runsql)){
$data[]=$item['first_name'];
}
return $data;
it is because when you write return in loop it return with first value,
but in print_r it shows all record . so we have to create an array of required field and then return it
Hope it will help you.
Try this.
while($item = mysql_fetch_array($runsql)){
$data.=$item['first_name']."<br/>";
}
return $data;
Return will simply get out of the loop that's why it prints only the first row. If you want to return it all, save them in a string and after the while loop just return that string.
The return statement is causing it to break the execution of the loop.
Try this instead:
while($item = db_assoc($query)){
$titles[] = '<p>'.$item['title'].'</p>';
}
And to access the titles, you can simply use a foreach loop:
foreach($titles as $title){
echo "<p> $title </p";
}
Let me first start off, sorry for the confusing title. I didn't know how to exactly describe it but here goes. So I am querying a database for string. If there is only 1 result found then it is relatively easy to create an array, fill it with information, encode JSON and return that. I am confused as to when there are multiple results. The code below is what I am using but I highly doubt it is correct. I can't encode it into JSON format using my method which is what I need. If you can help at least point me in the correct direction, I would be more than grateful! Thank you!
PHP:
if ($action == 'profile') {
while ($pson = mysql_fetch_array($personQuery)) {
$typeSearch = 'profile';
$profQuery = mysql_query("SELECT * FROM tableName WHERE ColumnName LIKE '$query'");
$compQuery = mysql_query("SELECT * FROM tableName2 WHERE ColumnName LIKE '$query'");
if ($profQuery && mysql_num_rows($profQuery) > 0) {
$personQueryRows = mysql_num_rows($profQuery);
while ($row = mysql_fetch_array($profQuery)) {
if ($compQuery && mysql_num_rows($compQuery) > 0) {
while ($com = mysql_fetch_array($compQuery)) {
if (mysql_num_rows($profQuery) > 1) {
$compQueryRows = mysql_num_rows($compQuery);
if ($compQueryRows > 0) {
$compReturn = "true";
} else {
$compReturn = "false";
}
$nameArray = Array(
"success"=>"true",
"date"=>date(),
"time"=>$time,
"action"=>$action,
"returned"=>"true"
);
global $result;
for ($i=1;$i<=$personQueryRows;$i++) {
$nameResult[$i]=Array(
"id"=>$row['id'],
"name"=>$row['name'],
"gender"=>$row['gender'],
"comp"=>$row['company'],
"queryType"=>"profile"
);
$result = array_merge($nameArray, $nameResult[$i]);
}
$encodedJSON = json_encode($result);
echo $encodedJSON;
}
}
}
}
}
}
}
}
Returned JSON:
{"success":"true","date":"Jun 29 2012","time":"14:43:16","action":"profile","returned":"true","id":"14321","name":"John Smith","gender":"male","comp":"ABC Studios, LLC.","queryType":"profile"}
{"success":"true","date":"Jun 29 2012","time":"14:43:16","action":"profile","returned":"true","id":"292742","name":"John Smith","gender":"male","comp":"DEF Studios, LLC.","queryType":"profile"}
JavaScript error (when parsing JSON):
Uncaught SyntaxError: Unexpected token {
P.S. I am just getting started with PHP Arrays, and JSON formatting so I apologize if this is totally wrong. Still in the learning phase.
It looks like you're building up $nameResult[$i], but then you do:
$result = array_merge($nameArray, $nameResult[$i]);
You're doing that in each iteration of that for loop (once for each of the rows you got back), meaning that each time, you're clobbering $result.
After you finish that for loop, you then take whatever $result finally is (meaning the last $personQueryRows), and then json_encode it.
Looking at your other question (http://stackoverflow.com/questions/11257490/jquery-parse-multidimensional-array), it looks like what you should really be doing is before the loop where you go over $personQueryRows:
$output=$nameArray;
And then replace the array_merge line with:
$output[] = $nameResult[$i];
That last line will append the $result array onto the $output array as a new array member, meaning that it's nesting the array, which is what you'll need for your nested JSON.
Your code should look like this:
global $result;
$result = array();
.......
if ($action == 'profile') {
while{{{{{{{{...}}}}}}}}}}}
$encodedJSON = json_encode( $result );
echo $encodedJSON;
}