PHP For Loop dynamic from database - php

I'm generating my check boxes from this code. But, I'm having difficulty with making it generate by 5 outputs then once the 5th output is displayed it should skip to the next line.
Would appreciate any help.
<?php
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
while($row = mysql_fetch_array($result))
echo '<input type="checkbox" name="type" value='.$row['type_id'].'>'
.'<label>'.$row['type_name']. '</label>'.'<br>'.'<br>';
?>

<?php
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
$i=1;
while($row = mysql_fetch_array($result))
{
echo '<input type="checkbox" name="type" value='.$row['type_id'].'><label>'.$row['type_name']. '</label>';
if($i%5==0)
{
echo "<br>";
}
$i++;
}
?>

$result = mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
$i=0;
while($row = mysql_fetch_array($result)){
if($i%5 == 0){
//skip to next line
//continue??
}
echo '<input type="checkbox" name="type" value='.$row['type_id'].'>'.'
<label>'.$row['type_name']. '</label>'.'<br>'.'<br>';
$i++;
}

Do like this
<?php
$i =1;
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
while($row = mysql_fetch_array($result)){
if($i == 5){
echo "<br>";
$i = 1;
}
else
echo '<input type="checkbox" name="type" value='.$row['type_id'].'>'
.'<label>'.$row['type_name']. '</label>';
$i++;
}
?>

You question is how to skip every 5th entry and to put a linebreak instead?
Have a try like this:
<?php
$i=0;
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
while($row = mysql_fetch_array($result))
{
if (++$i % 5)
echo sprintf ( '<input type="checkbox" name="type" value="%s">'
.'<label>%s</label>'."\n",
htmlentities($row['type_id']),
htmlentities($row['type_name']) );
else
echo "<br>\n";
}
?>
In addition to iterating over all entries in the result just use a counter you increment with every iteration. Then, inside the iteration, only output the current entry if the counter modulo 5 is not zero. So if it is not a clean multiple of 5.

Related

How to add an additional option to an option form which is filled with a db query

How can I add an extra <option> with a value of all to:
<?php
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("tnews2") or die(mysql_error());
$query = "SELECT name,id,path FROM categories ORDER BY ID DESC LIMIT 0,6";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="categories">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['path']."'>'".$row['name']."'</option>";
}
?>
</select>
I would be grateful for any suggestions
Edit
echo "<th>Tierart";
$query = $pdo->query("select sp_term from species");
//Abfrage der Tabelle Tierart
echo '<select name="sp_term">';
while ($sql_sp_term = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="all">all</option>';
echo '<option value="'.$sql_sp_term['sp_term'].'">'.$sql_sp_term['sp_term'].'</option>';
}
echo '</select>';
Since you're populating the values of option in a select tag section with a database query doing something as follows would do the trick.
echo '<select name="sp_term">';
while ($sql_sp_term = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$sql_sp_term['sp_term'].'">'.$sql_sp_term['sp_term'].'</option>';
}
echo '</select>';
However, when you want to add an additional item like All as an option, place an explicit option value before the while/after the while depending on your requirement and you'll have the select > option with the new All option added to the options from the database.
echo '<select name="sp_term">';
echo '<option value="all">all</option>';
while ($sql_sp_term = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$sql_sp_term['sp_term'].'">'.$sql_sp_term['sp_term'].'</option>';
}
echo '</select>';

How to convert string to variable for use in server code

