add HTML <div> if rows are added to database - php

I am trying to make a webpage that will add a card filled with data from a database if there is a row of data there. I have a <div class> that formats the card. Is there a way to programmatically add the <div class> so each <div class> is a row of data?
This is the PHP I have, it does read all the rows properly:
//SQL SELECT statement
$result = $conn->prepare("SELECT userid, pName, pDesc, dDate FROM test");
$result->execute();
// assign returned array elements to variables
for($i=0; $row=$result->fetch(); $i++){
$pName = $row['pName'];
$pDesc = $row['pDesc'];
$dDate = $row['dDate'];
}
Here is the HTML, it currently only displays the last row of data:
<h1>Project Dashboard</h1>
<div class="project-container">
<label>Project Owner:</label>
<span><?php echo $pName; ?></span><br>
<label>Project Description:</label>
<span><?php echo $pDesc; ?> </span><br>
<label>Project Due Date:</label>
<span><?php echo $dDate; ?> </span><br>
<div class="progress-bar">
<div id="myBar" class="container purple" style="height:24px;width:25%">
</div>
</div>
</div>

As mentioned in the comments, the PHP values are overwritten upon each iteration of the for loop, so only the last row of values will be displayed. For example, $pName can only hold one value at a time. So after the loop, $pName is defined as the last row's pName value.
I suggest using a while loop to output your HTML rows. Below, I'm assuming each .project-container is a row. I'm also using PDO.
<?php
while ($row=$result->fetch(PDO::FETCH_ASSOC)) {
?><div class="project-container">
<label>Project Owner:</label>
<span><?=$row['pName']?></span><br>
<label>Project Description:</label>
<span><?=$row['pDesc']?></span><br>
<label>Project Due Date:</label>
<span><?=$row['dDate']?></span>
</div><?php
}
Alternatively, you could fetch all the rows into a single PHP array and then loop through the array.
$rows=$result->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
// output row's HTML, just like above
}
See PDO::fetchAll vs. PDO::fetch in a loop
for performance considerations.

Related

How to count the arrays from a result of a query? [duplicate]

This question already has answers here:
Echo current number of row
(3 answers)
Closed 1 year ago.
I have a query that I make using PHP and it returns me all the rows that satisfied the condition that was given, now, I'm wondering if there's a way to count each number of row a result of a query has and pass that number to an id of an element on HTML?
<?php
$res2 = mysqli_query($con,"SELECT NAME, PRICE FROM product WHERE AVAILABLE = 1 AND ID_CATEGORY = 17");
?>
<body>
<?php
while($row = mysqli_fetch_row($res2)) {
print_r($row);
?>
<div class="item">
<img class="trj_img_cls" src="RSC/COMING_SOON.jpg" alt="" id="imgDG<?php ?>">
<div class="texto_trj">
<div class="nombre_producto">
<h2 id="ttlDG<?php ?>">título</h2>
</div>
<div class="precio_producto">
<i class="icon-dollar"></i>
<label id="prDG<?php ?>">0.00</label>
</div>
<div class="caracteristicas">
<ul id="caractDG<?php ?>"></ul>
</div>
</div>
</div>
<?php
}
?>
</body>
I put <?php ?> because there I want to add the variable (number of the row) so it complements the actual id and then i'm able to look for that id with javascript. Another thing is that I use the print_r() just to see if the elements were appearing.
This can be done by setting an $increment variable to 1 at the start of the while loop, and incrementing it at the end of the loop.
<?php
$increment = 1;
while($row = mysqli_fetch_row($res2)) {
And then using it like this:
id="imgDG<?php echo $increment; ?>">
And then incrementing it at the end:
<?php
$increment++;
}
?>

Getting rows from database but printing each one of them where I want

I have a number of rows I want to retrieve from the database but I want to print each row in the exact place I want and only even rows.
Is this possible? If yes, how can I achieve it?
<?php
$sql="Select * from plays where usertype=2 and idgame=$idgame";
$result=mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result)) {
$aword = $row['word'];
} ?>
<body>
<div id="row">
<span class="attemp">1 :</span>
<span class="word"><?php print //I want to print here only the 2nd fetched row ?></span>
</div>
<div id="row">
<span class="attemp">2 :</span>
<span class="word"><?php print //I want to print here only the 4th fetched row ?></span>
</div>
</body>
If when retrieving the data, you store it into an array, you can then output the data as you need to (remembering that arrays are 0 based)...
$aword = [];
while($row = mysqli_fetch_assoc($result)) {
$aword[] = $row['word'];
} ?>
<body>
<div id="row">
<span class="attemp">1 :</span>
<span class="word"><?php echo $aword[1]; ?></span>
</div>
<div id="row">
<span class="attemp">2 :</span>
<span class="word"><?php echo $aword[3]; ?></span>
</div>
</body>
Also I would suggest that if you only want the one column from the data, then select just that column rather than *...
$sql="Select word from plays where usertype=2 and idgame=".(int)$idgame;
and the obligatory comment about using prepared statements to stop SQL injection and some common errors.
$query = "Select * from plays where usertype=2 and idgame=$idgame";
$result = mysqli_query(isConnect(),$query);
while($row = mysqli_fetch_array($result));
{
echo "$row[0]";
}
?>

