Fetch All Records against id's in Codeigniter - php

When I retrieve the data from database the output is following
I want to fetch records against these id's but when I try in my controller with for each it gives me only 1 record back
Here is my code
//fetch all the posts relative to user in session
$post_id['id'] = $this->message_model->get_post($id);
echo '<pre>'; print_r($post_id['id']);die;
foreach ($post_id['id'] as $key) {
$post_id = $key['post_id'];
$results['post_list'] = $this->Model_Frontend_Posts->get($post_id);
}
when i print $results['post_list'] it gives me only one record

$post_id['id'] = $this->message_model->get_post($id);
$array = array_column($post_id['id'], 'post_id'));
foreach ($array as $value) {
$results['post_list'] = $this->Model_Frontend_Posts->get($value);
}
Better to use array_column from the reference http://php.net/manual/en/function.array-column.php

Put it in an array so that it doesn't overrides on every loop. I guess this should solve it -
$results['post_list'][] = $this->Model_Frontend_Posts->get($post_id);
instead of
$results['post_list'] = $this->Model_Frontend_Posts->get($post_id);

Related

Build a php array in foreach loop that I can sort

I have a foreach loop that goes through to get information related to a photo.
It's basically this
foreach($medias as $image) {
$fullImage = $image->imageHighResolutionUrl;
$standardRes = $image->imageStandardResolutionUrl;
$caption = $image->caption;
$createdTime = date("Y-m-d",$image->createdTime);
$imageCode = $image->code;
}
Now I want to put that data into an array (I'm assuming), so I can sort it by $createdTime then loop through the data to run an "INSERT INTO table" mysql query for each photo.
I think you can store the data into an array by the following way -
$sl = 0;
foreach($medias as $image) {
$data[$sl]['fullImage'] = $image->imageHighResolutionUrl;
$data[$sl]['standardRes'] = $image->imageStandardResolutionUrl;
$data[$sl]['caption'] = $image->caption;
$data[$sl]['createdTime'] = date("Y-m-d",$image->createdTime);
$data[$sl]['imageCode'] = $image->code;
$sl++;
}
echo print_r($data);
Now you can a sort the $data variable whatever you want. Then loop through the data and entry into Database.
let me know if you any problem there.

adding items to array during foreach on the array

I wish to run a foreach on a load of ID's.
However each of the items in the foreach is a select query and if it finds more ID's they need to be added to the array that is being run in the foreach.
E.g
$ids = array();
foreach($ids as $id)
{
SELECT id FROM table WHERE otherid = $id;
foreach ($query2->result_array() as $row)
{
array_push($array, $row['id']);
}
}
This is obviously pseudocode so no need to correct my SQL etc. I just need for the foreach to continue if it finds more ID's.
Possible?
I have tried adding an & here -> foreach($ids as &$id) as somebody else on here has suggested in a similar question. This doesn't seem to work.
foreach actually makes a copy of your array to loop though, you will need to use while.
while(list($id_key, $id) = each($ids)){
//your code
$ids[] = $row[id];
}
You should simply be able to just reference the original array ie
foreach ($query2->result_array() as $row)
{
$id[] = $row;
}
This will automatically assign an auto incremented key to the the new array element and add it to the $id array. I assume this is what you are after.
Try to iterate with a variable:
$ids = array();
$i = 0;
while ($i < count($ids)) {
$query2->query(SELECT id FROM table WHERE otherid = $ids[$i]);
foreach ($query2->result_array() as $row)
$ids []= $row['id'];
$i++;
}
For similar problems, I have always used two different arrays. Such code can run a query for every id only one time. I don't think it would be possible with only one array+foreach;
The following code is pretty simple. It keeps finding new ids until there are no new ids.
$ids = array();
$new = array();
$new = $ids;
do {
foreach($new as $n) {
$new = array();
//// HERE PUT YOUR CODE TO RUN A QUERY AND MAYBE PUSH A NEW ID TO $new \\\\
}
$ids = array_merge($ids,$new);
} while (count($new)!==0);

Search PHP Array from results of SQL

I currently have an array in php that stores product names, normally 5 - 10. I would like to create something where the results of a SQL query is matched against the array to make sure they are all correct, and if not to show an error.
So far I have put the results into an array, then ran the query to get the results. I believe I need to put some sort of while loop with the results of the query and check the array in that while loop?
You have the array with the product name($products) and the results of the query($row).
While you loop trough the results you can check if the element is present,otherwise echo error and break the loop:
While(...) {
if(!in_array($row['retrivedprod'],$products)) {
echo 'error';
break;
}
}
You can cycle while receiving results from db with a while loop and checking results with the in_array function http://php.net/manual/en/function.in-array.php
$availability = 0;
$cart_products = array("book", "album");
$available_products = array();
while($row = mysql_fetch_array($result)) {
$available_products[] = $row['product'];
}
foreach($cart_products as $key => $value){
if (in_array($value, $available_products)){
$availability = 1;
}
}

Multiple for loops - how to print data

i want to make a website something like popurls.com, but I will use static data stored in MySQL database. Btw I use php/mysql.
In each list i want to show around 10 links (just like on popurls). In that case, if I would have 20 lists, i would need to make 20 'for' loops (for each particular list).
My question is; is there some better way to print that 20 lists instead of using 20 'for' loops in php.
a for loop or a foreach loop will work fine, but it will be a lot less coding if you just create a single for loop and push content into an array of arrays or an array of strings... you can then do whatever you'd like with the actual content (assuming we're grouping by a column category. I'll use an example that uses an array of strings (and the query that I reference is explained here: http://explainextended.com/2009/03/06/advanced-row-sampling/)
$query = mysql_query([QUERY THAT GETS ALL ITEMS, BUT LIMITS BY EACH CATEGORY]) or die(mysql_error());
$all_items = array();
while($row=mysql_fetch_array($query)){
if (!isset($all_items[$row['category']])){ //if it isn't created yet, make it an empty string
$all_items[$row['category']] = "";
}
$all_items[$row['category']] .= "<li><a href='".$row['url']."'>".$row['title]."</a></li>"; //concatinate the new item to this list
}
Now we have an array where the block of HTML for each section is stored in an array keyed by the name of the category. To output each block, just:
echo $all_items['category name'];
PHP's foreach http://php.net/manual/en/control-structures.foreach.php
Depends a lot on your data input but I could imagine something like this:
<?php
$lists = arrray('list1', 'list2', 'list3');
foreach ($lists as $current) {
$data = fetch_data_from_mysql($current);
foreach ($data as $link) {
echo "Link";
}
}
function fetch_data_from_mysql($current)
{
$list_data = array();
// do whatever is required to fetch the list data for item $current from MySQL
// and store the data in $list_data
return $list_data;
}
You just need two foreach loops. Assuming that you take the data from a mysql table (like you wrote), this could be like this:
$list_query = mysql_query("SELECT * FROM lists";)
while( $list = mysql_fetch_array($list_query) )
{
echo "<h1>{$list['title']}</h1>";
$query = mysql_query("SELECT * FROM entries WHERE list_id = {$list['id']}");
while( $entry = mysql_fetch_array($query) )
{
echo "- {$entry['name']}<br />";
}
}
You can get all the information from the database and parse it into an array, something like
array[<news type1>] = array( link1, link2, link3, etc);
array[<news type2>] = array( link1, link2, link3, etc);
and so on
and on the layout you can use
foreach ($newsCategory AS $categoryLinks) {
foreach ($categoryLinks AS $newsLink) {
<show the link and / or extra data>
}
}
Just store your links in two-dimensional array. That way you'll have to make 1 outer loop (iterating over lists) and 1 inner loop iterating over links in a particular list.
$links = array(
'science' => array('link1', 'link2', ...),
'sports' => array('link1', 'link2'),
// ... and so on
);
foreach ($links as $category => $urls) {
echo "Links in category: $category\n";
foreach ($urls as $url) {
echo $url . "\n";
}
}

php mysql data only shows one row with foreach loop

ok i have this and it doesn't show all the rows when fetched from mysql database its like this:
mysql_select_db($database_config, $config);
$query_cat = "SELECT * FROM cat";
$cat = mysql_query($query_cat, $config) or die(mysql_error());
$row_cat = mysql_fetch_array($cat);
$arr = array("TIT" => $row_cat['title'],
"DES" => $row_cat['description']);
foreach($arr as $ar){
echo $ar;
}
now it only displays the first row and then stops why is it not displaying all the fields and i don't wanna use while loop for it can anyone explain me the problem??
EDIT: Well basically i want to work it like this
$p = "{TIT}{DES}";
foreach($arr as $k => $p){
$p = str_replace("{".$k."}", $v, $p);
echo $p;
}
Now the problem is not with str_replace its with the loop or database because the database rows are not incrementing and displays only one data.
This will always return the first row. you are fetching only once that will return only first row.
Instead you must fetch all the rows using fetch statement in loop
while($row_cat = mysql_fetch_array($cat)){
echo $row_cat['title'];
echo $row_cat['description'];
}
From PHP mysq_fetch_array documentation:
"Returns an array that corresponds to the fetched row and moves the internal data pointer ahead"
As far as I know, you cannot retrieve every row without using a loop. You should do something similar to this:
while($row_cat = mysql_fetch_array($cat)){
echo $row_cat['title'];
echo $row_cat['description'];
}

Categories