Fetching results from database in PDO - php

I developed a simple upload photo and comment system. When I use for each, it repeats the image. E.g If there are 5 comments on a photo. It repeats the photo 5 times with the 5 different comments. Instead of one image for 5 comments.
I want 1 image with each comments. How do I get all the comments for each photo without repeating the photo?
I use PDO and here is the php code:
<?php
//This is for the images
$results = $connecDB->prepare("select image,caption,id from gallery order by id desc LIMIT $start, $limit ");
$results->execute();
$results = $results->fetchAll();
foreach($results as $results) {
$pid=$results["id"];
//This is for the comments
$re= $connecDB->prepare("select * from comments where pid = :pid order by id");
$re->bindParam(':pid', $pid);
$re->execute();
foreach($re as $re) {
$name=$re["name"];
$comment=$re["comment"];
?>
<div class="item" id="item-<?php echo $results['id']?>">
<p><img src="../upload/images/<?php echo $results['image']?>" height="500px" width="500px"</p>
<p><?php echo $results['caption']?></p>
<div class="large-2 columns small-3"><font color="#3366ff"><?php echo $name?></font></div>
<div class="large-10 columns"><p><?php echo $comment?></p></div>
<?php}
}?>
Thanks.

You were looping everything inside inner loop, try like this.
<?php
//This is for the images
$results = $connecDB->prepare("select image,caption,id from gallery order by id desc LIMIT $start, $limit ");
$results->execute();
$results = $results->fetchAll();
foreach($results as $results) {
$pid=$results["id"];
?>
<div class="item" id="item-<?php echo $results['id']?>">
<p><img src="../upload/images/<?php echo $results['image']?>" height="500px" width="500px" /></p>
<p><?php echo $results['caption']?></p>
<?php
//This is for the comments
$re= $connecDB->prepare("select * from comments where pid = :pid order by id");
$re->bindParam(':pid', $pid);
$re->execute();
foreach($re as $re) {
$name=$re["name"];
$comment=$re["comment"];
?>
<div class="large-2 columns small-3"><font color="#3366ff"><?php echo $name?></font></div>
<div class="large-10 columns"><p><?php echo $comment?></p></div>
<?php}?>
</div>
<?php}?>

Actually you are not getting the result in $re variable. You need to fetchAll data after executing the query. As well as you were looping everything in inner foreach.
foreach($results as $results) {
$pid=$results["id"];
//This is for the comments
$re= $connecDB->prepare("select * from comments where pid = :pid order by id");
$re->bindParam(':pid', $pid);
$re->execute();
$comments = $re->fetchAll();
<div class="item" id="item-<?php echo $results['id']?>">
<p><img src="../upload/images/<?php echo $results['image']?>" height="500px" width="500px"</p>
<p><?php echo $results['caption']?></p>
<div class="large-2 columns small-3"><font color="#3366ff"><?php echo $name?></font></div>
foreach($comments as $re) {
$name=$re["name"];
$comment=$re["comment"];
?>
<div class="large-10 columns"><p><?php echo $comment; ?></p></div>
<?php}
}?>

Related

How can I get the information from one field in a query to use in another query?

