Adding PHP table to mySQL files - php

hey guys this maybe a stupid question for you but I have a database containing footballers names (please see screen shot) What i need to do is display maybe 5 names side by side and then 5 below, if that make sense. is there an easy way to do this?
the code i currently have after the established connect is
$sql = "SELECT ID, NAME FROM players";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// Outputting HTML and the data from the DB. Change to $row['the name of the field you want']
echo "<div class='caption'><h3><img src='http://placehold.it/180x180' alt=''>" . $row['NAME'] . "</h3><p>";
}
} else {
echo "No players to show";
}
$conn->close();
?>
is it CSS i should be focusing on to make this look the way i want it?
sorry i am a new at this and cant get my head around it lol

try this:
I have added a counter called i which will change the div after it has listed 5 names. Then I have styled the div to 50% width and float to left which allows 2 div side by side.
<style>
.caption
{
width:50%;
float:left;
}
<?php
$sql = "SELECT ID, NAME FROM players";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<div class='caption'>";
while($row = $result->fetch_assoc()) {
$i = 0;
if($i>=4)
{
$i = 0;
echo "</div><div class='caption'>";
// Outputting HTML and the data from the DB. Change to $row['the name of the field you want']
<h3><img src='http://placehold.it/180x180' alt=''><h3>" . $row['NAME'] . "<h3>";
}
} else {
echo "No players to show";
}
$conn->close();
?>
</div>

yes, you are doing it right way. You just need to do some css. You can take some help form here :- https://designshack.net/articles/css/5-simple-and-practical-css-list-styles-you-can-copy-and-paste/

Related

PHP Page Jumps Up and Down while loading html table elements from database

I'm loading tr and td elements into a table from a database using PHP, but when the table is loading, it jumps from the top of the page to the bottom of the page repeatedly until all the table elements are loaded. Is there any way for the page to stay in the same place without jumping to the table when the table is loading?
$result = $connection->query($query);
if ($result) {
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td> data from table</td>";
...
echo "</tr>";
}
}
}
EDIT: I put a lazy load on the page for now since it seems like there's no other solution.
You can try to store your html in a variable and echo it when the fetching is done.
$html = "";
$result = $connection->query($query);
if ($result) {
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$html .= "<tr>";
$html .= "<td> data from table</td>";
...
$html .= "</tr>";
}
}
}
echo $html;
If your elements loaded from DB are used to build sth. like images, then this could lead to the problem because the browser does not know the size of the elements in advance. You can try to set the dimensions of the elements or a kind of a container as placeholder in advance.
Perhaps this approach is helpful, too: Stop page jumping while images load

Inserting data into a repeatable div through PHP

