php while mysql_fetch_array inside while - php

i have this part of a code and i cant understund why the second loop inside the first does not work. I query two tables and i placed an echo inside the second table to see if it echo's but it does not either . thanx in advance
while($row = mysql_fetch_array($result))
{
echo "<li class=\"s01\"><a class=\"s03\" href=" . $row['link'] . "><span>". $row['onomaselidas'] ."</span></a>\n";
echo "<ul class=\"pn2\">\n";
$idd[]=$row['idwebsiteprimary'];
while($row2 = mysql_fetch_array($result2))
{
echo "test";
if($idd[$url]==$row2['idwebsite'])
{
echo "<li class=\"s01\"><span>". $row2['name'] ."</span></li>\n";
}
}
echo "</ul>\n";
}

After the first iteration of the first loop, the internal pointer of the second result set is at the end, so the second loop will not execute, because mysql_fetch_array() will return false immediately. If you want to it exactly as above - the second result set is not dependant on the first - you will need to do this:
// First, get the results of set 2 into an array
$resultset2 = array();
while ($row = mysql_fetch_assoc($result2)) $resultset2[] = $row;
while ($row = mysql_fetch_assoc($result)) { // Do your thang
echo "<li class=\"s01\"><a class=\"s03\" href=" . $row['link'] . "><span>".$row['onomaselidas'] ."</span></a>\n";
echo "<ul class=\"pn2\">\n";
$idd[] = $row['idwebsiteprimary'];
foreach ($resultset2 as $row2) { // Foreach sets it's pointer to the beginning every time, so this should work
echo "test";
if ($idd[$url]==$row2['idwebsite']) {
echo "<li class=\"s01\"><span>". $row2['name'] ."</span></li>\n";
}
}
echo "</ul>\n";
}
Alternatively, you can reset the internal pointer of $result2 on each iteration of the first loop by calling mysql_data_seek($result2, 0); like this:
while ($row = mysql_fetch_array($result)) {
echo "<li class=\"s01\"><a class=\"s03\" href=" . $row['link'] . "><span>". $row['onomaselidas'] ."</span></a>\n";
echo "<ul class=\"pn2\">\n";
$idd[] = $row['idwebsiteprimary'];
mysql_data_seek($result2, 0);
while ($row2 = mysql_fetch_array($result2)) {
echo "test";
if($idd[$url]==$row2['idwebsite']) {
echo "<li class=\"s01\"><span>". $row2['name'] ."</span></li>\n";
}
}
echo "</ul>\n";
}

Related

How can i get the quantity of every product outside of my while loop

I am fetching data from the database, the id, name and price. But inside the while loop is also a quantity. I dont know how to catch the quantity of every product. The quantity repeats with the new product inside the while loop. But if i want to catch the quantity of all products outside the while loop i only get one value. I hope someone can give me a answer with a post (i am a beginner).
Here comes the code
$arr = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$arr[] = $row;
$_SESSION['cart-checkout'] = $arr;
$quantity=$_SESSION['cart'][$id]['quantity'];
$sub_total=$price*$quantity;
echo "<div class='cart-row'>";
echo "<div class='col-md-8'>";
echo "<div class='product-name m-b-10px'><h4>{$name}</h4>
</div>";
echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>
{$quantity} item</div>";
echo "</div>";
echo "<div class='col-md-4'>";
echo "<h4>$" . number_format($price, 2, '.', ',') . "
</h4>";
echo "</div>";
echo "</div>";
$item_count += $quantity;
$total+=$sub_total;
}
You are halfway there. You are incrementing inside loop but to get total you need to print out outside loop. Also you need to declare variable total at the beginning.
Try this :
$arr = array();
$total = 0; //declare variable
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$arr[] = $row;
$_SESSION['cart-checkout'] = $arr;
$quantity=$_SESSION['cart'][$id]['quantity'];
$sub_total=$price*$quantity;
echo "<div class='cart-row'>";
echo "<div class='col-md-8'>";
echo "<div class='product-name m-b-10px'><h4>{$name}</h4>
</div>";
echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>
{$quantity} item</div>";
echo "</div>";
echo "<div class='col-md-4'>";
echo "<h4>$" . number_format($price, 2, '.', ',') . "
</h4>";
echo "</div>";
echo "</div>";
$item_count += $quantity;
$total+=$sub_total;//increment inside loop
}
echo $total;//print outside loop

