PHP while(): how to stop after three times? - php

I'm trying to make a PHP photo gallery (yes, I've tried other solutions, none work with the setup I want) and I am trying to make this while loop stop after three times, because I want to show three thumbnails per table row. Here's my current code:
<table>
<tr>
<?php while($row2 = mysql_fetch_assoc($result)) { echo "
<td><a href='URL/".$row2['file']."'><img src='URL/".$row2['file']."' width='200' height='106' /></a></td>
"; } ?>
</tr>
</table>
I don't remember learning anything about stopping PHP loops, so please help! It'd be greatly appreciated.

So what you actually want is 3 images per row. I think this will work:
<table>
<?php
$i = 0;
while($row2 = mysql_fetch_assoc($result)) {
if($i%3==0)
echo "<tr>";
echo "<td><a href='URL/".$row2['file']."'><img src='URL/".$row2['file']."' width='200' height='106' /></a></td>";
if($i%3==2)
echo "</tr>";
$i++;
}
if($i%3!=0)
echo "</tr>";
?>
</table>

<table>
<tr>
<?php
$i=1;
while($row2 = mysql_fetch_assoc($result)) { echo "
<td><a href='URL/".$row2['file']."'><img src='URL/".$row2['file']."' width='200' height='106' /></a></td>
";
if($i>=3) break;
$i++;
} ?>
</tr>
</table>

try adding an AND to the while and compare to a counter
while($row2=mysql_fetch_assoc($result) && $i < 3)
set $i to 0 before the loop

why not limit the results returned in the original MySQL query? you can add limit to your Query like this:
limit 3
that way $result will only have the three rows so no need for extra PHP and less data from the DB in memory

you can add a counter, like:
$nr = 1;
while($row2 = mysql_fetch_assoc($result)) {
if ($nr < 4) {
do your thing;
}
$nr++;
}

Related

How could you use PHP and a SQL database to change HTML <h> content?

I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}

Splitting Long php generated HTML table?

I use a MySql query to select data from my DB and then print it in the form of a HTML Table. It works perfectly, fine but sometimes the table consists of hundreds of rows and the webpage looks incredibly akward. Is there a way to split the table side by side into 2 or 3 halves.
Present Output
Desired output
PHP
<?php
....
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
What would be the best way to achieve it?
Help would be appreciated.
You can use PHP to determine in your loop if the loop index is divisible by a certain number using something like this:
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
$rowCount = 1;
$numRows = count($results);
$maxRows = 12;
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
if($rowCount % $maxRows == 0 && $rowCount != $numRows) {
echo "</table><table class='dates' border='1'>";
}
$rowCount ++;
}
echo "</table>";
That's the basics of doing this. Basically in your loop you're testing each index to see if it's divisible by $maxRows, and if so then you're going to close your table and open a new one. You'll have to add the styling to place the tables side by side.
If you wanted to expand upon this concept you can set $maxRows to be an evaluation of $numRows. For instance if you wanted to split the items as close as possible to half in order to show just two tables, you could do... $numRows = count($results); $maxRows = round($numRows / 2);
Inspired by Robert Wade's answer:
<?php
....
echo "<h3>Classes attended :</h3>";
$i=0;
$maxRows=10;
foreach ($results as $dates) {
$a=$i/$maxRows == 0 ? "<table class='dates' border='1'>":"";
$b=$i/$maxRows == 0 ? "</table>":"";
echo $a;
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
echo $b;
$i++;
}
?>
At last, add some css style to the tables.
You can also use array_chunk() for splitting your results. Or instead of displaing a lot of tables next to each other you can make pagination and get only some range in your query. For example:
SELECT * FROM `clients` LIMIT 5, 10
Selects 10 rows beggining from row 5. Now, when you change your page, just change limit values.

do while in do while in php