I am still trying to finish fixing my details page and I need one more piece to fix it.
I start with this query.
NOTE:recordID actually comes in from the previous page by clicking an item.
Also, name, img, item_code, and type_id are fields in my table not outside sources.
$recordID = $_GET['recordID'];
$query_master_details = "SELECT * FROM master_list WHERE master_list.master_id = $recordID";
$master_details = mysqli_query($conn, $query_master_details) or die(mysqli_error());
$row_master_details = mysqli_fetch_assoc($master_details);
$totalrows_master_details = mysqli_num_rows($master_details);
Now, I have created this to determine how to display the details about said item:
<div class="container2">
<div class="category"><h2><?php echo $row_master_details['name']; ?></h2></div>
<?php
$crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3 AND `length` = $row_master_details.length ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $crafted);
$crafted = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$crafted[] = $row;
}
}
if ($row_master_details['type_id'] > 3) {?>
<p><strong>Code 1</strong></p>
<p><?php echo $crafted['name']; ?></p>
<p><img src="img/<?php echo $crafted['img']; ?>" /></p>
<p><?php echo $crafted['item_code']; ?></p>
<br><br>
<p><strong>Code 2</strong></p>
<p><?php echo $row_master_details['name']; ?></p>
<p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
<p><?php echo $row_master_details['item_code']; ?></p>
<p><?php echo $row_master_details['length']; ?> Characters</p>
<?php }else { ?>
<p><?php echo $row_master_details['name']; ?></p>
<p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
<p><?php echo $row_master_details['item_code']; ?></p>
<p><?php echo $row_master_details['length']; ?> Characters</p>
<?php
mysqli_free_result($master_details);
?>
<?php } ?>
<!-- end .container2 --></div>
To explain what is happening here:
This looks at the item that was clicked on the previous page and finds the information about it.
If it has a type_id of 4 or higher, I need it to do the following:
Look at the "length" of the current item.
Select all the items from the master_list that has a type_id of 1, 2, or 3 and a matching length to the first one.
Choose 1 random match.
Output the "name, img, and item_code in the same fashion as the first one.
If the item selected originally has a type_id of less than 4, it just posts the original information. This part works. The part from the second query does not.
I have a feeling I need another $_GET[], but not exactly sure how to go about it. The recordID get was attached to the image used as a link.
Can anyone help me to query this so that I get what I am wanting?
Here is a pic of what I am trying to do to help make more sense:
This was done by manually choosing the item to match and putting them together. I want a random item to display.
Here is what the current code looks like. This is the same thing I get with MiK's answer:
I finally managed to fix this issue with a combination of tweaking and the answer from MiK.
Here is the final code I ended up with:
<div class="container2">
<div class="category"><h2><?php echo $row_master_details['name']; ?></h2></div>
<?php
$crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3 AND `length` = ". $row_master_details['length']." ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $crafted);
$citem = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$citem[] = $row;
}
}
if ($row_master_details['type_id'] > 3) {?>
<p><strong>Code 1</strong></p>
<p><?php echo $citem[0]['name']; ?></p>
<p><img src="img/<?php echo $citem[0]['img']; ?>" /></p>
<p><?php echo $citem[0]['item_code']; ?></p>
<br><br>
<p><strong>Code 2</strong></p>
<p><?php echo $row_master_details['name']; ?></p>
<p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
<p><?php echo $row_master_details['item_code']; ?></p>
<p><?php echo $row_master_details['length']; ?> Characters</p>
<?php }else { ?>
<p><?php echo $row_master_details['name']; ?></p>
<p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
<p><?php echo $row_master_details['item_code']; ?></p>
<p><?php echo $row_master_details['length']; ?> Characters</p>
<?php
mysqli_free_result($master_details);
?>
<?php } ?>
<p><h4>(Need a different crafted item? Refresh the page!)</h4></p>
<!-- end .container2 --></div>
The answer provided by MiK fixed the query, but the results were not showing because I had an array inside the array and had to call the inner array. Also, I had to fix the array name so it wasn't the same as the query.
select
ml1.master_id, ml1.`name`,ml1.item_code,ml1.img,ml1.length,ml1.type_id,
IF(ml1.type_id > 3,ml2.master_id,null) as craft_master_id,
IF(ml1.type_id > 3,ml2.`name`,null) as craft_name,
IF(ml1.type_id > 3,ml2.item_code,null) as craft_item_code,
IF(ml1.type_id > 3,ml2.img,null) as craft_img,
IF(ml1.type_id > 3,ml2.length,null) as craft_length,
IF(ml1.type_id > 3,ml2.type_id,null) as craft_type_id
from
(select * from master_list where master_id = 4) ml1
JOIN
(select * from master_list) ml2
ON ml1.length = ml2.length
ORDER BY RAND() LIMIT 1;
This query will give exactly what you need. Not required two query to run.
no need to add if else. use only on block. in code.Where you have to add crafted it just add if(craft_master_id) then only display that block else dont show.
Instead of
$crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3
AND `length` = $row_master_details.length ORDER BY RAND() LIMIT 1";
try
$crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3
AND `length` = ".$row_master_details['length']." ORDER BY RAND() LIMIT 1";
Your query fails to find a matching thing since it will match against the string "Arraylength" instead of the actual value.