I am unsure what kind of loop to use in php

I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';

How can I do a Line break

How can I do a line break every 5 scores? I have the following code but it shows me all the results in one line, and it needs to start a new line every 5 scores, without using a table.
<?php session_start();
include ("conexion.php");
?>
<?php
$correo=$_SESSION['s_username'];
$sql ="SELECT nombre_catalogo FROM catalogos WHERE email = '$correo'";
$res=mysqli_query($conexion,$sql);
echo "<table border='1' cellpadding='4' cellspacing='0'>";
$fecha = array();
while ($row20 = mysqli_fetch_array($res)) {
$fecha[] = $row20['nombre_catalogo'];
}
echo "<tr>";
echo "<td>Name</td>";
foreach($fecha as $fec) {
echo "<td>" . $fec . "</td>";
echo "<td>" . $fec . "</td>";
}
?>
For example, If I have 13 scores on my db it shows me one line like
*************
But its needs to be this way
*****
*****
***
array_chunk can be a solution.
while ($row20 = mysqli_fetch_array($res)) {
$fecha[] = $row20['nombre_catalogo'];
}
$fecha = array_chunk($fecha, 5);
foreach($fecha as $data)
{
foreach($data as $fec)
{
echo $fec;
}
# echo implode('', $data); // implode also can be used instead of nested loop.
echo '</br>';
}
You are looking for str_split() PHP DOC
See my example here:
<?php
$string = "0123456789ABCDEF";
// split the string every 5 chars, return as array
$result = str_split($string, 5);
// now create new string by imploding, with linebreak as glue
$result1 = implode(PHP_EOL, $result);
// OR
$result2 = implode("\r\n", $result);
print_r($result1);
print_r($result2);
?>

implementing next and back buttons for a slideshow

I'm trying to make a php slideshow and I'm almost done I just need to implement the next and back buttons which I thought were going to be easy, but apparently you can't increment indexes in php?
$sql = "SELECT pic_url FROM pic_info";
$result = $conn->query($sql);
$count = 0;
$dir = "http://dev2.matrix.msu.edu/~matrix.training/Holmberg_Dane/";
$source = "gallery.php";
if ($result->num_rows > 0) {
// output data of each row
$pic_array = array();
while ($row = $result->fetch_assoc()) {
$pic_array[$count] = $row['pic_url'];
$count++;
}
$index = 1;
echo "<img src= ' $dir$pic_array[$index]' />";
echo "<a href= '$dir$pic_array[$index + 1]'>next</a>";
echo "<a href= '$dir$pic_array[$index - 1]'>back</a>";
}
$conn->close();
?>
Try this
<?php
echo '<img src="'.$dir.$pic_array[$index].'">
next
back';
?>
I would suggest to place the url's in an array and loop over them.
$urls = ['website/url/for/image/image.jpg', 'another/url/image.jpg'];
foreach ($urls as $url) {
echo 'a href="http://'.$url.'"> Click </a>';
}
It is definitely more readable that way.

I want to print the output from DOMXPath in 2 colomns. 1. Car name 2. Price

I have tried the following code:
$car_row = $car_xpath->query('//h3[#class="adtitlesnb"]');
$car_row2 = $car_xpath->query('//div[#class="snb_price_tag"]');
$i = 0;
echo "<table><thead><tr><td>Car Name</td><td>Price</td></tr></thead><tbody>";
foreach($car_row as $row){
echo "<tr><td>";
echo $row->nodeValue;
echo "</td><td>";
echo $car_row2->nodeValue;
echo "</td></tr>";
}
echo "</tbody></table>";
You can't iterate over one array with foreach and expect the other to follow.
foreach essentially resets the current index on an array, then loops through calling next on the array until there are no elements left. Using reset and next you can emulate this for your second array as follows:
$car_row = $car_xpath->query('//h3[#class="adtitlesnb"]');
$car_row2 = $car_xpath->query('//div[#class="snb_price_tag"]');
echo "<table><thead><tr><td>Car Name</td><td>Price</td></tr></thead><tbody>";
$row2 = reset($car_row2); // set the internal array pointer to the begining
foreach($car_row as $row) {
echo "<tr><td>";
echo $row->nodeValue;
echo "</td><td>";
echo $row2->nodeValue;
echo "</td></tr>";
$row2 = next($car_row2); // retrieve the next node from car_row2
}
echo "</tbody></table>";

Categories