PHP Array with only unique values - php

I am a beginner in coding and am trying to understand and adjust the below code to return only unique values without repetition from the database. I have tried different variations of unique_array() but without success unfortunately. How can I limit the values returned from the database to only unique ones?
<?php
$sql ="SELECT COUNT( status) AS total_building FROM add_bulding WHERE status=1";
$query = $this->db->query($sql);
$total_building = $query->row_array();
?>
<div class="b-list-section">
<?php
if(!empty($building_info))
{
foreach ($building_info as $value)
{
$id = $value['id'];
$sql = "SELECT COUNT(DISTINCT building_id) AS total_list FROM add_listing WHERE building_id='$id'";
$query = $this->db->query($sql);
$total_list = $query->row_array();
?>
<a class="blink" target="_blank" href="<?php echo base_url() . 'details_building/' . $value['id'] ?>">
<div class="bilding-wrap">
<h3 class="buildingtitle"><?php echo $value['title']; ?></h3>
<?php if(!empty($value['image'])):?>
<img class="bimage" src="<?php echo base_url("uploads/thumb/" . $value['image']); ?>" alt="no image yet">
<?php else:?>
<?php $qry12=mysql_query("SELECT * FROM add_bulding_image WHERE add_building_id=$id");
$sqr1=mysql_fetch_array($qry12); ?>
<img class="bimage" src="<?php echo base_url("uploads/thumb/" . $sqr1['image']); ?>" alt="no image yet">
<?php endif;?>
</div>
</a>
The above code returns listings that match what a user is searching for. Since 2 listings can be in the same building, the code is returning the same building twice.

Try to change your query to this:
SELECT COUNT(building_id) AS total_list FROM add_listing WHERE building_id='$id' GROUP BY building_id

Related

How to loop within a for loop to get multiple values with the same ID

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.

Displaying fields in a unique php page for each row in myql Wordpress Database

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

Correct PHP loop to display post categories

I have two tables “categories” and “posts”, I’m trying to create a category.php page that displays the different categories with post titles as links to the original posts. I’ve tried different variations of loops but can’t seem to get it right. I’m hoping someone could point me in the right direction.
$query = "SELECT post_id, title, body, category_id, posted
FROM posts
INNER JOIN categories ON categories.category_id = posts.category_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){
<a href='index.php?id=<?php echo $post['post_id']; ?>' ><?php echo $post['title']; ?></a></h2>
<p>
Posted on <?php echo date('d-m-y h:i:s',strtotime($post['date_posted'])); ?>
In <a href='category.php?id=<?php echo $post['category_id']; ?>' ><?php echo $post['name']; ?></a>
</p>
echo "<hr />";
}
Thank you for any input
Forgive my syntax (it may be off a bit), but this should give you a good idea:
$categories = array(
'sports' => array(
post1,
post2,
),
'weather' => array(
post1,
post2,
),
);
Get all of your categories first, then loop through each and get all the posts related to that category. Then you can loop through the array normally like:
foreach($categories as $category){
//display category title
foreach($category['posts'] as $post){
//display post info
}
}
You have some issues in your code.
Modified code:
$query = "SELECT post_id, title, body, category_id, posted FROM posts INNER JOIN categories ON categories.category_id = posts.category_id";
$result = mysqli_query($dbc, $query) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){
?>
<a href="index.php?id=<?php echo $row['post_id']; ?>" >
<?php echo $row['title']; ?></a></h2> <p>
Posted on
<?php
echo date('d-m-y h:i:s',strtotime($row['date_posted']));
?>
In
<a href="category.php?id=<?php echo $row['category_id']; ?>">
<?php
echo $row['name'];
?></a> </p>
<hr />
<?php } ?>
Issues:
array index using with single quote inside the single quote.
wrong variable using post.
html tags inside the php
You are using a variable called $post inside your while loop, but you are retrieving each row in that while loop into a variable called $row.
Fix that and many of your issues will disappear.
You also need to stop and start the PHP interpreter when you want to output HTML in the way that you have done here, note the ?> and <?php I addded
$query = "SELECT post_id, title, body, category_id, posted
FROM posts
INNER JOIN categories ON categories.category_id = posts.category_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
// change this to use a variable called $post
while ($post = mysqli_fetch_array($result)){
?>
<a href='index.php?id=<?php echo $post['post_id']; ?>' ><?php echo $post['title']; ?></a>
<!-- Dont think this should be here -->
</h2>
<p>Posted on <?php echo date('d-m-y h:i:s',strtotime( $post['date_posted'] ) );?>In <a href='category.php?id=<?php echo $post['category_id']; ?>' ><?php echo $post['name']; ?></a>
</p>
<?php
echo "<hr />";
}
?>
There is HTML code inside <?php ?> try this :
<?php $query = "SELECT post_id, title, body, category_id, posted
FROM posts
INNER JOIN categories ON categories.category_id = posts.category_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){ ?>
<a href='index.php?id=<?php echo $post['post_id']; ?>' ><?php echo $post['title']; ?></a></h2>
<p>
Posted on <?php echo date('d-m-y h:i:s',strtotime($post['date_posted'])); ?>
In <a href='category.php?id=<?php echo $post['category_id']; ?>' ><?php echo $post['name']; ?></a>
</p>
echo "<hr />";
<?php } ?>