JSFiddle here, with unfunctionaing PHP obviously, but on the local host it pulls through the information just fine.
I am trying to append data in a loop into a specific set of tags, inside a di of a certain class.
For example, for every row in the the table, add a div with the class "card" and append "Title" into a H2, "description" into a P tag etc.
Anyone know how I could go about doing this? I'm googling but finding it hard to phrase my question right.
Div "Card" markup:
<div class="card">
<h2>Health and Wellbeing</h2>
<p>Sometimes you just did too much sitting not enough jumping go go go.</p>
</div>
PHP pull:
$sql = "SELECT title, description, count FROM relevant_topics";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<b>Title: </b>" . $row["title"]. " - Description: " . $row["description"]. " " . $row["count"]. "<br>";
}
} else {
echo "0 results";
}
You can echo the div markup into the PHP code like this:
while($row = $result->fetch_assoc()) {
echo'<div class="card">
<h2>'.$row["title"].'</h2>
<p>'.$row["description"].'
</div>';
}
Not sure where you want the Row['count'] though.
Also you might wanna use PDO instead of mysql, Since mysql is outdated: How can I prevent SQL injection in PHP?
check this
if ($result->num_rows > 0) {
// output data of each row
while($row = $result-> mysql_fetch_array()) {//if not works change mysql_fetch_array() to fetch_assoc()
echo'<div class="card"><h2>';
echo '.$row["title"].';
echo '</h2><p>';
echo '.$row["description"].';
echo '</P></div>';
}

PHP If statement, suitable?

I'm working on a small university assignment to build a simple e-commerce engine using PHP for a website.
I currently have the following script setup to display products within a category, all of which are retrieved from a MySQL database.
http://example.com/category.php?id=2
The problem I am currently having is that for each product displayed the script is simply echoing each one side by side into a new table entry. This is causing them to go across the page rather than vertically.
What would be the best way to alter this code to have for example a maximum of three products per row? An If loop or something along those lines? Would appreciate the support!
<?php
//Create Session
session_start();
//Connect to database
include "conn.php";
//Retrieve Header
include "header.php";
//Get Category ID
if (isset($_GET['id'])){
$CategoryID = $_GET['id'];
//QUERY collects product name, and product ID.
$q="SELECT ProductID, ProductName, Price,img FROM Products WHERE CategoryID=$CategoryID";
//QUERY collects Product Category descriptions
$d="SELECT `Desc` FROM ProductCategories WHERE CategoryID=$CategoryID";
//retrive and execute SQL query results and save into a variable
$result = mysqli_query($_SESSION['conn'],$q);
$result2 = mysqli_query($_SESSION['conn'],$d) or die(mysql_error());
//Retrieve Product Category Description
echo "<div>";
while ($myResult = mysqli_fetch_row($result2)){ //Create an array
echo "<p>".$myResult[0]."</p>";
}
echo "</div>";
//Retrieve Products in category
echo "<div align='center'><table border='1px' bordercolor='#000000' width='200px'><tr>"; //Define table, row and div containing each product
while ($row = mysqli_fetch_row($result)){ //Create an array
echo "<td>"; //Create table cell
echo "<p><img src=".$row[3]."></p>"; //product image small (250x250 Pixels)
echo "<p align='center'><a href='product.php?id=".$row[0]."'>".$row[1]." </a></p>"; //Product ID Link and Name
echo "<p align='center'>£ ".$row[2]."</p>";
echo "</td>"; //Close table cell
}
echo "</tr></table></div>";//Close table, div and row
mysqli_free_result($result);
}
// Retireve Footer
include "footer.php";
?>
I am new when it comes to programming of any kind, so would appreciate patience/any support you could give me. Also I am aware of the SQL injection problem and will fix this at a later date.
Well you would keep track of your while iterations with a counter then everytime you hit $counter%3 === 0 (replace 3 with whatever you want per row) you would close the tr and start a new one:
$counter = 0;
$perRow = 3;
while ($row = mysqli_fetch_row($result)){ //Create an array
if($counter === 0) {
echo '<tr>';
} else if ($counter%$perRow === 0 ) {
echo '</tr><tr>';
}
echo "<td>"; //Create table cell
echo "<p><img src=".$row[3]."></p>"; //product image small (250x250 Pixels)
echo "<p align='center'><a href='product.php?id=".$row[0]."'>".$row[1]." </a></p>"; //Product ID Link and Name
echo "<p align='center'>£ ".$row[2]."</p>";
echo "</td>";
$counter++;
}
Here you go
while ($row = mysqli_fetch_row($result)){ //Create an array
echo "<tr><td>"; //Create table cell
echo "<p><img src=".$row[3]."></p>"; //product image small (250x250 Pixels)
echo "<p align='center'><a href='product.php?id=".$row[0]."'>".$row[1]." </a></p>"; //Product ID Link and Name
echo "<p align='center'>£ ".$row[2]."</p>";
echo "</td></tr>"; //Close table cell
}
echo "</table></div>";//Close table, div and row
The TR needs to be inside the while since tr is a row
You can do it the old fashion way with tables and iteration counters. You could also use a more CSS based approach.
Loop your result set, and build the inner HTML part (rows, columns)
$rows = '';
while ($myResult = mysqli_fetch_row($result2)){ //Create an array
$rows .= '<div class="inner">'.$myResult[0].'</div>';
}
Decide on the width of the inner columns x and make them float left or right, And make the outer div width * x
<style type="text/css">
div.box {
width:900px;
}
div.inner {
float:left;
width:300px;
}
</style>
And finally echo your HTML
<div class="box"><?php echo $rows; ?></div>
What you need is to keep track of the position you're at. If you want 3 cols per row it would be something like:
$count = 1;
echo '<table>';
while ($row = mysqli_fetch_row($result)) {
$tmp = $count % 3; //get the remainder
if ($tmp==1) {
if ($count!=1) {
//not the first row so close the last one
echo "</tr>";
}
//start row
echo "<tr>";
}
//show your <td> info
$count++;
}
echo '</tr></table>';

PHP syntax help on if statement

I'm trying to determine the right syntax from what I'm trying to do with MySQL. I'm basically saying that if a value in a certain column of a row of a table is equal to some session variables, I want to echo out info.
I have a table with subject, description and user. User is set by taking the current user's first name and last name and inserting it into the table under user. This is done by the following code:
$sql="INSERT INTO tbl_name (subject, description, user)
VALUES
('$_POST[subject]','$_POST[description]','$_SESSION[firstname] $_SESSION[lastname]')";
Then once I'm calling this data back out, I want to basically allow the user to delete content that they submitted themselves. The first step for me is to be able to display it in the table. I believe this is just syntax error, but I've confused myself now with how things are set up:
$sql = "SELECT * FROM tbl_name ORDER BY subject, description
LIMIT {$startpoint},{$limit}";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME EXAMPLES:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if('$field->user' == '$_SESSION[firstname] $_SESSION[lastname]'){
echo '<td>You can delete this</td>';
}
}
I figured the $field->user would equal $_SESSION[firstname] $_SESSION[lastname] because that's how it was initially submitted to the table (without the '.' for concatenation).
Any help would be appreciated. Thanks!
EDIT
Here's the result of my table output code. The results are actually being display with $cell instead of from within the for loop I believe. I've added the if statement in after the but it doesn't seem to recognize echo "<td>".$field->user."</td>"; which makes me think that that is where the problem lies. What I would like to do is be able to add the if statement in a immediately after `echo {$field->user}"; to keep the code clean. I think I've confused myself thoroughly:
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME JOBS:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if($field->user == $_SESSION[firstname]." ".$_SESSION[lastname]){
echo '<td>You can delete this</td>';
}
else{
echo "<td>".$field->user."</td>";
echo "<td>".$_SESSION[firstname]." ".$_SESSION[lastname]."</td>";
}
}
echo "</tr>\n";
while($row = mysqli_fetch_row($result))
{
echo"<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no jobs!';
}
I re-wrote the code in a way that was a little bit easier for me to understand (though maybe not the shortest way to do it):
while($row = mysqli_fetch_array($result))
{
echo"<tr>";
echo"<td>".$row['subject']."</td>";
echo"<td>".$row['description']."</td>";
echo"<td>".$row['user']."</td>";
if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
echo"<td>You can delete this</td>";
}
else{
echo"<td>Code didn't work</td>";
}
echo "</tr>\n";
}
It ended up working this way. If there's way to do this shorter then feel free to post it here otherwise thanks for the help!

PHP: html table layout with data coming from query

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.

Categories