I have a PHP code that posts the articles I have made, but from Oldest to Newest and I need it to be Newest to Oldest, so the order is the issue
The inside of the "posts" row inside my database
This is the function I am using to put the posts in an array:
function getPublishedPosts() {
// use global $conn object in function
global $conn;
$sql = "SELECT * FROM posts WHERE published=true";
$result = mysqli_query($conn, $sql);
// fetch all posts as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $posts;
}
And this is the visual part of the code:
<?php foreach ($posts as $post): ?>
<div class="post" style="margin-left: 0px;">
<img src="<?php echo BASE_URL . '/static/' . $post['image']; ?>" class="post_image" alt="">
<a href="single_post.php?post-slug=<?php echo $post['slug']; ?>">
<div class="post_info">
<h3><?php echo $post['title'] ?></h3>
<div class="post-body-div">
<?php echo html_entity_decode($post['body']); ?>
</div>
<div class="info">
<span><?php echo date("F j, Y ", strtotime($post["created_at"])); ?></span>
</div>
</div>
</a>
</div>
<?php endforeach ?>
just use SQL query to order by created_at.
replace your function like this.
function getPublishedPosts() {
// use global $conn object in function
global $conn;
$sql = "SELECT * FROM posts WHERE published=true order by created_at desc";
$result = mysqli_query($conn, $sql);
// fetch all posts as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $posts;
}
You could just reverse the array holding your posts using array_reverse
<?php foreach (array_reverse($posts) as $post): ?>
http://docs.php.net/manual/da/function.array-reverse.php
(Better would be of course ordering the SQL using ORDER BY, but we need more information about the available database fields.)
Related
I'm working on a little project and I want to be able to search my database for all items associated with my search
My problem is that when I use my code below, I get only one result rather than an array of all results that fit my query. I have seen some solutions that suggested using fetchAll() but that doesn't seem to output anything.
What the PHP query looks like.
if(isset($_POST['search'])){
if(preg_match("/^[a-zA-Z]+/", $_POST['sname'])){
$search = $_POST['sname']; //name in form
$pdo = & dbconnect();
$userid = $_SESSION['user_id'];
$sql = "SELECT * FROM movie_dets Where user_id=? and Title LIKE '%" .$search."%'";
$stmt=$pdo->prepare($sql);
$stmt->execute([$userid]);
if(!$stmt)
{
die("Database pull did not return data");
}
$row=$stmt->fetch();
}
}
Then I have a foreach loop in my html that looks like so
<div class="row">
<?php
$loop = 0;
foreach ($stmt as $row): //loop through result set ?>
<div class="column" >
<div>
<figure>
<img src="<?php echo "/.../".$row['Cover'] ?>" alt="<?php echo $row['Title']; ?> cover" />
<figcaption>
...
</figcaption>
</figure>
</div>
</div>
<?php
$loop++;
if ($loop % 4 ==0) //to display four results the wrap.
{
echo "</div> <div class='row'>";
}
?>
<?php endforeach ?>
</div>
In my database, there are two titles called frozen. This is supposed to output all rows when given the 'fr' search word. Instead, it only fetches one of them.
I want to get some data from a MySql database which has the same ID but different values. see the image (this is just a sample)
Although the venue styles are different, I want to pull all the styles with the same ID. I'm using a foreach loop to get the data from the database.
How can I improve my code to achieve what I want.
<?php
$myrows = $wpdb->get_results( "SELECT vf_venues.title, vf_venues.mainimage,
vf_venues.permalink, vf_venuestyles.slug
FROM vf_venues
LEFT JOIN vf_venuestyles ON vf_venuestyles.vid=vf_venues.vid WHERE
vf_venuestyles.vid=vf_venues.vid" );?>
<div class="venue-list venue-grid">
<?php
foreach ( $myrows as $myrow ) {
//pull the data from the DB
"<pre>"
$venueName = $myrow->title;
$mainImage = $myrow->mainimage;
$permalink = $myrow->permalink;
$slug = $myrow->slug;
$vid = $myrow->vid;
"<pre>"
?>
<li class="venue-block block">
<div class="venue-img">
<a href="<?php echo $permalink; ?>">
<img src="<?php echo $mainImage; ?>">
</a>
</div>
<div class="venue-details"><h2><?php echo $venueName; ?></h2></div>
<?php echo $slug; ?>
<?php echo $vid; ?>
</li>
<?php
}
?>
</div>
I managed to fix this by creating a for loop within the existing for loop. I then created a sql query to pull the venue styles for that venue.
I have a table called "races" in my Wordpress database.
main.php
my events page displays all of my races inside the table "races" - everything works fine here
<?php
global $wpdb;
$table_name = $wpdb->prefix . "races";
$result = $wpdb->get_results ( "SELECT * FROM races ORDER BY date_start LIMIT 4" );?>
<div class="events-schedule">
<?php
foreach ( $result as $race ) {
$title = $race->title;
$raceid = $race->race_id;
$location = $race->venue;
$icon = $race->race_icon;
?>
<div class="wrapper">
<div class="row">
<div class="small-12 medium-4 columns event-icon text-center">
<img src="<?php echo $icon; ?>">
</div>
<div class="small-12 medium-8 columns text-center">
<?php echo $id; ?>
<h3 class="tagline location"><?php echo $location; ?> </h3>
<h2><?php echo $title; ?></h2>
<div><a class="btn yellow" href="/test/?id=<?php echo $id; ?>">Apply Now</a></div>
</div>
</div>
<?php
echo '</div>';
} ?>
</div> <?php
?>
test.php I am trying to display the other fields on this individual page when you go to http://mywebsite.com/test/?id=64
All I am getting is the number "64" which is fine because that is the correct ID!
I am trying to retrieve the other fields, such as the title, venue, etc.. but not working. Am I missing something?
Thank you in advance.
<?php
$id = $_GET['id'];
echo $id;
$result = $wpdb->get_results ( "SELECT * FROM races WHERE id='$id'" );
foreach ($result as $race) {
$title = $race->title;
echo $title;
}
?>
You are probably not getting back any results, so the for loop never executes. Are you sure that id 64 actually exists?
Also it is a terrible practice to put variables from the URL directly in the query. I can inject SQL into your system as easily as appending it to the URL. You need to sanitize your input to protect yourself from attackers.
After seeing your db schema it looks like the id field is actually named race_id. So your query should be like this:
$wpdb->get_results ( "SELECT * FROM races WHERE race_id='$id'" );
Firstly remove single quote from id and make your query like this
$wpdb->get_results ( "SELECT * FROM races WHERE race_id=$id" );
for display all fields do this
foreach($result as $race){
echo $title = $race->title;
echo $field_1= $race->field_1;
echo $field_2= $race->field_2;
echo $field_3= $race->field_3;
}
Note:: put your fields in place of field_1,field_2,field_3
I have 2 SQLite- tables, one containing articles and one containing image URL's.
What I'd like to do is to do a foreach() to show the articles in order and show a set number of random images next to the article.
The images should be selected by checking similarity between the Article's and image's categories (column in the table) and then randomized. (The article catergory could be for example 'motorboats' and the img category 'boat').
How do I show the results from two different arrays?
The code for the articles is:
$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="artikelLista">
<?php foreach($res as $article): ?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?>
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
To add the second array, I tried this, which didn't work, it only showed the results from the first array multiple times:
$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt2 = $db->prepare('SELECT * FROM Object;');
$stmt2->execute();
$res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="artikelLista">
<?php foreach($res as $article): ?>
<?php foreach($res2 as $object): ?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?><br>
<?php echo $object['img'];?> <!-- For testing. The images should be filtered and a a few random images would be shown here -->
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
I guess it's not possible to use nested foreach() like this.
How will I manage this?
Also, If anyone knows on top of their head how to match the similarities between the arrays as described above, I'd be greatful. If not, I'll deal with this later.
You can fall a function inside the first foreach a pass category of the article to that function. Now in that functino collect all images in an array related
to the passed category and then return it by randomizing it. Code below ..
<?php foreach($res as $article): ?>
<?php
$img = get_img($article['category']);
?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?><br>
<img src="<?php echo $img; ?>" /> <!-- The return result will be shown here -->
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
<?php
function get_img($category){
$stmt2 = $db->prepare('SELECT * FROM Object WHERE category = '.$category);
$stmt2->execute();
$res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$rnd = array();
foreach($res2 as $object){
$rnd[] = $object['img'];
}
$n = rand(0,(count($rnd)-1));
return $rnd[$n];
}
?>
I have two tables 'p_tuts' and 'h_tuts'. I'm using a method to display all the returned rows. Although I'm not sure how to set it up to run multiple queries, I can only get it to return one query at a time. Heres my code...
public function QueryAll($my_field, $limit) {
$query = mysql_query("SELECT * from $my_field LIMIT $limit");
$rows = array();
while($row = mysql_fetch_array($query)) {
$rows[] = $row;
}
return $rows; }
Here is my index file
<?php $results = $Database->QueryAll('p_tuts', 5); ?>
<?php foreach ($results as $result): ?>
<div class="tutorial">
<div class="tut_header"><h2><?php echo $result['tut_header']; ?></h2></div>
<div class="tut_poster">Posted by: <?php echo $result['tut_poster']; ?> on <?php echo $result['tut_date']; ?></div>
<div class="tut_img rounded"><img src="<?php echo "img_uploads/". $result['tut_img']; ?>" width="180" height="151" /></div>
<div class="tut_content"><p><?php $Website->CharLimit($result['tut_content'], 800); ?></p></div>
</div>
<?php endforeach; ?>
I'd really like to adapt it so I can use this class to display both multiple tables, rather than just the one.
kind regards
This is difficult to answer without knowing the relationship between the two tables, but it looks like you need to use a JOIN or UNION.