Echoing a div every 3 rows of a MySQL table [duplicate] - php

This question already has answers here:
New containing div after every 3 records
(3 answers)
Closed 5 years ago.
<?
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$selection = "SELECT steamUsername, steamid64, twitter, discord, github FROM hnTeam";
$result = $conn->query($selection);
?>
<div class="card-group">
<?
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
/*if($result->num_rows === 1 || $result->num_rows % 3 === 0) {
echo "<div class='card-group'>";
}*/
echo "<div class='card'>";
echo "<img class='card-img-top' src='...' alt='Profile picture'>";
echo "<div class='card-body'>";
echo "<p class='card-text'>";
echo "<span id='social'><i class='fab fa-steam'></i> " . $row["steamUsername"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-discord'></i> " . $row["discord"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-twitter'></i> " . $row["twitter"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-github'></i> " . $row["github"] . "</span>" . "<br> <br>";
echo "</p>";
echo "</div>";
echo "</div>";
/*if($result->num_rows === 1 || $result->num_rows % 3 === 0) {
echo "</div>";
}*/
}
}
?>
</div>
</div>
There is my code so far. Essentially, I need to do the following:
For context, I will be referring to the following as a card:
echo "<div class='card'>";
echo "<img class='card-img-top' src='...' alt='Profile picture'>";
echo "<div class='card-body'>";
echo "<p class='card-text'>";
echo "<span id='social'><i class='fab fa-steam'></i> " . $row["steamUsername"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-discord'></i> " . $row["discord"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-twitter'></i> " . $row["twitter"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-github'></i> " . $row["github"] . "</span>" . "<br> <br>";
echo "</p>";
echo "</div>";
echo "</div>";
Okay, so what I need to do is, every 3 cards need to be put into this div: <div class='card-group'>.
I tried some if statements as shown in the code block, however to no avail. From what I understand I need to echo it into a div once and after that echo it into a div every group of 3 cards. I tried to base the if statement on $result->num_rows but that isn't procedural, it constantly appears as the final amount of cards, it doesn't increase by 1 each run through.
I'm stumped here, any help is greatly appreciated!

You use the % operator with $result->num_rows, that is not correct, you must use the current iteration, so I added a $c var.
if($result->num_rows > 0) {
$c = 0;
while($row = $result->fetch_assoc()) {
if ($c % 3 === 0) {
if ($c > 0) {
echo "</div>"; //Close before one
}
echo "<div class='card-group'>";
}
echo "<div class='card'>";
echo "<img class='card-img-top' src='...' alt='Profile picture'>";
echo "<div class='card-body'>";
echo "<p class='card-text'>";
echo "<span id='social'><i class='fab fa-steam'></i> " . $row["steamUsername"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-discord'></i> " . $row["discord"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-twitter'></i> " . $row["twitter"] . "</span>" . "<br>";
echo "<span id='social'><i class='fab fa-github'></i> " . $row["github"] . "</span>" . "<br> <br>";
echo "</p>";
echo "</div>";
echo "</div>";
$c++;
if ($c == $result->num_rows) {
echo "</div>"; //Close last one
}
}
}

Related

Form tag closing automatically (no parent close)

The following php code produce a form with 2 inputs tag, the problem is that the form self-closes at exactly after opening it.
There are no other tags closing between (I read it could have been a parent closing inside the form).
echo "<form method='POST' action='player.php'>
<input type='submit' value='Info' name='submit'>
<input type='hidden' name='id' value='" . $row["id"] . "'>
</form>";
This echo is inside a while fetch array, result of a mysql query.
The result, from chrome dev tools is:
EDIT:
The complete loop is (it is pretty messy and there are a few things that are not best practice):
Basically I am showing a ranking, the top 3 is displayed inside a div, and the rest of the ranking are displayed in a table. The form that sends to the player.php page in the table works, but the one in the div (that is the exact same form without doesn't).
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//if top 3 show in a div
if ($row["rank"] == 1 or $row["rank"] == 2 or $row["rank"] == 3) {
if($row["rank"] == 1) {
echo "<div class='center'>";
echo "<div class='player first'>";
}
else if($row["rank"] == 2) {
echo "<div class='player second'>";
}
else if($row["rank"] == 3) {
echo "<div class='player third'>";
}
//player img
echo "<img class='player' src='";
$position = strpos($row["name"], ",");
$filename = substr($row["name"], 0, $position);
if (file_exists("src/players/" . $filename . ".png")) {
echo "src/players/" . $filename . ".png";
}
else {
echo "src/players/404.png";
}
echo "'>
<h2>" . $row["rank"] . "° - " . $row["rating"] . "</h2>
<h1>" . $row["name"] . "</h1>";
echo "<h3>" . $row["country_name"] . "</h3>
<h5>" . $row["title_name"] . " - " . $row["games"] . " games</h5>";
//possibility to add to favourites only to login users
if ($_SESSION["is_login"]) {
$id_user = $_SESSION["id"];
$id_player = $row["id"];
$sql2 = "SELECT * FROM fav_players WHERE id_user = $id_user AND id_player = $id_player";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
echo "<i class='fas fa-heart' onclick='addPlayerToFav(this, " . $row["id"] . ")'> </i>";
}
else {
echo "<i class='far fa-heart' onclick='addPlayerToFav(this, " . $row["id"] . ")'> </i>";
}
}
else {
echo "<i class='far fa-heart' onclick=\"window.location.href='account.php'\"></i>";
}
//the form that doesn't work
echo "<form method='POST' action='player.php'>
<input type='hidden' name='id' value='" . $row["id"] . "'>
<input type='submit' value='Info' name='submit'>
</form>";
echo "</div>";
continue;
}
//the table
echo "<tr>";
echo "
<td>" . $row["rank"] . "°</td>
<td>" . $row["name"] . "</td>
<td>" . $row["rating"] . "</td>
<td>" . $row["country_name"] . "</td>
<td>" . $row["title_name"] . "</td>
<td>" . $row["games"] . "</td>";
//the form that works
echo "<td class='center'><form method='POST' action='player.php'><input type='hidden' name='id' value='" . $row["id"] . "'>
<input type='submit' value='Info' name='submit'></form></td>";
echo "<td class='center'>";
if ($_SESSION["is_login"]) {
$id_user = $_SESSION["id"];
$id_player = $row["id"];
$sql2 = "SELECT * FROM fav_players WHERE id_user = $id_user AND id_player = $id_player";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
echo "<i class='fas fa-heart' onclick='addPlayerToFav(this, " . $row["id"] . ")'></i>";
}
else {
echo "<i class='far fa-heart' onclick='addPlayerToFav(this, " . $row["id"] . ")'></i>";
}
}
else {
echo "<i class='far fa-heart' onclick=\"window.location.href='account.php'\"></i>";
}
echo "</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
echo "</table>"
The form is auto-closing due to a div not closed (the class="center" div). When the div with the top 3 is closed and the first table row is opened the browser auto-closes the form.
Fixed adding the following code before the table echo to close the div only after the 3 player, so after the podium is finished.
if($row["rank"] == 3) {
echo "</div>";
}

SQL query not returning array

Working on getting a page to build off of an array that is returned from a DB to post a story, not sure what it is not working. The page URL looks like this: https://ohcrap.ninja/games/ps4/article.php?id=1
Here is the code that should be generating the content:
<?php
$id = $_GET['id'];
$query = mysqli_query($con,'SELECT * FROM `PS4` WHERE `id` =' .$id) or die(mysqli_error($con));
while ($row = mysqli_fetch_array($query));
// Echo page content
echo "<div class='col s12 m12 l12'>";
echo "<div class='card small grey darken-3'>";
echo "<div class='card-stacked'>";
echo "<div class='card-content'>";
echo "$id";
echo "<span class='card-title'>" . $row['title'] . "</span>";
echo "<hr color='black'>";
echo "<P>By:<i> " . $row['author'] . "</i></P>";
echo "<P>Published: " . $row['published'] . "</P>";
echo "<br>";
echo "<P class='truncate'>" . $row['story'] . "</P>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
?>
Your while loop is not doing anything useful, because you're immediately ending it with that ;.
while ($row = mysqli_fetch_array($query)) {
// all those echoes
}

Run UPDATE on single row within PHP loop

I have written this code, sorry I'm pretty new to PHP.
I have a loop which grabs all the horses from the database.
I have created a sell button underneath each entry, the problem I have is that when I hit "Sell" on a single entry it "Sell"s ALL of the entries.
Here is my code;
$query = "SELECT * FROM horses WHERE (owner = '$id') AND (status = 'active')";
if($result = $connect->query($query)) {
echo "<ul id='horses' class='row'>";
while ($row = $result->fetch_assoc()) {
echo "<li class='col-sm-4'>";
echo "<div class='horse-wrap'>";
echo "<h2>" . $row['name'] . "</h2>";
echo "<div class='details'>";
echo "<strong>Age:</strong> " . $row['age'] . "<br>";
echo "<strong>Colour:</strong> " . $row['colour'] . "<br>";
echo "<strong>Country:</strong> " . $row['country'] . "<br>";
echo "<strong>Value:</strong> £" . number_format($row['value']) . "<br>";
echo "</div>";
echo "<h3>Record</h3>";
echo "<ul class='history row'>";
echo "<li class='col-sm-3'>Runs: " . $row['runs'] . "</li>";
echo "<li class='col-sm-3'>Wins: " . $row['first'] . "</li>";
echo "<li class='col-sm-3'>2nd: " . $row['second'] . "</li>";
echo "<li class='col-sm-3'>3rd: " . $row['third'] . "</li>";
echo "</ul>";
echo "<ul class='skills'>";
echo "<h4>Speed</h4><li><span class='skill' style='width: " . $row['skill_speed'] . "%;'>" . $row['skill_speed'] . "</span></li>";
echo "<h4>Jumping</h4><li><span class='skill' style='width: " . $row['skill_jump'] . "%;'>" . $row['skill_jump'] . "</span></li>";
echo "<h4>Temperament</h4><li><span class='skill' style='width: " . $row['skill_temperment'] . "%;'>" . $row['skill_temperment'] . "</span></li>";
echo "<h4>Endurance</h4><li><span class='skill' style='width: " . $row['skill_endurance'] . "%;'>" . $row['skill_endurance'] . "</span></li>";
echo "</ul>";
// SELL HORSE BUTTON
echo "
<form action='./stables.php' method='post'>
<input type='hidden' value='" . $row['value'] . "' name='sellvalue' />
<input type='hidden' value='" . $row['name'] . "' name='sellname' />
<input type='submit' value='Sell Horse' name='sell' class='sell' />
</form>
";
echo "</div>";
echo "</li>";
// SELL HORSE
if(!empty($_POST["sell"])) {
//REMOVE HORSE FROM USER
$horseName = $row['name'];
$status = 'sold';
if($updateHorse = $connect->prepare("UPDATE horses SET status = ? WHERE name = ?")) {
$updateHorse->bind_param('ss', $status, $horseName);
$updateHorse->execute();
$updateHorse->close();
}
//ADD MONEY TO USER
$updateAmount = $money + $row['value'];
if($updateUser = $connect->prepare("UPDATE users SET money = ? WHERE id = ?")) {
$updateUser->bind_param('ss', $updateAmount, $id);
$updateUser->execute();
$updateUser->close();
}
}
}
echo "</ul>";
} else {
echo "You currently have no horses.";
}
You're doing the update inside of a loop, but you're never checking to see if the loop's current horse is the one the customer is trying to sell. As it's written, it is going to execute for every one.
You're checking to see if the form was submitted:
// SELL HORSE
if(!empty($_POST["sell"])) {
This is the perfect place to also make sure you have the right horse:
// SELL HORSE
if(!empty($_POST["sell"]) && $row["name"] === $_POST["sellname"]) {

How to get the highest value from a database row?

I have a problem. I have a one page website and if there is posted a message a posts shows up and below the post there needs to be an image, but on the last on the index page I don't want an image to show up. So it's like if the id from the database is the highest that post doesn't get a image below it.
Here is the code:
<?php
include 'functions/image/functions.php';
$countQuery = $db->prepare("SELECT paginaNummer AS max FROM pages ;");
$countRow = $countQuery->fetch();
$maxId = $countRow['max'];
$query = $db->prepare("SELECT * FROM pages");
$query->execute();
$num_cols = 1;
$i = 0;
$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);
while($row = $query->fetch()) {
if(isset($row)) {
echo "<section data-stellar-background-ratio='0.5'>";
echo "<div class='panelContainer'>";
echo "<div class='panel2'>";
echo "<div class='symbol3'></div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</section>";
echo "<section class='wrapper'>";
echo "<div class='box'>";
echo "<div class='content'>";
echo $i++ % $num_cols == 0 ? '' : '';
echo "<div id='message'><h2> ", $row['berichtNaam'], "</h2>";
echo $row['paginaContent'], "<br />";
if (isset($_SESSION['login']['5']) && $_SESSION['login']['5'] == 2) {
echo " <a class='edit' href='functions/admin/edit.php?id=" . $pageNumber . " '>Edit</a>";
echo " <a class='delete' href='functions/admin/deletePost.php?id=" . $pageNumber . " '>Delete</a>";
} elseif (isset($_SESSION['login']['5']) && $_SESSION['login']['5'] == 1) {
echo " <a class='edit' href='functions/admin/edit.php?id=" . $pageNumber . " '>Edit</a>";
} else {
}
echo "</div>";
echo "</div>";
echo "</section>";
echo max($row);
if (count($row['paginaNummer']) == max($row)){
} else {
echo "<a href='/'><img src='<?php echo $path . $img ?>'alt=''/></a>";
}
echo "</section>";
}
}
echo "</div></div>";
?>
I won't get any further with this part I hope you can help me with this problem
It's hard to understand what you need. But try this query:
$countQuery = $db->prepare("SELECT paginaNummer AS max
FROM pages ORDER BY paginaNummer DESC LIMIT 1");
Or may be this:
$countQuery = $db->prepare("SELECT paginaNummer AS max
FROM pages ORDER BY id DESC LIMIT 1");
Update: this code changes instead of top:
<?php
include 'functions/image/functions.php';
$query = $db->prepare("SELECT * FROM pages");
$query->execute();
$maxrow = $query->rowCount();
$num_cols = 1;
$i = 0;
$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);
$n = 0;
while($row = $query->fetch()) {
if(isset($row)) {
$n++;
echo "<section data-stellar-background-ratio='0.5'>";
echo "<div class='panelContainer'>";
echo "<div class='panel2'>";
echo "<div class='symbol3'></div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</section>";
echo "<section class='wrapper'>";
echo "<div class='box'>";
echo "<div class='content'>";
echo $i++ % $num_cols == 0 ? '' : '';
echo "<div id='message'><h2> ", $row['berichtNaam'], "</h2>";
echo $row['paginaContent'], "<br />";
if (isset($_SESSION['login']['5']) && $_SESSION['login']['5'] == 2) {
echo " <a class='edit' href='functions/admin/edit.php?id=" . $pageNumber . " '>Edit</a>";
echo " <a class='delete' href='functions/admin/deletePost.php?id=" . $pageNumber . " '>Delete</a>";
} elseif (isset($_SESSION['login']['5']) && $_SESSION['login']['5'] == 1) {
echo " <a class='edit' href='functions/admin/edit.php?id=" . $pageNumber . " '>Edit</a>";
} else {
}
echo "</div>";
echo "</div>";
echo "</section>";
echo max($row);
if ($n == $maxrow){
} else {
echo "<a href='/'><img src='<?php echo $path . $img ?>'alt=''/></a>";
}
echo "</section>";
}
}
echo "</div></div>";
?>

php if statement not sure how to do 2 if's

I'm trying to do a condition within an if statement.
I have a current if statement which determines odd and even for css styling.
Within this I want to add another if statement for the reference number. (outlined as Ref in the code).
I'm not sure how to go about this but I want to add something along the lines of
if ref == 1 then echo ref, I've tried putting an if within an if and I just keep getting syntax errors. Can someone point me in the right direction please?
include "db_connect.php";
$result1 = mysql_query("SELECT * FROM updates ORDER BY id DESC limit 5");
$result2 = mysql_num_rows($result1);
$x = $result2;
while ($row1 = mysql_fetch_array($result1)) {
if (++$x % 2) {
echo "<blockquote class='example-right'>" . $row1['update'] .
"<div class='ref'>Ref: " . $row1['ref'] .
"</div><div class='date-right'> from " . $row1['date'] .
" to " . $row1['todate'] .
"</div> </blockquote> <p>" . $row1['username'] .
"</p> </td>";
echo "</p>";
} else {
echo "<blockquote class='example-obtuse'>" . $row1['update'] .
"<div class='ref'>Ref: " . $row1['ref'] .
"</div><div class='date-right'> from " . $row1['date'] .
" to " . $row1['todate'] .
"</div> </blockquote> <p>" . $row1['username'] .
"</p> </td>";
}
}
the bit I tried to do with 2nd if statement:
include "db_connect.php";
$result1 = mysql_query("SELECT * FROM updates1 ORDER BY id DESC limit 5");
$result2 = mysql_num_rows($result1);
$x = $result2;
while ($row1 = mysql_fetch_array($result1)) {
if (++$x % 2) {
$sch = $row1['schuedled'];
else if ($sch == '1') {
echo "<blockquote class='example-right'>" . $row1['update'] .
"<div class='ref'>Ref: " .$row1['ref'] .
"</div><div class='date-right'> from " . $row1['date'] .
" to " . $row1['todate'] .
"</div> </blockquote> <p>" . $row1['username'] .
"</p> </td>";
else {
echo "<blockquote class='example-right'>" . $row1['update'] .
"</div><div class='date-right'> from " . $row1['date'] .
" to " . $row1['todate'] .
"</div> </blockquote> <p>" . $row1['username'] .
"</p> </td>";
}
}
echo "</p>";
} else {
echo "<blockquote class='example-obtuse'>" . $row1['update'] .
"<div class='assyst-ref'>Ref: " . $row1['ref'] .
"</div><div class='date-right'> from " . $row1['date'] .
" to " . $row1['todate'] .
"</div> </blockquote> <p>" . $row1['username'] .
"</p> </td>";
}
}
Try something like this:
while($row1 = mysql_fetch_array($result1)){
$html = '';
if (++$x % 2 ){
$html .= "<blockquote class='example-right'>";
} else {
$html .= "<blockquote class='example-obtuse'>";
}
$html .= $row1['update'];
if($row1['schuedled'] == '1'){
$html .= "<div class='ref'>Ref: " .$row1['ref'] . "</div>";
}
$html .= "more html";
$html .= "more html";
$html .= "more html";
$html .= "</blockquote>";
echo $html;
}

Categories