php and mysql to create tabs with bootstrap 3

enter image description here
How can I make a loop with php where I separate the comments as rounds
All comments for the round 1
<div id="$row['round']">
$row['comments']
</div>
All comments for the round 2
<div id="$row['round']">
$row['comments']
</div>
but I can have many rounds, so I don't know the exact query to use
<div id="chat" class="chat">
<ul class="nav nav-tabs">
<?php
$stmt = $DB->query("SELECT * FROM messages WHERE $id = video_id GROUP BY round ORDER BY round DESC");
while ($row = $stmt->fetch()) {
echo '<li><a data-toggle="tab" href="#menu'.$row['round'].'">'.$row['round'].'</a></li>';
}
?>
</ul>
<div class="tab-content">
<?php
$i=-1;
$stmt = $DB->query("SELECT * FROM messages WHERE $id = video_id GROUP BY round ORDER BY round DESC");
while ($row = $stmt->fetch()) {
echo '<div class="tab-pane '.( $i = $i ? 'active' : '' ).'" id="menu'.$row['round'].'">';
$test = $row['round'];
$stmt2 = $DB->query("SELECT * FROM messages INNER JOIN system_users ON messages.user_id = u_userid WHERE $id = video_id AND $test = round ORDER BY date ASC");
while ($row2 = $stmt2->fetch()) { ?>
<br />
<p><b>round:</b> <?php echo $row2["round"]; ?></p>
<p><b>Message:</b> <?php echo $row2["message"]; ?></p>
<p><b>User:</b> <?php echo $row2["u_username"]; ?></p>
<p><b>time:</b> <?php echo date_format (new DateTime($row2["date"]), 'd|m|Y H:i:s'); ?></p>
<hr />
<?php
}$i =0;
echo '</div>';
}
?>
</div>
I am completely sure this is not the best solution, but it is working,
thanks anyway..

PHP Show foreach() results from 2 SQLite-arrays, one as random

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];
}
?>

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.

Output of the table in div class

$resultSet = mysql_query("SELECT * FROM news ORDER BY id DESC LIMIT 7");
$product_count = mysql_num_rows($resultSet);
if($product_count >0){
while( mysql_fetch_array($resultSet)){
$id= $row["id"];
$cat= $row["categories"];
$title= $row["title"];
$image= $row["image"];
$txt= $row["txt"];
$res= $row["resource"];
}
}
else
{ echo'site is under maintaince ';}
echo " <div class=\"row-fluid\">
<div class=\"span6 post no-margin-left\">
<figure>
<img src=\"$image\" alt=\"Thumbnail 1\" />
<div class=\"cat-name\">
<span class=\"base\">'$cat'</span>
<span class=\"arrow\"></span>
</div>
</figure>
<div class=\"text\">
<h2>'$title'</h2>
<p>$txt</p>
<div class=\"meta\">By ' $res' | '$date' | 15 comments</div>
</div>
</div>
</div>";
?>
The code is not showing the output results of the table. Can you tell me what I am doing wrong? I want to show the output in the div class. My paging is working correctly, but it is not showing the output correctly. Can you guide me? I will really be grateful.
while( mysql_fetch_array($resultSet)){
$id= $row["id"];
$cat= $row["categories"];
$title= $row["title"];
$image= $row["image"];
$txt= $row["txt"];
$res= $row["resource"];
}
}
Where is $row in the lopp? However, to populate all the results, you need the printing inside the loop, otherwise you won't get them iterated

Categories