Images not visible in search results

I have this custom search function to search trough custom meta keys in Wordpress. The function works well.
However, all the images that I have added to my post using Advanced Custom Fields are now having their URL's changed to the attachment ID.
This should not happen according to the settings page in ACF:
The same field works ok on other pages, just not on the search results page. Check how it changes the image source on the search results:
How and why is the image URL here changed to the attachment ID? Kindly check out my code below:
function custom_search_function($pieces) {
// filter to select search query
if (is_search() && !is_admin()) {
global $wpdb;
$custom_fields = array('regio','provincie');
$keywords = explode(' ', get_query_var('s'));
$query = "";
foreach ($custom_fields as $field) {
foreach ($keywords as $word) {
$query .= "((mypm1.meta_key = '".$field."')";
$query .= " AND (mypm1.meta_value LIKE '%{$word}%')) OR ";
}
}
if (!empty($query)) {
// add to where clause
$pieces['where'] = str_replace("((({$wpdb->posts}.post_title LIKE '%", "( {$query} (({$wpdb->posts}.post_title LIKE '%", $pieces['where']);
$pieces['join'] = $pieces['join'] . " INNER JOIN {$wpdb->postmeta} AS mypm1 ON ({$wpdb->posts}.ID = mypm1.post_id)";
//$pieces['groupby'] = "{$wpdb->posts}.ID";
}
}
return ($pieces);
}
add_filter('posts_clauses', 'custom_search_function', 20, 1);
EDIT: Here's the code that displays my post results, the "foto" field is the field which is responsible for displaying the image:
<?php foreach( $posts as $post ):
//fusion-column-last, or none for normal class
$lastclass = '';
if(++$counter % 2 === 0) {
$lastclass = ' fusion-column-last';
}
setup_postdata( $post )
?>
<div class="fusion-one-half fusion-layout-column fusion-spacing-yes<?php echo $lastclass?>" style="margin-top:0px;margin-bottom:20px;background-color:white;">
<div class="fusion-column-wrapper">
<div class="bw-search-picture">
<?php $postid = get_the_ID(); ?>
<?php //echo $postid; ?>
<img src="<?php the_field('foto', $postid); ?>" alt="<?php the_title(); ?>"/>
</div>
<div class="bw-search-content">
<h2>
<a class="green" href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</h2>
<p class="bw-regio">Regio <?php the_field('regio'); ?></p>
<p>
<a style="color:#9C9E9F;" href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">LEES VERDER ></a>
</p>
</div>
</div>
</div>
<?php endforeach; ?>
Try for the thumbnail:
$imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id( $post_id ));
echo $imgsrc[0];
Edit, use this code with the attachment id:
$imgsrc = wp_get_attachment_image_src(get_field('foto', $postid));
echo $imgsrc[0];
Rather than using
<img src="<?php the_field('foto', $postid); ?>" />
Try using
<?php $foto_url = get_field('foto', $postid); ?>
<img src="<?php echo $foto_url; ?>" />

