How to get each value in a column of database in php - php

I don't have enough knowledge about this criteria:
I want to loop inside the for each loop to get all values in a particular column.
For example: I got the values from DB through get_result and store the result in $results.
After that use:
for each($results as $result)
❴
$output = $result->message
❵
Where message is a column in DB.
I want to loop over all the messages instead of storing last one by replacing.
Can you please give me suggestions on how to loop inside for each?

Try this:
$output[] = $result ->message;
Now $output will contain all messages on index 0, 1, 2 ...
You are facing the issue because:
$output=$result ->message;
the above line is present inside the loop, and each new iteration onerride the old value.

Well if you just looking for foreach inside foreach then you can try the following.
<?php
foreach($results as $result){
$output=$result->message;
foreach($output as $messages){
echo $messages;
}
}
?>

You don't need to put the message into another variable. You can do whatever you need to do inside the loop. For example, if you are displaying the messages, you can get it done inside the loop:
foreach ($results AS $result) {
echo $results->message . "<br>";
}

Related

How to put foreach in array

I have this
$homedata = $user->getbanks();
foreach ($homedata as $data)
echo json_encode(array("replies" => array(array("message" => $data->bankname))));
I have this put the result am getting is only one array from the list. I want to get all.
If I understand your requirement correctly, you need the banknames in an array replies within a key message. For that the below code will do the job. But you can optimize the query for better performance.
$homedata = $user->getbanks();
$banks['replies'] = [];
foreach ($homedata as $data) {
$banks['replies'][]['message'] = $data->bankname;
}
print_r(json_encode($banks)); exit;
Further, you were only getting the first content because you are overriding the previous content when you iterate using foreach.

I want a query result using codeigniter

i have an array result. i want to print 2 rows(product data) in first page.
next 2 rows in second page and so on. if anybody knows this,please help me to solve it
my array
$data['product_list']
foreach($data['product_list'] as $dat)
{
echo $dat->prd_id;
echo $dat->prd_name;
}
You are doing a foreach loop on an associative array and then trying to access the the contents as objects by using ->. I can only given assumption of what you might be doing. If your array is already populated with a name and id like you have described in your foreach loop this is how you would access the contents in the loop:
foreach($data['product_list'] as $dat)
{
echo $dat['prd_id'];
echo $dat['prd_name'];
}
That is how you would print out the contents providing you had the data stored in your array like so:
$data['product_list'][0] = array('prd_id'=>'id0','prd_name'=>'name0');
$data['product_list'][1] = array('prd_id'=>'id1','prd_name'=>'name1');
$data['product_list'][2] = array('prd_id'=>'id2','prd_name'=>'name2');
Better you try with array_slice();
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>

Reusing a PDO Query block in another area best practices

