str_replace within a while loop - PHP - php

I'm having a problem with str_replace within a while loop.
I've created a couple of variables before a while loop:
$c = 0; // This represents the first object within an array EG: array[0]
$i = 1; // This represents the first [image#] tag within $articleContent
What I'm trying to achieve is, when the user inputs '[image1], [image2], [image3]' etc into the $articleContent, to replace the [image#] tags with an <img src=""/> containing the file path located within the unserialized array.
The $images[$c] variable is pointing to the file path with the id of [0] within the array.
The issue:
My expectations were that the loop would naturally count through each $c and $i, labeling each [image#] and array object accordingly, then replacing the [image#] tag with the <img src='images/$imageSplit[$i]'/>, however this has not been the case.
The current functionality:
Say I have three articles being echo'd by the loop. each with three [image#] tags in [image1], [image2] and [image3]. The first article will ONLY show the first image, the second article will only show the second image, and the third article will only show the third.
If anyone could point me in the right direction for the script to replace the image tags accordingly then that'd be much appreciated.
Here is my code so far:
$sql = "SELECT * FROM articles";
$res = mysql_query($sql);
$i = 1; // [image#]
$c = 0; // Array object #
echo "<br/><br/>";
while($row = mysql_fetch_assoc($res)){
$title = $row['title']; // Grabs the title
$articles = $row['articleContent']; // Grabs the article
$images = unserialize(base64_decode($row['image']));
$imageSplit[$i] = $images[$c]; // [image1] = array[0]
$articles = str_replace("[image$i]","<img src='images/$imageSplit[$i]' width='300px' height='auto'/>","$articles");
// str_replace is only applied once per loop
echo "Title: $title<br/>
Content: $articles<br/>
c = $c<br/>
i = $i<hr/>";
// All variables, including $c and $i are both echoing out correctly, however $i is only being applied correctly once every loop
$c++;
$i++;
}

Say I have three articles being echo'd by the loop. each with three
[image#] tags in [image1], [image2] and [image3]
That means you will have to nest 2 loops: a)foreach article, b)foreach one of its images.
Here is a possible way of doing it (I commented out some of the lines that won't be needed):
$sql = "SELECT * FROM articles";
$res = mysql_query($sql);
//$i = 1; // [image#]
//$c = 0; // Array object #
echo "<br/><br/>";
while($row = mysql_fetch_assoc($res)){
$title = $row['title']; // Grabs the title
$articles = $row['articleContent']; // Grabs the article
$images = unserialize(base64_decode($row['image']));
// $imageSplit[$i] = $images[$c]; // [image1] = array[0]
foreach ($images as $index => $img_url) {
$i = $index + 1;
$articles = str_replace("[image$i]","<img src='images/$img_url' width='300px' height='auto'/>","$articles");
}
echo "Title: $title<br/>
Content: $articles<br/>
<br/>
<hr/>";
// All variables, including $c and $i are both echoing out correctly, however $i is only being applied correctly once every loop
//$c++;
//$i++;
}

Related

loop through same variables in for loop

How can I loop through each of these variable within a for loop?
$prod1 = $_POST['Option1']; //get input text
$prod2 = $_POST['Option2']; //get input text
$prod3 = $_POST['Option3']; //get input text
$prod4 = $_POST['Option4']; //get input text
for ($i=1; $i < 5; $i++) {
$prod = $prod . $i;
}
when I echo $prod . $i inside the loop, I want it to display the variable value.
You should be better off with storing your data in an array and then looping over the array:
$products = [
$_POST['Option1'],
$_POST['Option2'],
$_POST['Option3'],
$_POST['Option4']
];
foreach ($products as $prod ) {
echo $prod;
}
Alternatively, You can also iterate over the POST directly:
for ($i=1; $i < 5; $i++) {
echo $_POST['Option' . $i];
}
You can loop through the $_POST variable - it's an array.
foreach ($_POST as $prod)
{
echo $prod;
}
(Obviously if there are other values in the $_POST array then you would need to check the key name first before deciding to use it.)
N.B. We don't know the source of this data (is it a HTML form) but it might make more sense for them to be submitted inside a single array to begin with - so all of the values would be accessed through $_POST["options"] for example, and you'd just loop through that specific list.

PHP/MySQLi - Combining for and while

I'm attempting to combine two pages into one for simplicity, however to do so, I need to find a way to combine a for() loop from one page with a while() loop from the other page, so that they both work in the same way.
This is what they currently are:
for($i = 0; $i < $count; $i++) {
and
while($widget = $grabWidget->fetch_array()) {
As you may see, the for() loop does not loop through a MySQLi query, but rather an array of values which are identical to that of what is also in a database.
The second while() loop grabs a set of identical values from the database. However they both must stay on their current bases.
My question is, can both loops be combined into one, while still being able to loop through individual database and array elements?
Thanks in advance :)
EDIT: As requested, here are both the usages for the loops.
if($grabWidget = $db->query("SELECT * FROM editor_widgets"))
{
while($widget = $grabWidget->fetch_array())
{
$id = $core->input($widget[1]);
$coords[0] = $core->input($widget[4]);
$coords[1] = $core->input($widget[5]);
$temp = $core->input($widget[2]);
$content_out = $core->output($widget[3],true);
and
if(isset($_POST['widgets']))
{
$widget = $_POST['widgets'];
$count = count($widget);
for($i = 0; $i < $count; $i++)
{
$id = $core->input($widget[$i][0]);
$content_in = $core->input($widget[$i][1]);
$coords[0] = $core->input($widget[$i][2][0]);
$coords[1] = $core->input($widget[$i][2][1]);
$temp = $core->input($widget[$i][3]);
$content_out = $core->output($widget[$i][1],true);
The new simplified page must have the ability to loop through from either an array OR a MySQLi query. So basically, I want to use the for() loop and have it also work with MySQLi
Add an interator $i thats in while thats it.
$i=0;
while($widget = $grabWidget->fetch_array()) {
++$i;
// YOUR CODE
}

PHP run query off each array variable and return results in table

I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.

Why doesn't my loop echo for all iterations?

I'm trying to make a tag cloud system getting its values from PHP/SQL but it seems to work erratically, only giving a handful of the expected results. What's causing this odd behaviour?
As far as I can tell it should loop through a total of 20 times (0-19) and each time it adds a string into an array.
The system starts out by getting the 20 most popular tags from my database in descending order, once its got this I create a string and set the font size. This string is then stored in an array and is echoed out using a random number array giving a random order to the cloud.
I then increase the value of i for my loop iteration whilst decreasing the font size for the next less popular tag.
<h1>Tag Cloud</h1>
<?php
$sql = "SELECT * FROM tags ORDER BY count DESC";
$tags_query = mysqli_query($db_conx, $sql);
$i = 0;
$tag_array = array();
$tag_size_max = 36;
$tag_size_min = 16;
$numbers = range(0, 19);
shuffle($numbers);
do {
$row = mysqli_fetch_array($tags_query, MYSQLI_ASSOC);
$tag = $row["tag"];
$tag_count = $row["count"];
$tag_array[] = "<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
echo $tag_array[$numbers[$i]];
$i++;
$tag_size_max--;
} while ($i < 20);
?>
You can see it kind of working in the footer of my site http://www.vwrx-project.co.uk
It seems that you're trying to echo $tag_array element with index which isn't yet in the array itself.
You would probably need two loops - first to fill the $tag_array, and another one to echo them.
Do you have proper ERROR_LEVEL - there should be some notices about missing indexes - at least if I'm ready your code correctly ;)
Something like this:
// fill the array
for ($i=0; $i<20; $i++) {
$row = mysqli_fetch_array($tags_query, MYSQLI_ASSOC);
$tag = $row["tag"];
$tag_count = $row["count"]; // this seems to be unused
$tag_array[] = "<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
}
// echo the array
for ($i=0; $i<count($tag_array); $i++) {
echo $tag_array[$numbers[$i]];
}
I think the problem occurs in the following line
echo $tag_array[$numbers[$i]];
when you push to the array
$tag_array[] = "<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
you get an index for each tag , for example
[0] =>"<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
[1] =>"<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
for every iteration
and then in the following line you echo a random element (probably different form the one you just created )from the array by using the $number array which is not ordered after shuffling it.
I suggest you shuffle the results from the database first with
$results = array();
while($row =mysqli_fetch_array($tags_query, MYSQLI_ASSOC))
{
array_push($results, $row);
}
shuffle($results);
and then create a "normal" loop for printing in the tags using the results array.
Also if you need only 20 tags why not adding LIMIT 20 to your query to simplify the code?
Hope it helps

PHP Nested Loop. How on the second loop print items according to the id of the first loop?

I need to print a wine list from a database.
I need to print at first a categorie and after all the items that are inside. Thats the order. And i have multiple categorie. So at the end the result will be categorie1, many items, categorie2 many items...
This is the code that i write from now: I think that my problem is to print items according to the id of the alcool_categorie !!
$q_vine = "SELECT * FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
$q_bouteille = "SELECT * FROM alcool_item where ALCNID = '$alid'";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
for($i = 0; $i < $n_vine; $i++){
echo mysql_result($r_vine,$i,'named').'<br/><br/>';
for($z = 0; $k < $n_bouteille; $k++){
echo mysql_result($r_bouteille,$k,'name').'<br/>';
}
}
I think it's best to use a "JOIN" in your query and then order the rows in the way you want them to be ordered, then you'll only need one loop. While running the loop you compare the category name with the previous category name and if it changes display the category name.
Example
$sql = "SELECT categoryName, bottleName FROM category INNER JOIN bottle ON category.categoryId = bottle.categoryId ORDER BY category.categoryId";
$result = mysql_query($sql,$connection);
$categoryName = ''; //just to make sure the first time the Category is named
while ($row = mysql_fetch_assoc($result)) {
if($categoryName != row['categoryName']){
$categoryName = row['categoryName'];
echo '<h1>'.$categoryName.'</h1>';
}
echo row['bottleName'].'<br/>';
}
Try this after correctly giving the category id field name in the query and inside the first while loop.
$q_vine = "SELECT id, named FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
while ($row = mysql_fetch_assoc($r_vine)) {
$categories[$row['id']] = $row;
}
$q_bouteille = "SELECT name, ALCNID FROM alcool_item ";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
while ($row = mysql_fetch_assoc($r_bouteille)) {
$items[$row['ALCNID']] = $row;
}
foreach ($categories as $category_id=>$category) {
echo "<ul><li>{$category['named']}<ul>";
foreach ($items[$category_id] as $item) {
echo "<li>{$item['name']}</li>";
}
echo "</ul></li></ul>";
}
You will want to look into PHP's foreach construct. Foreach loops through an entire array of results, for each element inside the array, it extracts its value and optionally also its key. This will not require the use of mysql_num_rows.
Instead of calling mysql_result, you could use mysql_fetch_assoc to get a row's value from your mysql_query. The row's To get all values, you can incorporate this into a loop even. If you do the latter, you can create your own array of key/value pairs and use this inside a foreach construct.
Also note that the use of mysql is outdated, you will want to use mysqli now, which is very similar to mysql.

Categories