MySQL query doesn't show all the records correctly

The query am running against my database to get the 3 records order it by Random. The problem is that sometimes it shows all 3 records sometimes it only shows 2, 1 and other times its just blank. In the database I have around 28 records.
What I have tried
I have tried without LIMIT - Problem Same
I have echoed out $suggested_profile_id found all 3 records coming out.
This is the query that gets the records LIMIT it by 3
<?php
$sql = "SELECT * FROM members WHERE member_status='activated' ORDER BY RAND() DESC LIMIT 3";
$query = $db->SELECT($sql);
if($db->NUM_ROWS() > 0){
$rows = $db->FETCH_OBJECT();
?>
This is the code that runs and gets all 3 records in a loop.
<!-- Suggested Friends -->
<div class="col-md-0 media-body">
<?php
foreach($rows as $row){
$member_id = $row->member_id;
$sql = "SELECT * FROM profile WHERE profile_id='$member_id' LIMIT 1";
$query = $db->SELECT($sql);
$rows = $db->FETCH_OBJECT();
foreach($rows as $row){
$suggested_profile_id = $row->profile_id;
$suggested_profile_photo = $row->profile_photo;
$suggested_profile_username = $row->profile_username;
$suggested_profile_name = $row->profile_name;
if(
$suggested_profile_id != GET_SESSION_ID_VALUE(ENCRYPTION_KEY)&&
!is_in_ARRAY($make_string_to_ARRAY, $suggested_profile_id)
){
?>
<div class="row margin0">
<div class="col-md-4 pad0">
<a href="/<?php echo $suggested_profile_username; ?>" title="<?php echo $suggested_friends_profile_name; ?>" >
<?php
global $suggested_friends_profile_id;
$member_dir = dirname(dirname(dirname(__FILE__))) . "/members/" . $suggested_profile_id ."/smalll_" . $suggested_profile_photo;
if(file_exists($member_dir)){
?>
<img alt="<?php echo $suggested_profile_name; ?>" title="<?php echo $suggested_profile_name; ?>" src="/members/<?php echo $suggested_profile_id; ?>/smalll_<?php echo $suggested_profile_photo; ?>" width="50" height="50">
<?php
} else {
?>
<img alt="<?php echo $suggested_profile_name; ?>" title="<?php echo $suggested_profile_name; ?>" src="/assets/images/default.jpg" width="50" height="50">
<?php
}
?>
</a>
</div>
<div class="col-md-8 pad0">
<?php echo $suggested_profile_name; ?>
<span class="f12 gray">271 Mutual Friends</span>
Add as friend
</div>
</div>
<?php
}
}
}
?>
</div>
<!-- ** Suggested Friends -->
What am I missing? Is there any alternative way I can achieve this...thanks!
It looks to me like you're overwriting your $rows variable within the inner select.
foreach($rows as $row){ // <-- first $rows / $row
$member_id = $row->member_id;
$sql = "SELECT * FROM profile WHERE profile_id='$member_id' LIMIT 1";
$query = $db->SELECT($sql);
$rows = $db->FETCH_OBJECT(); <-- $rows overwritten
foreach($rows as $row){
Break your display from your application logic and you won't have such a hard time debugging this kind of thing. Besides, you have a lot of duplicated code and that makes things hard to manage as well as being hard to debug.
Further, you wouldn't have this problem if you ran one query: SELECT * FROM members JOIN profile ON members.member_id = profile.profile_id and not only does your code get simpler and your double-foreach loop problem disappear, but your database access will also be a lot more efficient.

Categories