I'm just transitioning over to PDO from mysql_
I have been pointed in the direction of some helpful tutorials, but there is one issue I haven't seen raised and I wanted to check I am doing it in the 'correct way'
I want to reuse the same values that I am dropping into an array in two different areas (both different PHP code blocks) within one page. Both are styled differently depending on media queries (hidden/not hidden etc.)
At the moment I am running a query like this:
<?php
$data = $pdo->query("SELECT * FROM sitelinks WHERE `show` = 'yes' ORDER BY `Order` ASC")->fetchAll();
foreach ($data as $links)
{
echo "\n<li class=\"linkitem\">{$links['Text']}</li>";
}
?>
So my understanding is that I should then be able to load and loop through the $links variable somewhere else on the page. I am doing that like this:
<?php
foreach ($data as $links)
{
echo "\n<li class=\"desktoplinkitem\">{$links['Text']}</li>";
}
?>
Is that correct? It's working, but seems a little crazy to use ($data as $links) again. Following on, really stupid question but why does the $data variable then have to be stored as $links. Could it not just be run as foreach ($links) to begin with?
Assuming you do not write some code later that changes/destroys the $data variable between these 2 usages there is no problem doing this. It in fact reduces the runtime to reuse data if you can rather than getting it again.
What you need to remember is that ->fetchAll() returns all the rows from your resultset into an array. Its your array from then on, which you can do whatever you like with once the ->fetchAll() is completed
Second question:
the foreach
foreach ($data as $links)
processes over an array $data and returns one occurance (row in your case) at a time. So you have to give it another variable name. That name can be anything.
If you use sensible names for things they normally look like this
foreach ($rows as $row)
foreach ($sitelinks as $sitelink)
Using the plural for the original array and the singular for the single occurance returned by each iteration over the array.
So I would amend your code like so:
<?php
$sitelinks = $pdo->query("SELECT *
FROM sitelinks
WHERE `show` = 'yes'
ORDER BY `Order` ASC")
->fetchAll();
foreach ($sitelinks as $sitelink) {
echo "\n<li class=\"linkitem\">{$links['Text']}</li>";
}
?>
And the second use of the array
<?php
foreach ($sitelinks as $sitelink) {
echo '\n<li class=\"desktoplinkitem\">{$sitelink['Text']}</li>";
}
?>

array isn't combining with loop in php

i've a array problem couldn't just solve it:
here's the code that is already in a foreach loop. i'm getting the $row->class_id value from this loop. it works fine and get me the total students row within an array and i preserved it in $total_student_of_this_class variable. i used another foreach loop for storing the result of first loop and then second loop and so on. but this loop gives only first loop result.
i need to combine the all array of total iteration of the loop.
$total_student_of_this_class =
$this->db->select('student_id')->where('class_id',
$row->class_id)->get('student')->result_array();
echo count($total_student_of_this_class);
// prints 2 in the first row of the output table and 5 in the second
row for me.
$total_student = array();
foreach ($total_student_of_this_class as $tt)
{
$total_student[] = $tt;
}
echo '<pre>';
print_r($total_student_of_this_class);
echo '</pre>'
echo count($total_student);
// prints only 2 outside the loop (not 7)
pls someone help me.
The problem here is seems to be with $total_student = array();: initializing array inside an other loop it always starts it from zero values array, so you get only results from one iteration inside it and doesn't collect all datas.
You can also look at array_merge php function.

PHP: foreach loop inside PHP variable?

I'm trying to dynamically generate html select options using PHP based on whatever its stored in mysql database.
the column that stores the data called sizez.
the data in that column is stored like so:
small,large,xlarge,xxlarge
so basically the data is separated by a comma.
now in my php page I simply pull the data and display it on my page using a while loop for each product that is stored in the mysql database.
the issue that I am having is that I need to generate a select option dropdown list based on the sizez column for each item.
for that I am using the explode() function and it will generate the select option successfully too.
however, the issue is that it will only get the strings from the first sizez column and ignores the rest of the items But it will display the string from the first column for other items too and it repeats them!
this is my code:
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$sizez = $row["sizez"];
$sizez = preg_replace('/\.$/', '', $sizez); //Remove dot at end if exists
$array = explode(',', $sizez); //split string into array seperated by ','
foreach($array as $value) //loop over values
{
//echo $value . PHP_EOL; //print value
$sizesOption .='<option>'.$value.'</option>';
}
$all_list .="<select>
'.$sizesOption.'
</select>";
so I thought to put the foreach($array as $value) inside the $all_list .= but that approach is wrong.
could someone please advise on this issue?
any help would be appreciated.
EDIT:
The expected result should be like this:
item one item two item three
small large small
large xxlarge xxlarge
However, with my code I get the result like this:
item one item two item three
small small small
large large large
small small
large large
small
large
so basically, it will get the sizes column from the first item and it will repeat it inside select options for other items exactly like the example above.
Since you are generating separate <select> for each iteration, you have to reset $sizeOptions. I suggest using arrays instead of just concatenating strings:
$allList = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$sizesOption = array();
$sizez = preg_replace('/\.$/', '', $row["sizez"]);
$array = explode(',', $sizez);
foreach ($array as $value) {
$sizesOption[] = "<option>{$value}</option>";
}
$all_list[] = '<select>'.implode("\r\n", $sizesOption).'</select>';
}
echo implode("\r\n", $allList);
From what you have posted it looks like you're regenerating $all_list in every iteration of your while loop.
So if you echo $all_list outside of the while loop it will only have the last iteration available - all the other ones having been overwritten during the process of the while loop.
Maybe I am wrong. but as simple as:
$all_list ="<select>".$sizesOption."</select>";
Close the opening braces for while loop before the '$all_list .="' statement.You are iterating the statement inside while loop.
`
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
$id = $row["id"];
$sizez = $row["sizez"];
$sizez = preg_replace('/\.$/', '', $sizez); //Remove dot at end if exists
$array = explode(',', $sizez); //split string into array seperated by ','
foreach($array as $value) //loop over values
{
//echo $value . PHP_EOL; //print value
$sizesOption .='<option>'.$value.'</option>';
}
}
$all_list .="<select>
'.$sizesOption.'
</select>";
`
May be this will work
I figured it out. Thanks to Justinas's answer. I realized that I had to put my php variable inside the while loop.
so all I had to do was to put $sizesOption =array(); inside my while loop and everything works fine now.
P.S. i haven't made any other changes to my code above.

Categories