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++;
}
?>
Related
For parsing a list of articles, i have this code to parse all the articles:
while($article = $articles->fetch())
{
$date = strtotime($article['createdAt']);
$formatted_date = date("F Y",$date);
?>
<br />
<div class="news-content">
<div class="news-image">
<?php echo $article['title']; ?>
</div>
<div class="news-article">
<h3>
<span><?php $date = strtotime($article['createdAt']); echo /*date("F j",$date);*/ strftime('%e %B',$date) ?></span>
<br />
<?php echo $article['title']; ?>
</h3>
</div>
</div>
<?php
} //end while loop
?>
What i want to achieve: only the first 5 <div class="news-content">...</div> should be shown.
I know i have to do something with a for loop
but i do not know exactly how to use the for loop for this situation...
Can someone help me with that?
There are a lot of different ways to limit a loop. One possibility is to use a for loop instead of a while loop. for is often a good option if you want something to happen a specific number of times. Adding something else like fetch into the continuation condition will mean it happens up to a specific number of times.
for ($i = 0; $i < 5 && $article = $articles->fetch(); $i++) {
// output article
}
I've the following query
As you see jigsaw repeats twice because the movie has two categories
but i would like to echo both categories but not twice the movie..
<?php
while ($mInfo = $testquery->fetch(PDO::FETCH_ASSOC)) {
?>
<div class="col-xs-6 col-sm-4 col-md-3">
<a href="movie.php?title=<?php echo $mInfo['titleEN']; ?>&m=<?php echo $mInfo['imdbID']; ?>" title="<?php echo $mInfo['titleEN']; ?>" alt="<?php echo $mInfo['titleEN']; ?>" target="_self">
<div class="movie-info">
<img src="assets/images/poster/<?php echo $mInfo['poster']; ?>.jpg" alt="<?php echo $mInfo['titleEN']; ?>">
</div>
<div class="movieinformation">
<div class="movie-title"><?php echo $mInfo['titleEN']; ?></div>
<div class="movie-categories">I WOULD LIKE TO ECHO THE CATEGORIES HERE</div>
</div>
</a>
</div>
<?php
}
?>
So far i just could do it, could anyone help me with that?
Here's a concept for such tasks. I kept it with general names and left out html on purpose.
$oldMainId = null; // Initialize to null to start with. This will be needed later.
while ($item = $result->fetch()) { // get your items (movies in your case)
if($oldMain != $item['mainId']) {
// only show title if you haven't yet
echo $item['mainTitle'];
}
// always show the category though
echo $item['sub'];
// re-set the 'old' variable.
$oldMainId = $item['mainId'];
}
I would use
OPTION 1
$res = $stmt->fetchAll(PDO::FETCH_GROUP);
Then it will group on the first column, assuming that is movie ID, or something unique to the movie you would get multiple rows in a nested array for that movie.
Then when you iterate thorough them you can loop over the nested array for the genre stuff
OPTION 2
Another option is to use GROUP_CONCAT and group by the movie id,
SELECT GROUP_CONCAT(genre) AS genre, ... WHERE ... GROUP BY movieID
But be aware that GROUP_CONCAT does have a setting for max length and it will silently truncate your data if it exceeds it.
OPTION 3
You can build the structure yourself (same as fetch group does)
$data = [];
while ($mInfo = $testquery->fetch(PDO::FETCH_ASSOC)) {
$key = $mInfo['movieid']
if(!isset($data[$key])) $data[$key] = [];
$data[$key][] = $mInfo;
}
Then go through that and do your html by using a second foreach($data as ...) It has to be done after organizing the data as the order of the result is unknown.
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.
Anyone knows how to do create multiple cards looping through a PHP array?
For example, I have 5 friend with 5 description corrresponding each friend (from a mysqli table) saved in $friendList.
So I want, for each row, to create and show a card with the friend as a header and its description as the content of the card.
This would be the loop
while ($row = mysqli_fetch_array($friendList, MYSQLI_ASSOC)){
// $row['friend'];
// $row['description'];
}
but then, I do not know how to create the cards with the variables obtained:
Assuming that you have $friendList variable already defined and it is a mysqli_result object, here's how you can do it:
<?php while($row = mysqli_fetch_array($friendList, MYSQLI_ASSOC)): ?>
<div class="w3-card-4 test">
<img src="img_avatar3.png" alt="Avatar">
<div class="w3-container">
<h4><b><?php echo $row["friend"] ?></b></h4>
<p><?php echo $row["description"] ?></p>
</div>
</div>
<?php endwhile; ?>
Feel free to ask any questions :-)
I have a list of names in a database that i want to display one by one
(also for bonus points, another column in the database is a Boolean value for if a task is completed or not. if this is true i want the css content box background to be green instead of red.)
so how can i select a name from row one, put it to a PHP variable, then select the value from the "Name" column in row 2 and put that to another PHP variable or the next item in the array?
thanks for any help!
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="mngPWinCSS.css"/>
</head>
<body>
<?php
$dsn ='mysql:host=****.******.com;dbname=o****_**n';
$username='********';
$password ='******';
mysql_connect('localhost',$username,$password);
$query=mysql_query("SELECT Name FROM CLOAS_Team LIMIT 0,1");
$bob="dkajfk";
$url=$_SERVER['REQUEST_URI'];
header("Refresh: 60; URL=$url");
$com[1]="i";
$com[2]="i";
$com[3]="i";
$com[4]="i";
$com[5]="i";
$com[6]="i";
$name=mysql_fetch_array($query);
?>
<div id="content">
<img src="logjpg.JPG" alt="Smiley face" height="50" width="200">
<h3>CLOAS Tracker</h3>
</div>
<div id="Content">
<?php
?>
<div id="complete">
<h3names>
<?php
echo $name['Name'];
?>
</h3names>
</div>
<div id="incomplete">
<h3names>Name2</h3names>
</div>
</div>
</body>
</html>
First you need to change your SELECT query to select all of the rows that you wish to display, perhaps by taking off the LIMIT clause. Something like this;
$result=mysql_query("SELECT Name FROM CLOAS_Team");
(This will get you all of the names in your table.)
Next, you need to loop through the results you got from this query, like so;
$names = array();
while($row = mysql_fetch_assoc($result))
{
$names[] = $row['Name'];
}
This will put them into the array $names for you, which you can then work with. Instead of putting them into the array, you might want to output them immediately, perhaps like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div>
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>
However, you have many more errors in your code. Such as;
You can't just invent html elements called <h3names>
I doubt that you want to set the id attribute to 'incomplete'. An id should be unique, I expect you should be putting this in as a class (class = "incomplete")
I don't think your line header("Refresh: 60; URL=$url"); will do anything as your headers have already been sent to the page. If you want this line to work, it needs to be right at the top, BEFORE any output has been sent to the browser.
And for the bonus point, include the 'Completed' field in your query (if that is what it is called) and use this to add a style to each <div> element that you display in your loop. So your query might become;
$result=mysql_query("SELECT Name, Completed FROM CLOAS_Team");
And your loop would now be like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div style = "background-color:<?php echo $row['Completed'] == true ? 'green' : ' red'; ?>">
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>