I have a query that selects 3 rows; but I only want to display the one row at a time, use the data from that row, then move to the next row, then repeat. How would this be accomplished? Table has 4 items in it.
PHP:
<?php
$server = "secret";
$user = "secret";
$pass = "secret";
$db = "secret";
$con=mysqli_connect($server,$user,$pass,$db);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'SELECT * FROM news ORDER BY id DESC LIMIT 3';
mysqli_select_db($con, $db);
$query = mysqli_query($con, $sql);
$number = 1;
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
}
mysqli_close($con);
?>
Attempt to display:
<div name='title'><?php echo $title; ?></div> || <div name='news_date'><?php echo $news_date; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post; ?></p>
<?php
$number++;
?>
Output of attempt:
Test
||
7/14/13
News 1
Testing to see if this will work lalalalalla
NOTE: Tried to repeat the attempt to see if it would work, but it displayed same as output but with a second one that was a duplicate except said News 2
Desired output look:
Newest Title | Newest Date
Newest news. Etc. Insert Big Paragraph of news here etc etc.
2nd Newest Title | 2nd Newest Date
2nd Newest news. Etc. Insert Big Paragraph of news here etc etc.
3rd Newest Title | 3rd Newest Date
3rd Newest news. Etc. Insert Big Paragraph of news here etc etc.
The problem is that you are overwriting your variables with each while() loop -
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
}
so when you try to echo $id, $title, $news_date, and $post, you will only get the last row data
you either need to add your html in the while loop -
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
?>
<div name='title'><?php echo $title; ?></div> || <div name='news_date'><?php echo $news_date; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post; ?></p>
<?php
$number++;
}
or save them to an array
$id = array();
$title = array();
$news_date = array();
$post = array();
while ($result = mysqli_fetch_array($query)) {
$id[] = $result['id'];
$title[] = $result['title'];
$news_date[] = $result['news_date'];
$post[] = $result['post'];
}
and then access the array in your display
<div name='title'><?php echo $title[$number-1]; ?></div> || <div name='news_date'><?php echo $news_date[$number-1]; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post[$number-1]; ?></p>
<?php
$number++;
?>
I used [$number-1] as I assume $number is starting at 1, and arrays are 0 based
edit here are ways to echo your html. It would be beneficial to visit the php documentation, as all of this is there. In these I set $number back to 0, but you can change it back to 1, and just change each of the $number->$number-1, and the $number+1->$number
using a for loop - http://php.net/manual/en/control-structures.for.php
<?php
for($number=0;$number<count($title);$number++){
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
}
?>
using a foreach loop - http://php.net/manual/en/control-structures.foreach.php
<?php
foreach($title as $number => $value{
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
}
?>
using a while loop - http://php.net/manual/en/control-structures.while.php
<?php
$number = 0;
while($number<count($title){
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
$number++;
}
?>
each of the above was done by closing out of php, and writing the html, and then opening php again. You could also just stay in php, and echo the html - http://php.net/manual/en/function.echo.php
<?php
for($number=0;$number<count($title);$number++){
echo "<div name='title'>".$title[$number]."</div> || <div name='news_date'>".$news_date[$number]."</div>";
echo "<p>News ".($number+1)."</p>";
echo "<p>".$post[$number]."</p>";
}
?>
Related
I'm looking for a way to display:
<h1>State1</h1>
<h2>City1</h2>
<p>Address1</p>
***if next address is in the same state:*
<h2>City2</h2>
<p>Address2</p>
<hr>
**if next address is NOT in the same state
<h1>State2</h1>
<h2>City3</h2>
<p>Address3</p>
I'm using:
<?php
$query = "SELECT * FROM places";
$select_all_places = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc()){
$p_state = $row['p_state'];
$p_city = $row['p_city'];
$p_address = $row['p_address'];
?>
<h1><?php echo $p_state ?></h1>
<h2><?php echo $p_city ?></h2>
<p><?php echo $p_address ?></p>
<?php } ?>
Take a look at the code here. I added some semicolons on your echo statements and added the query variable into the mysqli_fetch_assoc method for you. I added some comments as well to help you understand what I have done here.
<?php
$query = "SELECT * FROM places";
$select_all_places = mysqli_query($connection, $query);
// This will be the state we are currently on. Start it as null.
$current_state = '';
while($row = mysqli_fetch_assoc($select_all_places)){
$p_state = $row['p_state'];
$p_city = $row['p_city'];
$p_address = $row['p_address'];
?>
<!-- Check if variable state is equal to current row's state. -->
<?php if($current_state != $p_state): ?>
<!-- Echo state if they aren't equal -->
<h1><?php echo $p_state; ?></h1>
<!-- Assign new current state -->
<?php $current_state = $p_state; ?>
<?php endif; ?>
<h2><?php echo $p_city; ?></h2>
<p><?php echo $p_address; ?></p>
<?php } ?>
I have set-up a news page which retrieves news from MYSQL news table.
I am trying to identify if the news column is odd or even, so if the news columns is odd or even it will add a class to the div element.
My code is as follows:
<?php
$cat = $_GET['cat'];
$date = $_GET['date'];
if ($date !="") {
$date = explode('-', $date);
$year = $date[1];
$month = $date[0];
$month = date("m", strtotime($month));
$sql = "SELECT * FROM news WHERE year(newsDate) = '$year' AND month(newsDate) = '$month' AND newsState = 1 ORDER BY newsDate DESC";
} else {
$sql = "SELECT * FROM news WHERE newsState = 1 ORDER BY newsDate DESC";
}
$result = $conn->query($sql);
$rows = $result->num_rows;
$pager = new PS_Pagination($conn, $sql, 5, 10, null);
$rs = $pager->paginate();
$num = $rs->num_rows;
if($num >= 1 ){
while($row = $rs->fetch_assoc()){
?>
<div class="news <?php echo $num; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php } } else {
echo "No records found!";
}
if ($rows >= 5) {
echo "<div class='page-nav blog-nav'>";
echo $pager->renderFullNav();
echo "</div>";
}
?>
TAke any flag which maintains odd-even position...
$f = 0; //ADDED THIS LINE
if($num >= 1 ){
while($row = $rs->fetch_assoc()){
if($f%2==0) //ADDED THIS LINE
$class_name = "even"; //ADDED THIS LINE
else //ADDED THIS LINE
$class_name = "odd"; //ADDED THIS LINE
?>
<div class="news <?php echo $class_name; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php $f++; } } else {
echo "No records found!";
}
if($num >= 1 ){
$tr = 1;
while($row = $rs->fetch_assoc()){
if($tr%2 == 0)
{
//then even class
}
else
{
//odd class
}
?>
<div class="news <?php echo $num; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php $tr++; } } else {
echo "No records found!";
}
Use counter variable and check if it is even or odd ?
Create variable, increment that in each loop and check, if $i % 2 is 0 (even) or 1 (odd).
$i = 1;
while($row = $rs->fetch_assoc()){
?>
<div class="news <?php echo $num; echo $i % 2 == 0 ? ' even' : ' odd' ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php
$i++;
}
Take $classname = '';
Get news ID in loop and divide / 2 and compare whether you getting odd / even value. In case odd value add $classname = 'oddCLASS' and in case even value add $classname = 'evenCLASS' and updare class = $classname wherever you required.
This way it will automatically update dynamic class.
so the fastest way to do this is just by using a boolean:
$odd = false;
while ( .... )
{
echo ($odd = !$odd) ? 'odd' : 'even';
}
No need to keep a counter for that, no need for a modulo and it keeps the code pretty clean. My preferred way unless you need to keep a counter. And even then: $counter & 1 == 1 is faster than $counter % 2 == 1 and does exactly the same.
Simple explanation:
echo ($odd = !$odd) ? 'odd' : 'even';
// will become
$odd = ! $odd; // it flips the boolean
if ($odd)
echo 'odd';
else
echo 'even';
index.php:
<?php
$st = $pdo->query("SELECT * FROM post WHERE parent=0 ORDER BY no DESC");
$posts = $st->fetchAll();
for($i = 0;$i < count($posts); $i++){
$st = $pdo->query("SELECT * FROM post WHERE parent={$posts[$i]['no']} ORDER BY no");
$posts[$i]['child'] = $st->fetchAll();
}
require 'd_index.php';
?>
d_design.php:
foreach($posts as $post) { ?>
<div class="post_parent">
<h3>no:<?php echo $post['no'] . "Title:" . $post['title'] ?></h3>
<p><?php echo $post['name'] ?></p>
<p><?php echo nl2br($post['content']) ?></p>
<p>comment</p>
<p><small>posted:<?php echo $post['time'] ?></small></p>
<?php foreach($post['child'] as $child) { ?>
<div class="post_child">
<h4>no:<?php echo $child['no'] . "Title:" . $child['title'] ?></h4>
<p><?php echo $child['name'] ?></p>
<p><?php echo nl2br($child['content']) ?></p>
<p><small>posted:<?php echo $child['time'] ?></small></p>
</div>
<?php } ?>
</div>
<?php } ?>
I want to nest the foreach, but in this code, the second foreach($child) can't indicate.
You can achive this by making your loop recursive. Example:
function loop_posts($posts) {
foreach($posts as $post) {
echo $post->name;
if (isset($post['child'])) {
loop_posts($post['child']);
}
}
}
loop_posts($posts);
Im reading questions and answers columns of my faq table.
And I want to show my faq questions and correspondent answers where status is icual to 1.
I know how can I do this with two selects, but with one select Im not see how it is possible.
Because I can´t do something like my example1: (Because Im repeating my <ol> </ol> in my while loop and dont works great.)
Do you know how can I do this using just one select?
example1:
<div id="container">
<?php
$read = mysql_query("SELECT * FROM faq WHERE status = 1");
$lines = mysql_num_rows($pesquisa);
?>
<h2>FAQ: Answers to <?php echo $lines ?> frequently asked questions.</h2>
<?php
while($result = mysql_fetch_array($read)){
$question = $result['question'];
$answer = $result['answer'];
echo '<ol>';
echo '<li>'.$question.'</li>';
echo '</ol>';
echo '<hr/>';
echo '<div id="answers">';
echo '<h2>'.$question.'</h2>';
echo '<p>'.$answer.'</p>';
echo '</div>';
}
?>
</div>
My code:
<div id="container">
<?php
$read = mysql_query("SELECT * FROM faq WHERE status = 1");
$lines = mysql_num_rows($pesquisa);
?>
<h2>FAQ: Answers to <?php echo $lines ?> frequently asked questions.</h2>
<ol>
<?php
while($result = mysql_fetch_array($read)){
$question = $result['question'];
$answer = $result['answer'];
echo '<li>'.$question.'</li>';
}
?>
</ol>
<hr/>
<div id="answers">
<h2><?php echo $question; ?></h2>
<p><?php echo $answer; ?></p>
</div>
</div>
alright, here is what you looking for;
<div id="container">
<?php
$read = mysql_query("SELECT * FROM faq WHERE status = 1");
$lines = mysql_num_rows($pesquisa);
$results = array();
while($result = mysql_fetch_array($read)){
$results[]=$result;
}
?>
<h2>FAQ: Answers to <?php echo $lines ?> frequently asked questions.</h2>
<ol>
<?php
foreach($results as $result){
$question = $result['question'];
$answer = $result['answer'];
$link='#'.$question;
echo '<li><a href='.$link.'>'.$question.'</a></li>';
}
?>
</ol>
<hr/>
<div id="answers">
<?php
foreach($results as $result){
$question = $result['question'];
$answer = $result['answer'];
echo'<div id='.$question.'>';
echo"<h2>".$question."</h2>";
echo"<p>".$answer."</p>";
}
?>
</div>
</div>
I'm not sure I understand exactly what you are asking but is it something like this?
<div id="container">
<?php
$read = mysql_query("SELECT * FROM faq WHERE status = 1");
$lines = mysql_num_rows($pesquisa);
?>
<h2>FAQ: Answers to <?php echo $lines ?> frequently asked questions.</h2>
<ol>
<?php
while($result = mysql_fetch_array($read)){
$question = $result['question'];
$answer = $result['answer'];
echo '<li>'.$question.'</li>';
}
?>
</ol>
<hr/>
<div id="answers">
<?php
reset($read);
while($result = mysql_fetch_array($read)){ ?>
<h2 name='<?php echo str_replace(" ","",$question); ?>'><?php echo $result['question']; ?></h2>
<p><?php echo $result['answer']; ?></p>
<? }?>
</div>
</div>
If you are just dealing with a formatting issue then don't use the ol tag...you can reproduce any effect you want with simple divs.
Try using an array :
<div id="container">
<?php
$read = mysqli_query("SELECT * FROM faq WHERE status = 1");
$lines = mysqli_num_rows($pesquisa);
$result = mysqli_fetch_all($read); //<- Put all results in one array to work on
?>
<h2>FAQ: Answers to <?php echo $lines ?> frequently asked questions.</h2>
<ol>
<?php
foreach($row in $result) {
echo '<li>'.$row['question'].'</li>';
}
?>
</ol>
<hr/>
<div id="answers">
<?php
foreach($row in $result) {
echo '<h2>'. $row['question'].'</h2>';
echo '<p>'. $row['answer'].'</p>';
}
?>
</div>
</div>
I've got a table called tickets. The Tickets table has 4 columns: user_id, ticket_id, subject, message. I want to loop the ticket_id and subject of the logged in user. I want to echo it with foreach, but I cant get it to work. This is what I've got:
Query:
$showTheTickets = array();
$user_id = $_SESSION['user_id'];
$getTickets = mysqli_query($mysqli,"SELECT * FROM tickets WHERE user_id = '$user_id'") OR die (mysqli_error($mysqli));
while($row = mysqli_fetch_assoc($getTickets)){
$showTicketID = $row['ticket_id'];
$showTicketSubject = $row['subject'];
}
Code in the page:
<?php foreach ($showTheTickets as $showTheTickets): ?>
<div class="preview">
<?php echo $showTicketID ?>
<?php echo $showTicketSubject ?>
</div>
<?php endforeach; ?>
Anyones willing to help me? Thanks.
Try this:
$showTheTickets = array();
$user_id = $_SESSION['user_id'];
$getTickets = mysqli_query($mysqli,"SELECT * FROM tickets WHERE user_id = $user_id") OR die (mysqli_error($mysqli));
while($row = mysqli_fetch_array($getTickets)){
$row = array( 'ticket_id' => $row['ticket_id'], 'subject' => $row['subject'] );
$showTheTickets[] = $row;
}
And then:
<?php foreach ($showTheTickets as $stt): ?>
<div class="preview">
<?php echo $stt['ticket_id'] ?>
<?php echo $stt['subject'] ?>
</div>
<?php endforeach; ?>
Hope it helps...
You are overwriting the values you get from the query and your $showTheTickets array remains empty.
You probably want something like:
$showTheTickets = array();
while($row = mysqli_fetch_assoc($getTickets)){
$showTheTickets[$row['ticket_id']] = $row['subject'];
}
and:
<?php foreach ($showTheTickets as $id => $subject): ?>
<div class="preview">
<?php echo $id; ?>
<?php echo $subject; ?>
</div>
<?php endforeach; ?>
Why not simply
while($row = mysqli_fetch_assoc($getTickets)){
?><div class="preview"><?
echo $row['ticket_id'];
echo $row['subject'];
?></div><?
}
you have to save $showTicketID and $showTicketSubject in a array (could be the same array or 2 arrays) and then in the view show the arrays, like this:
while($row = mysqli_fetch_assoc($getTickets)){
$array[$row['ticket_id']] = $row['subject'];
}
and the view:
<?php foreach ($showTheTickets as $ticketid => $ticketsubject): ?>
<div class="preview">
<?php echo $ticketid ?>
<?php echo $ticketsubject ?>
</div>
<?php endforeach; ?>