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];
}
?>
Related
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.)
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 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
<?php
require_once 'db/connect.php';
if(isset($_GET['keywords'])) {
$keywords = $db->escape_string($_GET['keywords']);
$query = $db->query("
SELECT title
FROM articles
WHERE body LIKE '%{$keywords}%'
OR title LIKE '%{$keywords}%'
");
?>
<div class="result-count">
Found <?php echo $query->num_rows; ?> results
</div>
<?php
if($query->num_rows) {
while($r = $query->fetch_object()) {
?>
<div class="result">
<?php echo $r->title; ?>
</div>
<?php
}
}
}
It appears that all you are querying for is the article title? if this is all you need for the url then just replace the
<?php echo $r->title; ?>
with
<?php echo $r->title; ?>
however if you need an id or something else then you will need to ensure your database query is returning that data for example
SELECT ID, Title FROM...
then use
<a href="http://example.com/<?php echo $r->id; ?>">...
I am creating a forum and the code I am putting in this thread is the page that shows all of the forum categories. I have this setup where I have an id, category_section, category_title, and category_description. The way it is structured now is that it creates a new category section border every time I add a new category title in my database. This is what I mean by this:
As an example:
My category section is called Shoes, my category titles are Nike, Adidas, Reebok
Currently, it does:
Shoes
Nike
Shoes
Adidas
Shoes
Reebok
But it should do this:
Shoes
Nike
Adidas
Reebok
How can I get my current code to do this?
$query = mysqli_query($con,"SELECT * FROM forum_categories ORDER BY category_title DESC");
$numrows = mysqli_num_rows($query);
$categories = "";
if($numrows > 0){
while($forum_row = mysqli_fetch_assoc($query)){
$categoryid = $forum_row['id'];
$category_section = $forum_row['category_section'];
$categoryTitle = $forum_row['category_title'];
$categoryDescription = $forum_row['category_description'];
$categories = "<a href='forum_view_category.php?cid=".$categoryid."'>"
. $categoryTitle . "</a>";
//$categories .= "<a href='forum_view_category.php?cid=".$categoryid
//."' class='cat_links'>" . $categoryTitle . "</a>" " - " . $categoryDescription .;
?>
<div class="category_section">
<?php echo $category_section; ?>
</div>
<div class="category_border">
<div class="discussions_left">
<div class="discussions_category_title">
<?php echo $categories; ?>
</div>
<div class="discussions_category_description">
<?php echo $categoryDescription; ?>
</div>
</div>
<div class="discussions_right">
</div>
</div>
<?php
}
//echo $categories;
} else {
echo "<p>There are no posted categories available yet. </p>";
}
I would change your SQL to order by section first, then the title.
SELECT * FROM forum_categories ORDER BY category_section DESC, category_title DESC
After you've done that, define an if statement to check if the current section is the same as the previous statement.
If so, move one.
If not, echo the new section title.
I've cleaned up your code a bit and switched to the Alternative syntax for control structures for readability and maintainability.
PHPFiddle Demo (faked MySQL)
<?php
$query = mysqli_query($con,"SELECT * FROM forum_categories ORDER BY category_section DESC, category_title DESC");
$category_section = "";
?>
<?php if(mysqli_num_rows($query) > 0): ?>
<?php while($cat = mysqli_fetch_assoc($query)): ?>
<?php if($cat['category_section'] !== $category_section): ?>
<?php $category_section = $cat['category_section'] ?>
<div class="category_section">
<?= $category_section ?>
</div>
<?php endif; ?>
<div class="category_border">
<div class="discussions_left">
<div class="discussions_category_title">
<a href="forum_view_category.php?cid=<?= $cat['id'] ?>">
<?= $cat['category_title'] ?>
</a>
</div>
<div class="discussions_category_description">
<?= $cat['category_description'] ?>
</div>
</div>
<div class="discussions_right">
</div>
</div>
<?php endwhile; ?>
<?php else: ?>
<p>There are no posted categories available yet.</p>
<?php endif; ?>