I want convert $RowNumber from string to a variable, for use in while, do is that possible?!how to do it?
$row1 = mysqli_query($Database,"SELECT * FROM Table1 ORDER BY ID");
$row2 = mysqli_query($Database,"SELECT * FROM Table2 ORDER BY ID");
// Others Rows code
for ($num = 1; $num <= 6; $num++)
{
$RowNumber = "row" . $num; // Save RowNumber for use in while
echo '<tr>';
// when it's used it not work becuse it's just a string only and
// i want convert it to variable to use in while
while($row = mysqli_fetch_array($RowNumber))
{
echo '<td>
<div class="Image_DIV" id="'; echo $row['DIV_ID']; echo '">
<table>
<tr><td class="Image"><img class="ImageOfDiv"
src="3DGallery/Chosen/Small/'; echo $row['src']; echo '"/></td></tr>
<tr>
<td class="ImageDescribe">'; echo $row['describe']; echo '</td></tr></table>
</div>
</td>';
}
echo '</tr><tr>';
}
Try ${$RowNumber} instead of $RowNumber for your purpose, If you need more info you can find it here. But as Mr. raina77ow has commented arrays are a good option.
If Table1 and Table2 have the same columns then you should UNION them together in your SQL then work on a single results set.
$results = mysqli_query($Database, "SELECT ID, DIV_ID, src, describe FROM `Table1` UNION SELECT ID, DIV_ID, src, describe FROM `Table2` ORDER BY ID");
echo '<tr>';
$x = 0;
while($row = mysqli_fetch_array($results))
{
echo '<td>';
echo $row['DIV_ID'];
echo $row['src'];
echo $row['describe'];
echo '</td>';
if( ++$x % 3 == 0 ) {
echo '</tr><tr>';
}
}
echo '</tr>';
Try this:
$rows[] = mysqli_query($Database,"SELECT * FROM Table1 ORDER BY ID");
$rows[] = mysqli_query($Database,"SELECT * FROM Table2 ORDER BY ID");
// Others Rows code
foreach ($rows as $current)
{
echo '<tr>';
// loop the query
while($row = mysqli_fetch_array($current))
{
echo '<td>
<div class="Image_DIV" id="'; echo $row['DIV_ID']; echo '">
<table>
<tr><td class="Image"><img class="ImageOfDiv"
src="3DGallery/Chosen/Small/'; echo $row['src']; echo '"/></td></tr>
<tr>
<td class="ImageDescribe">'; echo $row['describe']; echo '</td></tr></table>
</div>
</td>';
}
echo '</tr><tr>';
}
You cant assign variables like that without using php Eval: http://www.php.net/eval, but that is realy bad practise!
or using ${$var} syntax. But arrays is probably easier to work with.

Populate multiple drop-down lists with a single query

I have four drop-down lists that I would like to populate with values from an MSSQL table. All four lists should contain the same values. The query looks like this:
$data = $con->prepare("SELECT ID, Code FROM Table WHERE Code = :value ORDER BY Code");
$input = array('value'=>'value'); //'value' is hardcoded, not a variable
$data->execute($input);
And here is the code for my drop-downs:
<?php
echo "<select name=\"proj1[]\">";
while($row = $data->fetch(PDO::FETCH_BOTH))
{
echo "<option value='".$row['Code']."'>".$row['Code']."</option> ";
}
echo "</select>";
?>
This works fine for one drop-down. If I try to create another one (proj2[], proj3[], proj4[]) and apply the same query, however, the PHP page stops loading at that point and the second drop-down does not populate. The only way I've found around it is to copy the query and change the variables ($data becomes $data2 for proj2[], and so on). I'd really rather not have to write the same query four times. Is there a way around it?
$select = '';
while($row = $data->fetch(PDO::FETCH_BOTH))
{
$select .= "<option value='".$row['Code']."'>".$row['Code']."</option> ";
}
echo "<select name=\"proj1[]\">";
echo $select;
echo "</select>";
echo "<select name=\"proj2[]\">";
echo $select;
echo "</select>";
//etc...
Why not just put all of it in a veriable and then using it 4 times?
Somthing like this:
<?php
while($row = $data->fetch(PDO::FETCH_BOTH))
{
$options .= "<option value='".$row['Code']."'>".$row['Code']."</option> ";
}
for($i = 0; $i <= 4; $i++){
echo "<select name=\"proj1[]\">";
echo $options;
echo "</select>";
}
?>

mysql database data into html table limiting column

