replace while loop with foreach - php

I have a php code like this:
$categories_query = tep_db_query("select categories_id, categories_name from categories order by categories_name");
while ($categories = mysql_fetch_array($categories_query)) {
$categories_array[] = array('id' => $categories['categories_id'], 'text' => $categories['categories_name']);
}
question is how can I replace the while loop with for example foreach so I can first fetch mysql array, then I want to edit some values and then pass it on to a loop? I tried different versions of loops but they don't give me the same result as the while loop does.

PHP doesn't have a mysql_fetch function that delivers all rows at once which could be used in a foreach look.
Try to get all rows in one loop and build an array with all rows. Then, iterate over this array and perform operations as you described.

what you have tried looks good. there is no "fetch all" function in the old and deprecated mysql library. you should switch to mysqli or PDO instead.
in PDO you can just grab all the result-data with $statement->fetchAll() for example.
if you still want to solve your problem with the old mysql library, then:
$categories_query = tep_db_query("select categories_id, categories_name from categories order by categories_name");
while ($categories = mysql_fetch_array($categories_query))
{
$categories_array[] = array('id' => $categories['categories_id'], 'text' => $categories['categories_name']);
}
// do something with your $categories_array here
foreach($categories_array AS $array => $row)
{
// you can output / access each row here e.g. with: $row['id']
// or you can do a second foreach-loop for the columns:
foreach($row AS $col => $data)
{
echo $data;
}
}

From the looks of it the purpose of your loop is just to rename some table columns.
Just do:
<?php
$categories_array = mysqli_query( mysqli_fetch_assoc($con,"SELECT categories_id AS id, categories_name AS text FROM categories ORDER BY categories_name") );
?>

Related

How to stop second foreach from looping more than once

I have an query which select all ids from a table. Once I have all id's, they are stored in an array which I foreach over.
Then there is an second array which pull data from url (around 5k rows) and should update DB based on the id's.
The problem - second foreach is looping once for each ID, which is not what I want. What I want is to loop once for all id's.
Here is the code I have so far
$query = " SELECT id, code FROM `countries` WHERE type = 1";
$result = $DB->query($query);
$url = "https://api.gov/v2/data?api_key=xxxxx";
$api_responce = file_get_contents($url);
$api_responce = json_decode($api_responce);
$data_array = $api_responce->data;
$rows = Array();
while($row = $DB->fetch_object($result)) $rows[] = $row;
foreach ($rows as $row) {
foreach ($data_array as $key => $dataArr) {
$query = "UPDATE table SET data_field = $dataArr->value WHERE country_id = $row->id LIMIT 1";
}
}
The query returns 200 id's and because of than the second foreach (foreach ($data_array as $key => $dataArr) { ... }) execute everything 200 times.
It must execute once for all 200 id's not 200 * 5000 times.
Since the question is aboot using a loop, we will talk about the loop, instead of trying to find another way. Actually, I see no reason to find another way.
->Loops and recursions are great, powerful tools. As usually, with great tools, you need to also find ways of controlling them.
See cars for example, they have breaks.
The solution is not to be slow and sit to horses era, but to have good brakes.
->In the same spirit, all you need to master the power called recursions and loops is to stop them properly. You can use if cases and "break" command in PHP.
For example, here we have a case of arrays containing arrays, each first child of the array having the last of the other (1,2,3), (3,4,5) and we want to controll the loop in a way of showing data in a proper way (1,2,3,4,5).
We will use an if case and a counter :
<?php
$array = array( array(-1,0,1), array(1,2,3,4,5), array(5,6,7,8,9,10), array(10,11,12,13,14,15) );
static $key_counter;
foreach( $array as $key ){
$key_counter = 0;
foreach( $key as $key2 ){
if ( $key_counter != 0 ) {
echo $key2 . ', ';
}
$key_counter = $key_counter + 1;
}
}
Since I dont have access to your DB is actually hard for me to run and debbug the code, so the best I can say is that you need to use an if case which checks if the ID of the object is the ID we want to proccess, then proceed to proccessing.
P.S. Static variables are usefull for loops and specially for recurrsions, since they dont get deleted from the memory once the functions execution ends.
The static keyword is also used to declare variables in a function
which keep their value after the function has ended.

Why PHP Mysql query inside a foreach loop always returns the first result from database?

I'm trying to run a MYSQL query inside a foreach loop.
here's the scenario:
I have a comma separated string with some names in it.
I use explode() and foreach() to get the separate values/names from this comma separated string.
Then I need to search mysql database for each of these values/names that I get from this string and if that value exists in the database, I then get its ID and create a new recrord in another table in the database.
However, when I run my code, I only get the ID of the first instance from the comma separated string.
my mysql database looks like this:
id category_name
3 Hotel
4 Restaurants
This is my code:
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
///i do the explode and foreach here///
$arrs = explode(',', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
}
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>;
}
so when the i run my code, I get the ID of the Hotel twice like so:
3
3
I'm expecting it to be like below based on what I have in MYSQL:
3
4
Could someone please advice on this issue?
First of all such things should be done using prepared statements. Not only it is easier and faster, but also more secure. Remember to always use prepared statements.
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
$stmt = $db_conx->prepare('SELECT * FROM categories WHERE category_name=?');
$stmt->bind_param('s', $cat);
foreach(explode(',', $biz_cat) as $cat){
$cat = trim($cat); // remove extra spaces at the beginning/end
$stmt->execute();
// we fetch a single row, but if you expect multiple rows for each category name, then you should loop on the $stmt->get_result()
$row99 = $stmt->get_result()->fetch_assoc();
// echo it in the loop or save it in the array for later use
echo $row99['id'];
}
In the example here I prepare a statement and bind a variable $cat. I then explode the string into an array on which I loop straight away. In each iteration I execute my statement, which in turn produces a result. Since you seem to be interested only in the first row returned, we do not need to loop on the result, we can ask for the array immediately. If you would like to loop just replace
$row99 = $stmt->get_result()->fetch_assoc();
with
foreach($stmt->get_result() as $row99) {
echo $row99['id'];
}
Once you get the id in the array, you can either print it out or save it into an array for later use.
As of now, you are re-assigning a new value to scalar variable $catIDS for each record returned by the query, then you echo it one you are done looping. You would need to put the echo/insert logic inside the loop (or maybe store the values in array).
Another thing to note is that you are splitting with , (a single comma), but you have a space between the two words. As a result, the second value (Restaurant) starts with a space, which will cause the query to return an empty resultset. You probably want to split with , (a comma followed by a space).
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(', ', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>';
}
}
The code below can do what you need.
Update INSERT YOUR NEW DATA HERE
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(',', $biz_cat);
foreach ($arrs as $arr) {
$query99 = mysqli_query($db_conx, "SELECT * FROM categories WHERE category_name='$arr'");
while ($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)) {
$catIDS = $row99['id'];
// INSERT YOUR NEW DATA HERE
echo $catIDS . '<br/>';
}
}

Column keys to fetch for select_avg active record result in CodeIgniter

I have this active record query.
$this->db->select_avg('score');
$this->db->select_min('time');
$q = $this->db->get_where('place_rvw', array('place_id' => $place_id));
I want to know what array keys I will use to access the results if I use result_array() since the select statement uses functions. Will the code below work?
foreach ($q->result_array() as $row)
{
$score_mean = $row['AVG(score)'];
$day_one = $row['MIN(time)'];
}
Thanks in advance!
If you don't know what they keys are you could always use PHP to print them for you.
foreach ($q->result_array() as $row) {
print_r(array_keys($row));
}

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