For example: I have a page that lists book titles stored in a database. What I want to happen is WHEN it gets to a certain book title say something different or add additional info like "ON SALE".
Is there a function that exists that allows me to manipulate data inside a loop?
I've tried a couple of things, but have not gotten the desired results.
Here's my thought process:
Query:
$sql = "SELECT *
FROM `artist`
ORDER BY artist_name ASC";
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
Output:
<?php while ($r = $q->fetch()); ?>
<li class="<?php echo $r['sort_status']; ?>">
<figure>
<div class="gallery-img"><img src="books/<?php echo $r['photo']; ?>" alt="picture of <?php echo $r['book_title']; ?>"></div>
<figcaption>
<h3 class="padding-fifteen-bottom"><?php $book = $r['book_title']; if($book=="A Tale of Two Cities"){echo "A Tale of Two Cities - On Sale NOW! ";} else { echo htmlspecialchars_decode(truncate($book,34));}?></h3>
</figcaption>
</figure>
</li>
<!-- end work item -->
<?php endwhile; ?>
Yes!
if($book_title == "My Title")
{
// Logic here.
}
HTML format
<?php if($book_title == "My Title"): ?>
<p>my html</p>
<?php endif;?>
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 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'm building a blog and I'm done with the webpage which shows all the posts with their titles, pictures and short descriptions (each post = one picture, one title and one description). Next I want to enable redirecting users to a page with a full post after clicking a chosen title, but I don't know where to start.
home.php
<?php
session_start();
require_once('connection.php');
mysql_select_db($database_connection, $connection);
$query_post = "SELECT postID, title, date, category, description, pimage, text FROM post";
$post = mysql_query($query_post, $connection) or die(mysql_error());
$row_post = mysql_fetch_assoc($post);
$totalRows_post = mysql_num_rows($post);
mysql_select_db($database_connection, $connection);
$query_joining = "SELECT * FROM image inner join post on post.pimage = image.imagename";
$joining = mysql_query($query_joining, $connection) or die(mysql_error());
$row_joining = mysql_fetch_assoc($joining);
$totalRows_joining = mysql_num_rows($joining);
?>
<ul>
<?php
while($row_joining = mysql_fetch_assoc($joining)) {
?>
<li>
<img src="images/<?php echo $row_joining['imagename']; ?>">
<h3><?php echo $row_joining['title']; ?></h3>
<p><?php echo $row_joining['description']; ?></p>
Read more
</li>
<?php
}
?>
</ul>
post.php
<div>
<h1><?php echo $row_post['title']; ?></h1>
<img "images/<?php echo $row_post['pimage']; ?>">
<h4><?php echo $row_post['date']; ?>, <?php echo $row_post['category']; ?></h4>
<p><?php echo $row_post['text']; ?></p>
</div>
I know that especially the post.php needs changes, but I don't know how to proceed so that the chosen post will be displayed in post.php.
When you showing all posts, in the href you can put like this:
<a href="post.php?post='.$row_post['postID'].'">
Then in post.php you can do something like:
if (isset($_GET['post']))
{
// check if post is integer
// check if post exist in database
// show content from that post only. WHERE postID = data
}
else
{
// list all posts.
}
Been looking around and am stumped. Basically I'm trying to filter out a result from an xml feed and hide it from displaying in the html output. I'm trying to find out the venue "Hornblower Cruises and Events" and if it exists, hide the whole , which is the parent of all the nodes.
Here's the URL: http://www.sandiegomagazine.com/goldstartest/rss3-exclude.php
Here's my code:
<?php
$myfeed = simplexml_load_file('https://www.goldstar.com/api/listings.xml?api_key=6d0d598c69dfecfcf028b0d2b3c9b693b606ad8c&postal_code=92101');
$i = 0;
foreach ($myfeed as $goldstar):
$title=$goldstar->headline_as_html;
$summary=$goldstar->summary_as_html;
$dates=$goldstar->upcoming_dates->event_date->date;
$ourprice=$goldstar->our_price_range;
$fullprice=$goldstar->full_price_range;
$img=$goldstar->image;
$link=$goldstar->link;
$venue_name=$goldstar->venue->name;
$venue_street=$goldstar->venue->address->street_address;
$venue_locality=$goldstar->venue->address->locality;
$venue_region=$goldstar->venue->address->region;
$venue_zip=$goldstar->venue->address->postal_code;
$venue_phone=$goldstar->venue->phone;
$category=$goldstar->category_list->category->name;
// if ($venue_name == 'Hornblower Cruises and Events'){
// unset($myfeed->event);
//echo $myfeed->asxml();
//}
if (++$i > 20) {
// stop after 10 loops
break;
}
?>
<html>
<head></head>
<body>
<div class="gs-item">
<div class="gs-itemcontent">
<h3 class="gs-cat"><?php echo $category; ?></h3>
<h2><?php echo $title; ?></h2>
<h4 class="gs-date">Date: <?php echo $dates; ?> <br/>For more show dates, click here</h4>
<img src="<?php echo $img; ?>" />
<p><?php echo $summary; ?></p>
<div id="gs-callout">
<span class="fullprice">Full Price: <?php echo $fullprice; ?></span>
<br/>
<span class="ourprice">Our Price: <span class="gs-hilite"><?php echo $ourprice; ?></span></span>
<p><a class="gs-button" href="<?php echo $link; ?>" target="_blank">Buy Tickets ยป</a></p>
</div>
<ul class="gs-venue">
<li><strong><?php echo $venue_name; ?></strong> | </li>
<li><?php echo $venue_street; ?></li>
<li><?php echo $venue_locality; ?>, <?php echo $venue_region; ?> <?php echo $venue_zip; ?></li>
<li><?php echo $venue_phone; ?></li>
</ul>
</div>
<div class="gs-clear"></div>
</div>
<? endforeach; ?>
</body>
Help?
Use a keyed foreach
foreach ($myfeed as $key => $goldstar):
And then unset the entire current xml using the key
unset($myfeed->$key);
Or unset just the venue with unset($myfeed->$key->venue);
Alternately, you could just build a new obj instead of trying to edit the existing one. Instantiate a new object before your loop and then only add the pieces to it that you want to keep.
Or, you can just continue the foreach if you find the unwanted venue. The only downside is that you won't have a copy of your ok'd list in $myfeed. So...
if ($venue_name == 'Hornblower Cruises and Events') { continue; }
Firstly you should cast every object that you are getting from your SimpleXML object to the relevant type. For example you should cast string attributes or nodes with putting (string) before reading the field:
$venue_name = (string)$goldstar->venue->name
For your question about filtering, I'd suggest your own way to keep looking for the match string and then decide to add or not.
EDIT
You're trying to see if the venue name is 'Hornblower Cruises and Events' then unset the current event field and echo it as XML? Firstly you should write unset($myfeed) because it's the event field itself. Next asxml would return nothing if you unset $myfeed. And you have HTML mistake in your code. In every loop of your for, you're writing:
<html>
<head></head>
<body>
You should place them before the for. And there is no closing tag for them. Put the closing tags after for. If you want to just get the fields with not venue name 'Hornblower Cruises and Events', put the <?php if($venue_name != 'Hornblower Cruises and Events') : ?> before <div class="gs-item"> and put <?php endif; ?> after </ul>.