My script is retrieving images from a database and displaying the images in a table. I want to have the table have 4 columns of images before it breaks the row and starts over. I've found some helpful answers on this forum but after re-organizing and fussing with the code it displays every image in it's own table rather than adding the row breaks after every fourth image. I'm running on little sleep, but hopefully a second pair of eyes could help me spot the problem.
<?php
include_once "connect.php";
$userid = $_SESSION['id'];
$albumid = $_GET['album'];
$pic = mysql_query("SELECT * FROM `pictures` WHERE userid='$userid' AND
albumid='$albumid'");
$i = 0;
echo "<center><table width='50%'><tr>";
while($row = mysql_fetch_assoc($pic)){
$id = $row["id"];
$thumbnail = $row["thumbnail"];
echo "<td><a href='viewphoto.php?photo=$id'><img src='$thumbnail'>
</a></td>";
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
echo "</tr><tr>";
}
echo "</table> </center>";
?>
Fiddled around a little bit and
while($row = mysql_fetch_assoc($pic)){
$id = $row["id"];
$thumbnail = $row["thumbnail"];
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
echo "<td><a href='viewphoto.php?photo=$id' rel='facebox'><img src='$thumbnail'>
</a></td>";}
worked like a charm.
The problem is that you are declaring your table inside the while loop. You should open and close your table tags on either side of the while loop, and only have tr and td's inside the loop.
There seem to be a couple of interchanged variable names here too that would cause unexpected behaviour. In your SQL query I think you mean ...albumid='$albumid'... and in the while loop I think you want while($row = mysql_fetch_assoc($pic)) {
Also, you should take note that this SQL query is open to SQL injection attacks
$i was initialized inside the loop. and Table also bring outside.
see the code below.
<?php
include_once "connect.php";
$userid = $_SESSION['id'];
$albumid = $_GET['album'];
$pic = mysql_query("SELECT * FROM `pictures` WHERE userid='$userid' AND
albumid='$pic'");
$i = 0;
echo "
<center><table width='50%'><tr>";
while($row = mysql_fetch_assoc($image)){
$id = $row["id"];
$thumb = $row["thumb"];
$date = strftime("%b %d, %Y", strtotime($row['date']));
echo "<td><img src='$thumbnail'></td>";
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
}
echo "</table> </center>";
?>

loop through database and show in table

I am trying to loop though my users database to show each username in the table in their own row. I can only get it to show one user but loops through this the number of rows there are. Code is below
<?php
require_once ('../login/connection.php');
include ('functions.php');
$query = "SELECT * FROM users";
$results=mysql_query($query);
$row_count=mysql_num_rows($results);
$row_users = mysql_fetch_array($results);
echo "<table>";
for ($i=0; $i<$row_count; $i++)
{
echo "<table><tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
?>
Thanks
mysql_fetch_array fetches a single row - you typically use it in a while loop to eat all the rows in the result set, e.g.
echo "<table>";
while ($row_users = mysql_fetch_array($results)) {
//output a row here
echo "<tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
You're only fetching one row:
$row_users = mysql_fetch_array($results);
You're never calling a fetch again so you're not really looping through anything.
I'd suggest changing your loop to the following:
echo "<table>";
while ($row = mysql_fetch_array($results)) {
echo "<tr><td>".($row['email'])."</td></tr>";
}
echo "</table>";
The while loop will loop through the results and assign a row to $row, until you run out of rows. Plus no need to deal with getting the count of results at that point. This is the "usual" way to loop through results from a DB in php.
In the new MYSQLI, I use this coding
$query = "SELECT * FROM users";
$results=mysqli_query($con,$query);
$row_count=mysqli_num_rows($results);
echo "<table>";
while ($row = mysqli_fetch_array($results)) {
echo "<tr><td>".($row['id'])."</td></tr>";
}
echo "</table>";
mysqli_query($con,$query);
mysqli_close($con);
Your problem is in this line:
echo "<table><tr><td>".($row_users['email'])."</td></tr>";
You're echoing out a <table> tag again. Remove that so your code looks like this:
echo "<table>";
for ($i=0; $i<$row_count; $i++)
{
echo "<tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
You don't need to output a table within a table the way you're doing it.
$result = mysql_query("SELECT `email` FROM `users`");
$num_emails = mysql_num_rows($result);
echo "<table><caption>There are/is $num_emails email(s)</caption>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>{$row['email']}</td></tr>";
}
echo '</table>';
Something like that should work.

Categories