That loop using do while, and it is working fine but when I add another do while in to this the second do while work but first do while only show one row not all 10 row. My code is below
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<?php do { ?>
<td><?php echo $row_Recordset1['nav']; ?></td>
<?php } while ($row_Recordset1= mysql_fetch_assoc($Recordset1)); ?>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
My date should be displayed once in a row but all the other td will be took from nav;
This is what I want:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
|2014-02-25|3.1|1.2|1.5|
But I'm currently getting:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
You should look at http://php.net/mysql_fetch_assoc
It moves the internal pointer one step ahead, so each time you do mysql_fetch_assoc() you get the next value, hence only your enternal do while is executed. That is, only date from the first row is output, and all other values are output in second do while;
Try this for exercise:
$q = mysql_query("SOME MYSQL QUERY WITH MINIMUM THREE ROWS");
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
print_r($f);
First of all, please don't bounce in and out of PHP like that...
<?php
do {
echo '<tr>
<td>';
echo $row_Recordset1['date'];
echo '</td>';
do {
echo '<td>';
echo $row_Recordset1['nav'];
echo '</td>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
echo '</tr>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
?>
Where do you fetch your first $row_Recordset1? Somewhere earlier than this code? You're going to output table cells (<td>) until you run out of rows. I don't think you want that.
Like so:
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<td><?php echo $row_Recordset1['nav']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Because each time you use mysql_fetch_assoc it does the following
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
Part of the reason this doesn't work is because you are re-assigning the value of the same variable. If you don't want to lose it then you cannot do it this way. At the very least it is a bad idea if you ever intend to do anything new with the code.
Next, I really recommend you populate an array with the data first before you ever do anything with outputting it. It is a very good idea to separate logic from output.
Your code should look more like this:
<?php
//Assumes you have already connected to a mysqli resource
$conditional_data_filtered = $mysqli->real_escape_string($conditional_data);
$sql = "SELECT date, nav FROM some_table WHERE some_column = '" . $conditional_data_filtered . "'";
if ($result = $mysqli->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$data = array(); //Make sure we start with a fresh array each time.
$data['date'] = $row['date'];
//Now I think you have a bunch of data in the nav you need to loop through
$nav_filtered = $mysqli->real_escape_string($row['nav']);
$subSql = "SELECT some_data FROM navigation WHERE some_identifier = '" . $nav_filtered . "'";
if ($subResult = $mysqli->query($subSql)) {
while ($subRow = $subResult->fetch_assoc()) {
$data['nav'][] = $subRow;
}
}
$rowList[] = $data;
}
/* free result set */
$result->free();
}
foreach ($rowList as $rowData) {
echo "<tr>";
echo "<td>" . $rowData['date'] . "</td>";
foreach ($rowData['nav'] as $navData) {
echo "<td>" . $navData['some_info'] . "</td>";
}
echo "</tr>";
}
?>
Just a note: If you really don't have sub-data and just want to output the next column then you don't need a sub-loop. You just need to echo the contents of the column like you did with the first one. Then you can get rid of the sub-loops I have shown above and just put it within the first loop.

SQL Image Database assembling rows into HTML cells and rows

I have a database of images which I want to output as a gallery ...
I want to display each image in its own cell <td>image1</td> and limit the number of cells to 7 per row.
<tr>
<td>image1</td><td>image2</td><td>image3</td><td>image4</td><td>image5</td><td>image6</td><td>image7</td>
</tr>
Then a new row would be created and continue to output all the images.
<tr>
<td>image8</td>
and so on ..
I know how to do a query, but I am lost as to how to assemble the rows into the format I am looking for.
Can anyone please help me it would be greatly appreciated. Thanks.
First run your query, then get the mysql_fetch_assoc in a variable. Then echo your beginning tags for the table and tr. Then create a foreach loop of the query assoc, as another variable such as row, and echo $row['image'] in a td. This will add a new td with the image for every entry in the database. Then echo your closing tags for the tr and table.
$query = mysql_query("SELECT image FROM table_name");
$query_a = mysql_fetch_assoc($query);
echo "<table><tr>"
foreach ($query_a as $row)) {
echo "
<td>" . $row['image'] . "</td>
";
}
echo "</tr></table>";
Not tested, but try something like this
<table>
<?php
// make sure there is at least 1 row first
$cnt = 0;
$while($row = mysql_fetch_assoc($query))
{
if(++$cnt == 1) {
echo '<tr>';
} elseif($cnt % 7 == 0) {
echo '</tr><tr>';
}
// show images in <td>'s
echo "<td>" . $row['image']. "</td>";
}
echo '</tr>';
?>
</table>
Keep it simple:
Query the database to get the desired information, loop through the results, construct a new row come each new loop.
$sql = "Select * from table";
mysql_query($sql) or die(mysql_error());
if(mysql_num_rows !=0)
{
// Found at least one record, create table
echo "<table>";
echo "<tr>";
while($row = mysql_fetch_assoc($sql)
{
$cell_count = 0;
// Create a new row for each record found
echo "<td>" . $row['image_column']. "</td>";
$cell_count++;
if($cell_count == 7)
{
echo "</tr>";
echo "<tr>";
$cell_count = 0;
}
}
// Close the table
echo "</tr>";
echo "</table>";
}

PHP/MySQL Output Data in TD's

How would I go about imposing a restriction on the number of HTML table columns when querying the database.
For example, I have a MySQL table with the following values:
myTable:
id color
1 red
2 blue
3 green
4 pink
5 purple
And when I run my query, instead of showing all rows in traditional table rows, e.g.
<table>
<?php
while {
echo "<tr><td>$row['color']</td></tr>;
}
?>
</table>
Instead, I would like to impose something where, every three td's, a new tr is created.
For example, it would output something like this:
<table>
<tr>
<td>red</td>
<td>blue</td>
<td>green</td>
</tr> <-- Notice how after 3 columns, a new table row is created.
<tr>
<td>pink</td>
<td>purple</td>
</tr>
</table>
Any way to achieve this?
In order to achieve this, you can use a combination of a counter and a modulus (%) operator:
<table>
<?php
$count = 0;
while($row = mysql_fetch_array($results)) {
$outputTr = ($count % 3) == 0;
if($outputTr) echo '<tr>';
echo '<td>' . $row['color'] . '</td>';
if($outputTr) echo '</tr>';
$count++;
}
?>
</table>
To achive this, put in a simple counter that resets every 3 table datas.
<?php
echo "<table><tr>";
$count = 0;
foreach($data as $key => $color)
{
if($count == 3)
{
$count = 0;
echo "</tr><tr>";
}
$count++;
echo "<td>".$color."</td>";
}
echo "</tr></table>";
?>

Categories