I have a while loop nested in another while loop. The first while will give me 5 elements, and for each element I have to go to the second while and get 2 elements.
The problem is I have to return all 10 values to a function.
How can I make it?
I tried to merge two arrays but it didn't work.
function ShowCustomers()
{
while($row2 = mysql_fetch_array($result2))
{
while($row3 = mysql_fetch_array($result3))
{
$res = array($row2['f_name'], $row3['name'], $row3['s_name']);
$res1 = array_merge($res1,$res);
}
}
return $res1;
}
If all you want to do is put all the results into one array and return it, you can use array_push(), or the shorthand: $your_array[] = ...:
function ShowCustomers()
{
$result_array = array();
while($row2 = mysql_fetch_array($result2))
{
while($row3 = mysql_fetch_array($result3))
{
$res = array($row2['f_name'], $row3['name'], $row3['s_name']);
$result_array[] = $res;
}
}
return $result_array;
}
You need to declare $res1 outside the scope of your loops so that it keeps its value after each iteration:
function ShowCustomers()
{
$res1 = array();
while($row2 = mysql_fetch_array($result2))
{
while($row3 = mysql_fetch_array($result3))
{
$res = array($row2['f_name'], $row3['name'], $row3['s_name']);
$res1 = array_merge($res1,$res);
}
}
return $res1;
}
Related
I created a function that read data from a mysql db.
I want to put the data into a array and read that outside of the PHP function.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
return $kategorien;
}
}
To load the data outside from function:
$kategorien = showCategory($con);
echo $kategorien['kategorie'][0];
It doesn't work. Whats wrong?
The
return $kategorien;
will exit the loop and the function, so move this to the end of the function and not in the loop.
function showCategory($con) {
$sql = "SELECT kategorie FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}
Rather than using *, it's also worth specifying the column names if you only need some of them.
Display the data using...
$kategorien = showCategory($con);
print_r( $kategorien );
or use a foreach()...
$kategorien = showCategory($con);
foreach ( $kategorien as $kat ) {
echo $kat.PHP_EOL;
}
Use this instead, because returning $kategorien will exit the loop, so it will only run once.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}
I am migrating from mysql to mysqli, and I am having trouble returning more than one row from the database in a query.
$db = new mysqli($hostname, $sql_us, $sql_us_pwd, $sql_db); // This is already connected
function db_query($db, $query, $type = 'object') {
global $db;
$result = $db->query($query);
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
return $row;
}
} else {
while($row = $result->fetch_object()) {
return $row;
}
}
mysqli_free_result($result);
}
$query = "SELECT * FROM `users`";
$user = db_query($db, $query);
print_r($user); // This is only returning the first row of results
I'm obviously trying to make a function where I can query the database and either return the results in an associative array or as an object. What am I doing wrong?
Use this code:
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;
You are using the return inside the while and return terminates the while loop after first iteration that's why you are getting only one row.
You need to store while loop values into array try this
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;
When you return in a function it stops executing at that point and goes back to the where it was called from with the value that you are returning.
In your case when you do a return $row, you are getting out of the function as soon as the first row is read.
Fix is:
$result = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$result[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$result[] = $row;
}
}
return $row;
You are only returning the first row. You have to return an array.
$arr = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
else {
while($row = $result->fetch_object()) {
$arr[] = $row;
}
}
return $arr;
Please tell, why this code is wrong?
function myres () {
$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
return $res;
}
while ($row = myres()->fetch_row()) {
echo $row[0];
}
P.S.
this code is working:
$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
while ($row = $res->fetch_row()) {
echo $row[0];
}
Here you call myres() every time, I think:
while ($row = myres()->fetch_row()) {
echo $row[0];
}
So every time $row contain first row of the result, and it will not stop. It will works fine, I think:
$res = myres();
while ($row = $res->fetch_row()) {
echo $row[0];
}
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function
$data = mysql_query("SELECT * FROM users);
now the data is stored in the $data variable. I would like to store the mysql data in an array and return that.
$data_array = mysql_fetch_assoc($data);
This would store the first row (the first array) of the data.
now to store all the rows I was wondering what should I do.
The standard approach:
$res = mysql_query($sql);
$data = array();
while(($row = mysql_fetch_array($res)) !== false) {
$data[] = $row;
}
// now $data is an array with all rows
http://php.net/manual/en/function.mysql-fetch-array.php
Returns an array of strings that
corresponds to the fetched row, or
FALSE if there are no more rows.
This approach works with mysql_fetch_* functions.
while ($row = mysql_fetch_assoc($data))
{
array_push($data_array,$row);
}
If your result set is big, it's not a good idea to do that. It could use a lot of memory on the process.
Having said that, you could store the whole thing on an array like this:
<?php
$query="select * from table_xyz";
$result = mysql_query($query) or die(mysql_error());
$arr_table_result=mysql_fetch_full_result_array($result);
function mysql_fetch_full_result_array($result)
{
$table_result=array();
$r=0;
while($row = mysql_fetch_assoc($result)){
$arr_row=array();
$c=0;
while ($c < mysql_num_fields($result)) {
$col = mysql_fetch_field($result, $c);
$arr_row[$col -> name] = $row[$col -> name];
$c++;
}
$table_result[$r] = $arr_row;
$r++;
}
return $table_result;
}
?>
Got the code sample from the PHP site.
$res = mysql_query($sql);
$data = array();
while(($row[] = mysql_fetch_array($res)) !== false) {
}