IF inside WHILE with database result not working

I have a simple ticket sale registration system with 6 types of tickets and 3 different "physical" sales locations. Each order is inserted as a row in the database and stores the amount of each type of ticket along with the sale location, total cost and a datetime timestamp.
I want to display the total amount of each ticket type, that was sold within a given time frame along with the total cost of those tickets. I also want to filter the results based on sale location.
This is my db query:
"SELECT SUM(ticketType1), SUM(ticketType2), SUM(ticketType3),
SUM(ticketType4), SUM(ticketType5), SUM(ticketType6),
SUM(cost), saleLocation
FROM `orders`
WHERE time BETWEEN '2018-07-10 07:00:01'
AND '2018-07-11 07:00:00'"
Then I display it in a HTML table row:
<?php
while ($row = $result->fetch_assoc()) {
if($row["saleLocation"] == 'location1') { ?>
<div class="cell">
<?php echo $row["SUM(ticketType1)"] ?>
</div>
<div class="cell">
<?php echo $row["SUM(ticketType2)"] ?>
</div>
<div class="cell">
<?php echo $row["SUM(ticketType3)"] ?>
</div>
<div class="cell">
<?php echo $row["SUM(ticketType4)"] ?>
</div>
<div class="cell">
<?php echo $row["SUM(ticketType5)"] ?>
</div>
<div class="cell">
<?php echo $row["SUM(ticketType6)"] ?>
</div>
<div class="cell">
<?php echo number_format($row["SUM(cost)"], 0, "", "."); ?>
</div>
<?php } //end if
} // end while
?>
It works, but I'm trying to use an IF statement inside the WHILE loop to filter the result based on location, but the IF statement doesn't appear to have any effect and instead it displays the results from all 3 locations.
I know I can easily modify the query to achieve this, but I would rather not do that in this specific case.
I'm guessing that the problem still lies within the query, though?
Some help would be greatly appreciated.

Make all title elements the same height when some titles are longer than others and need to wrap

