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>";
?>
Related
I have been struggling with this for several days now. I have searched on how to update tables and have managed to get as far as to update rows, but only the last one in the table. So now i am trying to get a loop that loops through all the inputs and updates the database with the inputted values. I think the code that needs to be corrected is located near the end of the code
What i want to do:
Get/display database in html table
Change values of certain columns
Update the database table using a submit button which updates every row in database
Here is a picture of what the table looks like in web view:
<?php
//Connect to database
include '../db/connect.php';
?>
<form action='test7.php' method="post">
<table border='1'>
<?php
$result = $MySQLi_CON->query("SELECT * FROM users");
echo "<tr>";
echo "<td colspan='3'>CLASS 1</td>";
echo "</tr>";
//All table rows in database presented in html table
while($row = $result->fetch_array()){
echo "<tr>";
echo "<td><input type='hidden' name='user_id[]' value='".$row['user_id']."' /></td>";
echo "<td>username :<input type='text' name='username[]' value='".$row['username']."' /></td>";
echo "<td>email :<input type='text' name='email[]' value='".$row['email']."' /></td>";
echo "<td>rank :<input type='number' name='rank[]' value='".$row['rank']."' /></td>";
echo "</tr>";
}
echo "<input type='submit' name='update' value='UPDATE' />";
?>
<table>
</form>
<?php
if(isset($_POST['update'])){
$total = count($_POST['rank']);
$user_id_arr = $_POST['user_id'];
$rank_arr = $_POST['rank'];
for($i = 0; $i < $total; $i++){
$user_id = $user_id_arr[$i];
$rank = $rank_arr[$i];
$query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";
$MySQLi_CON->query($query);
header('Location: test7.php');
}
}
?>
When I press the UPDATE button, i get PHP Notice: Array to string conversion in....
It refers to line 30 which is this line:
$query = "UPDATE user SET rank=$_POST[rank][$row] WHERE user_id=$value ";
EDIT: Edited the code above to the working code. Thank you #Frayne Konok for your help.
You are very close.
The issue is that in this code $_POST[rank][$row] - rank is an undefined constant. You need it to be a string, like so $_POST['rank'][$row]. Also, pull the $POST variable out of the query directly to allow typecasting - you should always be very uncomfortable when you see a query that has $_POST data directly:
if(isset($_POST['update'])){
foreach ($result as $row => $value) {
// typecast to a number with decimals below. If you only need integers, than use (int)
$rank = (float)$_POST['rank'][$row];
$query = "UPDATE user SET rank={$rank} WHERE user_id={$value}";
$MySQLi_CON->query($query);
}
}
However, it would be better to use mysqli prepared statements rather than insert the variables directly - as it stand, the above code is vulnerable to SQL Injection attacks.
Your code should be modified to look something like so to prevent sql injection attacks:
if(isset($_POST['update'])) {
$stmt = $MySQLi_CON->prepare("UPDATE user SET rank= ? WHERE user_id= ?");
foreach ($result as $row => $value){
$stmt->bind_param('di', $_POST['rank'][$row], $value);
$stmt->execute();
}
$stmt->close();
}
You did a great mistake here, Why you use the $result in foreach
loop?? FRom where the $result comes?? The $result is the resource
of the sql query.
Try this:
if(isset($_POST['update'])){
$total = count($_POST['rank']);
$user_id_arr = $_POST['user_id'];
$rank_arr = $_POST['rank'];
for($i = 0; $i < $total; $i++){
$user_id = $user_id_arr[$i];
$rank = $rank_arr[$i];
$query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";
$MySQLi_CON->query($query);
}
}
Try with this and let me know if there is any problem.
I am trying to delete multiple values from my form (its a car rental system, where I want to give the staff the ability to delete a car from the record). I am new to PHP but this is what I have right now.
<?php
$link = mysql_connect ("xxxx", "xxxx", "xxxx");
mysql_select_db ("xxxx");
$query = "SELECT * from car";
$result = mysql_query ($query);
echo ("<form action=\"deleting2.php\" method=\"GET\">");
echo "<table id = 'table-3'>";
echo "<thead>";
echo "<th>Car ID</th>
<th>Car Name</th>
<th>Fuel Type</th>
<th>Transmission</th>
<th>Engine Size</th>
<th>Doors</th>
<th>Total</th>
<th>Available</th>
<th>Date Added</th>
<th>Delete</th> ";
echo "</thead>";
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
echo "<tbody>";
echo "<tr>";
echo "<td>$row->ID</td>";
echo "<td>$row->CARNAME</td>";
echo "<td>$row->FUELTYPE</td>";
echo "<td>$row->TRANSMISSION</td>";
echo "<td>$row->ENGINE_SIZE</td>";
echo "<td>$row->DOORS</td>";
echo "<td>$row->TOTAL</td>";
echo "<td>$row->AVAILABLE</td>";
echo "<td>$row->DATEADDED</td>";
echo "<td><input type='checkbox' name='delete[]' value='$row->ID' /></td>";
echo "</tr>";
echo "</tbody>";
}
echo ("<tr><td colspan='6' align='center'><input type=\"submit\" value=\"Delete \"></td> </tr></table></form>");
echo "</table>";
mysql_close ($link);
?>
Now,when I do press the delete button, it goes to my php page called 'deleting2.php' as mentioned in the form action, which has the following code:
<?php
$link = mysql_connect ("xxxx", "xxxx", "xxxx");
mysql_select_db ("xxxx");
$ID='$_GET[ID]';
// DELETE ANY RECORDS IN DATABASE
for ($i = 0; $i < #mysql_num_rows ($result); $i ++)
{
if(isset($_GET['delete[]']) && $_GET['delete[]']=='$row->ID');
{
$query=("DELETE FROM car WHERE ID='$_POST[ID]'");
$result1 = mysql_query($query);
}
}
mysql_close ($link);
?>
The problem is, it is NOT deleting anything from the my database. The URL in the address bar when the deleting2.php is being processed, is:
http://www.computing.northampton.ac.uk/~11430900/a1/webpages/deleting2.php?delete[]=6
Which according to my knowledge, selects the values that were ticket. Here, I had checked the box, which had a corresponding ID value of 6. So, check-box DOES work, it just does not do anything to the database, does not delete the value. I have tried many tutorials but I can't delete it using check-boxes. Any help would be much appreciated.
You don't need to itrate through following loop as mentioned in your question
for ($i = 0; $i < #mysql_num_rows ($result); $i ++)
{
if(isset($_GET['delete[]']) && $_GET['delete[]']=='$row->ID');
{
$query=("DELETE FROM car WHERE ID='$_POST[ID]'");
$result1 = mysql_query($query);
}
}
mysql_close ($link);
just to the following.
change your form method to POST.
use the following code. implode is necessary as $_POST['delete'] will be an array
if(isset($_POST['delete']) && count($_POST['delete']) > 0) {
$query=("DELETE FROM car WHERE ID in ('".implode(',',$_POST['delete'])."')");
$result1 = mysql_query($query);
}
Your data needs sanitizing but this should be Ok if you expect the ID to be a number:
$id = (int)$_GET['ID'];
$query=("DELETE FROM car WHERE ID=$id");
You really need to look at the rest of your code for SQL injection attacks.
First of all, be very carefull when implementing a database entries deletion as You could end up with empty database.
Secondly, always sanitize Your input to prevent SQL Injection.
Thirdly, learn PDO or at least mysqli_* functions instead of mysql_ as they are deprecated now and could be removed with any next PHP release.
Now, to Your problem, You are setting the ID values into a delete[] array value, that means You should do this:
// DELETE THE DESIRED RECORDS IN DATABASE
foreach($_GET['delete'] as $id) {
$result = mysql_query("DELETE FROM car WHERE ID = '" . mysql_real_escape_string($id) . "'");
// do something with the $result here ...
}
Other option could be to expect only integers:
// DELETE THE DESIRED RECORDS IN DATABASE
foreach($_GET['delete'] as $id) {
$result = mysql_query("DELETE FROM car WHERE ID = '" . (int)$id . "'");
// do something with the $result here ...
}
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>";
}
I'm trying to fix the layout of the data coming from the database in this way:
The query is returning names of games and the points awarded for each game.
The layout I need is like that:
in one row the name of the game and in a row below its points, two columns with this and then carriage break until all results are displayed.
Please see this image, it'll show some light:
http://217.116.9.130/wordpress/HTMLtableFROMquery.gif
What I have done by far is the following code, but I cannot display the layout needed.
![<?php
echo "<table border=1><tr>";
$count=0;
$sql2 = "select * from games";
$res2= $db_class->select($sql2);
if (mysql_num_rows($res2)>0) {
while($row2 = $db_class->get_row($res2)){
$gname = $row2['gamename'];
$gpoints = $row2['gamepoints'];
$count++;
echo"<td>".$gname."</td>";
if($count % 2 != 0)
{
echo "</tr><tr>";
echo"<td>".$gpoints."</td>";
}
}
}
echo "</tr></table>";
?>
What about some divs?
<?php
echo "<table border=1><tr>";
$count=0;
$sql2 = "select * from games";
$res2= $db_class->select($sql2);
if (mysql_num_rows($res2)>0) {
while($row2 = $db_class->get_row($res2)){
$gname = $row2['gamename'];
$gpoints = $row2['gamepoints'];
$count++;
echo"<td>
<div class=\"gname\">".$gname."</div>
<div class=\"gpoints\">".$gpoints."</div>
</td>";
if($count % 2 != 0)
{
echo "</tr><tr>";
}
}
}
echo "</tr></table>";
?>
You may want to create a table for each set of name-score, and then style it after your needs.
You can use the border property in CSS to style your table, and also table:nth-child(2n){ clear: left; to have only two tables on each row.
I believe this method is more flexible, as CSS gives endless possibilities for styling an element.
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.