I am displaying information in a card-based layout, but if any title in the card is longer than 41 characters, it doesn't fit into the card.
I thought about using [wordwrap], but all that would do is cause the one specific title to wrap and change the height of that card, affecting the layout of the other cards.
This is the PHP I use to print my results for pagination purposes, so it only prints 9 things at a time.
<div class="row">
<?php
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<div class="col xl4 l4 m12 s12">
<div class="card z-depth-5">
<div class="card-content">
<p><? echo $row["title"]; ?></p>
<p>Category: <? echo $row["category"]; ?></p>
</div>
</div>
</div>
<?php
};
?>
</div>
How would I go about line breaking every title if even one title is detected as longer than 41 characters?
EDIT: This is the solution I created:
$titlebreak = $row["title"];
if (strlen($titlebreak) >= 40)
{
$titlebreak2 = wordwrap($titlebreak, 39, "</p><p>");
}
else
{
$titlebreak2 = $row["title"] . "<p> </p>\n";
}
I've included 3 possible solutions below - adding manual line breaks as you asked about in your question; a basic but unsatisfactory CSS option and a jQuery solution which in this case is the one I would suggest as the most flexible.
Although a CSS-only solution is usually the preferred way of fixing a layout issue, when it comes to equal heights of elements there isn't a clear-cut way to do it and often a jQuery solution like the one below is required.
Manual line-break - as requested in your question
Instead of doing an additional SQL query as mentioned, you can easily do it in the PHP in 2 different ways:
(a) loop through the rows before displaying them to calculate the title lengths, then loop again to display with/without the line break
or
(b) if you really down't want to loop twice, you could include the line break regardless of length as you loop once, but also calculate the line length in that loop. Then hide the line break using CSS if its not required
(a) 2 loops: Calculate length to determine whether to add the line break or not:
<?php
$maxchars = 41;
$cards = array();
$bLongTitle = false;
while ($row = mysql_fetch_assoc($rs_result)) {
// save detaisl to $cards array
$cards[$row["title"]] = $row["category"];
// check title lengths until we find one over 41 - no need to check any more after that
if (!$bLongTitle && strlen($row["title"])) > $maxchars)
$bLongTitle = true;
}
?>
<div class="row">
<?php
foreach ($cards as $title => $category) {
?>
<div class="col xl4 l4 m12 s12">
<div class="card z-depth-5">
<div class="card-content">
<p><?
// if there were any long title, wrap them all text
if ($bLongTitle)
$title = wordwrap($title, $maxchars, "<br />\n");
echo $title;
?></p>
<p>Category: <? echo $category; ?></p>
</div>
</div>
</div>
<?php
}
?>
</div>
(b) 1 loop: Always display line break, and hide it if not required
<div class="row">
<?php
$bLongTitle = false;
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<div class="col xl4 l4 m12 s12">
<div class="card z-depth-5">
<div class="card-content">
<p class="cardTitle"><? echo wordwrap($title, $maxchars, "<br />\n"); ?></p>
<p>Category: <? echo $row["category"]; ?></p>
<?php
// check title lengths until we find one over 41 - no need to check any more after that
if (!$bLongTitle && strlen($row["title"])) > $maxchars)
$bLongTitle = true;
?>
</div>
</div>
</div>
<?php
};
?>
</div>
<?php if ($bLongTitle) {?>
<script>.cardTitle br {display:none;}</script>
<?php } ?>
CSS-only solution - not viable for the OP?
Because the titles are aren't direct siblings, the only way would be to fix the height of all title. This isn't a desirable solution, as I'm sure titles can vary a lot in length so its impossible to pick a "default" height to suit every possibility, and even that's complicated by the responsive width of the columns potentially changing the heights dynamically.
But for the sake of completeness:
add a class (e.g. .cardTitle) to the title in your loop
identify suitable heights for the title with and without a line break, and set these in your CSS
add the corresponding class (e.g. wrapTitle) to your <p> if any title is too long in a loop (similar to adding a line break above)
CSS
p.cardTitle { height:20px; } /* example of the default height for title */
p.cardTitle.wraptitle { height:40px; } /* example of height for wrapped title */
PHP (after looping through SQL rows to fill $cards array as option (a) above)
<?php
foreach ($cards as $title => $category) {
?>
<div class="col xl4 l4 m12 s12">
<div class="card z-depth-5">
<div class="card-content">
<p class="cardTitle <?php if ($bLongTitle) echo "wrapTitle"; ?>"><? echo $title; ?></p>
<p>Category: <? echo $row["category"]; ?></p>
</div>
</div>
</div>
<?php
};
?>
jQuery
You could use jQuery to loop through all elements to calculate the heights, and set them all to the tallest.
You could write the code yourself (see How to make all div columns of the same height automatically with jQuery or Setting equal heights for div's with jQuery but there is a library available to do this for you: matchHeight
Using the library, all you need to do is include it on your page and call it like this (assuming you've added the class cardTitle to the <p> that holds your title)
jQuery(document).ready(function() {
$(".cardTitle").matchHeight();
});
I would perform a new SQL query first to see if any results have a title length of greater than 41 characters:
select count(*) from table where length(title)>41
And then set the result of this query to be a variable, e.g. $has41
You can then use an if statement within your loop ...
if($has41) {
// do something with $row['title']
} else {
// do something else with $row['title']
}

PHP putting the right row in the right html div

This one is going to be a bit hard to explain but I am going to try my best.
I have a database with a table called content with 3 columns, I’m trying to get the values as rows and put them in different <div>’s. here is what I wrote so far
<?php
$sql = "SELECT * FROM content";
$query = mysqli_query($db, $sql) or die (mysqli_error());
$contentDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$content_id = $row["id"];
$content_title= $row["title"];
$content_text = $row["text"];
$contentDisplay .= '<h1>'.$content_title.'</h1> <p>'.$content_text.'</p>' ."\n";
}
$row_cnt = $query->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
?>
The row count gives 4 rows which is correct amount of rows.
In my html I have <?php echo $contentDisplay; ?> which puts out all 4 rows after each other, but I need to show the first row in my first <div>, the second row in my second <div> and so forth. thanks in advance
Update: I forgot to say that I have my <div>'s in the html part with different styles. all i need is the first row in one <div> (like on top of the page) and second row in another <div> (like on the bottom of the page) :)
Update2: here is the html code
<div class="content-top">
<section>
<h1></h1>
<p></p>
</section>
</div>
<div class="content-left">
<section>
<h1></h1>
<p></p>
</section>
</div>
<div class="content-center">
<section>
<h1></h1>
<p></p>
</section>
</div>
<div class="content-right">
<section>
<h1></h1>
<p></p>
</section>
</div>
i want the first row to be displayed in <div class="content-top"> the second row in <div class="content-left"> the third row in <div class="content-center"> and the fourth row in <div class="content-right">
<?php
$sql = "SELECT * FROM content";
$query = mysqli_query($db, $sql) or die (mysqli_error());
$rows = [];
while ($row = mysqli_fetch_array($query))
$rows[] = '<h1>'.$row['title'].'</h1> <p>'.$row['text'].'</p>' . "\n";
?>
<div class="content-top">
<section>
<?php echo $rows[0]; ?>
</section>
</div>
<div class="content-left">
<section>
<?php echo $rows[1]; ?>
</section>
</div>
<div class="content-center">
<section>
<?php echo $rows[2]; ?>
</section>
</div>
<div class="content-right">
<section>
<?php echo $rows[3]; ?>
</section>
</div>
$contentDisplay .= '<div><h1>'.$content_title.'</h1> <p>'.$content_text.'</p></div>' ."\n";
Just add divs for each row? :) This way, each row in the database will get a div.
Each row will be appended to the $contentDisplay variable, but since all you are doing is printing it, you can print the html directly.
I'm not sure why you are being downvoted, since you are asking a valid question with code that shows what you have tried so far.

Categories