Converting Query from forEach in a better solution - php

foreach ($getComments as $comments) {
$comAuthor=$comments['uid'];
$getUser = $pdo->query("SELECT * FROM user WHERE uid = $comAuthor")->fetch();
$user = $getUser['name'];
$comContent=$comments['cdata'];
$comLikes=$comments['likes'];
echo "<div class='comment'><a href='profile?uid=$comAuthor'>$user</a><p>$comContent</p><likes>$comLikes</likes></div>";
}
I have been trying to get this query to work in a forEach cycle, but after I have done my research I found out it's impossible to run it more than once. I need help trying to get this to work. I am new to PHP and a lot of stuff is unfamiliar to me.

You can use INNER JOIN in the base query.
SELECT users.name, comments.cdata, comments.likes
FROM comments
INNER JOIN user ON comments.uid = user.uid
So in the foreach you already have the user name in the $comments variable.

Related

The above query will not pull the information from the database

$read = "SELECT * FROM elmtree
WHERE id ='$getid' AND
INNER JOIN elmtree_users ON elmtree.userid = elmtree_users.id";
The above query will not pull the information from the database to publish to the website.
Im trying to pull the item from the database with the $getid but also join the item id with the userid who uploaded it. Then using a while loop to print out the item to screen.
Any help would be greatly appreciated.
The SQL syntax you show isn't correct. A join clause describes which tables will be available for the rest of the query; all tables you mention need to be part of the ‘FROM’ clause, so that is where the ‘JOIN’ also belongs.
SELECT *
FROM elmtree
INNER JOIN elmtree_users ON elmtree.userid = elmtree_users.id
WHERE id ='$getid'
Your SQL query was not correctly written. The AND is not used in joining tables and the WHERE statement should be after the JOIN.
Try the following:
$read = "SELECT * FROM elmtree INNER JOIN elmtree_users ON(elmtree.userid = elmtree_users.id) WHERE elmtree.id ='$getid'";
UPDATE
Could you try the following in your code (replacing $this->database with your database variable) and post the result:
if ($result = $conn->query($read)) {
while ($row = $result->fetch_assoc()) {
...
}
} else {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
$read = "SELECT * FROM elmtree INNER JOIN elmtree_users ON(elmtree.userid = elmtree_users.id) WHERE elmtree.itemid ='$getid'
Big thanks to Omari Celestine to finding the answer to the problem!

Inserting SQL statement into PHP variable

Im trying to insert an SQL statment into a variable. The statement contains keywords entered by the user in a search bar. However, for some reason I can keep getting the error "Trying to get the property of non-object". Below is my code:
public function searchTable() {
$sql = "SELECT grades_eng.Grade, domain_math_eng.Domain, cluster_eng.Cluster, math_standards_eng.Standard FROM ".$this->standardsTable."
WHERE Standard LIKE '%".$this->keyword." %'
INNER JOIN grades_eng ON math_standards_eng.Grade_Id = grades_eng.Id
INNER JOIN domain_math_eng ON math_standards_eng.Domain_Math_Eng_Id = domain_math_eng.Id
INNER JOIN cluster_eng ON math_standards_eng.Cluster_Eng_Id = cluster_eng.Id";
$results = $this->conn->query($sql);
//returns array
return $results;
}
The code for the object being used:
$search = new SearchResult($conn, $subject, $keyword);
$queryResults = $search->searchTable();
$search->displayResults($queryResults);
Im confident is my sql query that's causing the error because when I use the following code, it displays results :
$sql = "SELECT * FROM ".$this->standardsTable." WHERE Standard LIKE '%".$this->keyword."%' ";
$results = $this->conn->query($sql);
Im Trying to display the same results but replace the IDs with actual text. The query does work when I run it in MySql.
P.S Still working on learning to use Aliases so I apologize in advance.
I just learned that the "Where" keyword was suppose to go towards the end. Lesson learned!
$sql = "SELECT grades_eng.Grade, domain_math_eng.Domain, cluster_eng.Cluster, math_standards_eng.Standard FROM ".$this->standardsTable."
INNER JOIN grades_eng ON math_standards_eng.Grade_Id = grades_eng.Id
INNER JOIN domain_math_eng ON math_standards_eng.Domain_Math_Eng_Id = domain_math_eng.Id
INNER JOIN cluster_eng ON math_standards_eng.Cluster_Eng_Id = cluster_eng.Id
WHERE Standard LIKE '%".$this->keyword."%' ";

How i can compare the result in one query or two?

I am trying to fetch last 10 topics from smf database but topics are in two separate tables.
Subject, Post Time and Message ID in smf_messages.
Topic ID and Topic First Message in smf_topics.
I wrote this code to fetch topics but i dont know how to compare these two results.
$result = mysql_query("select subject,id_msg,id_topic from smf_messages");
$result2= mysql_query("select id_first_msg from smf_topics");
if(mysql_num_rows($result)!=0)
{
while($read = mysql_fetch_object($result))
{
if ($read->id_msg==$read->id_topic) {
echo "<a href='../index.php?topic=" . $read->id_topic . "'>".$read->subject."</a><br>";
}
}
You probably want the following query
select subject, id_msg, id_topic, id_first_msg
from smf_messages
left join smf_topics on smf_message.id_msg = smf_topics.id_first_msg
bind the records by joining in sql:
select subject id_msg, id_topic, id_first_msg from smf_messages
join smf_topics on smf_messages.id_msg = smf_topics.id_topic
mysql have many many options, with a small google search you could found about left join.
tuttorial and examples.
Fist thing you have to do is stop using mysql_* and start using mysqli_* or pdo learn about sql injections
Your query should look like this.
select smf_messages.subject,smf_messages.id_msg,smf_messages.id_topic from smf_messages left join smf_topics on smf_topics.id_first_msg=smf_messages.id_msg
If you want to do that without using SQL, this is my solution it's not good but you can have an idea of how it works:
$messages = array();
$topics = array();
while($readmessage = mysql_fetch_object($resultmessage)) {
array_push($messages, $readmessage);
}
while($readtopic = mysql_fetch_object($resulttopic)) {
array_push($topics, $readtopic);
}
foreach ($topics as $topic) {
$result = array_search($topic->id_first_message);
if($result != true){
//HERE $result IS THE INDEX OF FIRST MESSAGE IF IT IS IN THE MESSAGES ARRAY
$messages[$result].id_msg //Access message attributes
}
}

SQL-Query PHP -Blog

I am sure that somewhere in the web this question has been already asked but i have not found it, because i don't know for what exactly i should search. So i will try to describe the problem:
I have a Blog written in PHP and a SQL-database, where i receive the needed data.
Each Blog entry contains 1 image and 1 text-field and has its own id.
To get this data i execute this query (pseudo-code) -> this is working fine:
foreach($db->query("SELECT news.id, news.position, news_text.date, news_text.text, news_images.image
FROM news
LEFT OUTER JOIN news_text ON news.id=news_text.id
LEFT OUTER JOIN news_images ON news_images.id = news.id
ORDER BY position") as $row){
echo "{$row['id']}";
echo "{$row['position']}";
echo "{$row['date']}";
echo "{$row['text']}";
echo "{$row['image']}";
}
Now the problem starts. I want to add a comment field, where users can add a message. So for each blog-entry there can be several comments (would probably be a 1:n connection).
- I tried to add a foreach loop in a foreach loop (stupid)
- I tried with several SQL-query but only get rubbish as a result
- I don't see the logic how to connect the database news_comment with the others
Here is my simplified database:
Can someone give me a hint how i could solve this problem. Result should be:
foreach($db->query("SELECT news.id, news.position, news_text.date, news_text.text, news_images.image
FROM news
LEFT OUTER JOIN news_text ON news.id=news_text.id
LEFT OUTER JOIN news_images ON news_images.id = news.id
ORDER BY position") as $row){
echo "{$row['id']}";
echo "{$row['position']}";
echo "{$row['date']}";
echo "{$row['text']}";
echo "{$row['image']}";
Here i get for each blog-entry the corresponding comments..
}
Thank you.
Misch
You should retrieve comments in another one query (not in loop) using the same conditions as for retrieving news. So that after executing both queries you will have to arrays: news and comments.
Then you just need to take appropriate comments for each news item.
To do that you might need to rebuild comments array so that comment news_id will be an index of array where comments are stored.
Finally it'd look like this:
$news = [
[
'id' => ...,
'position' => ...
<so on>
]
];
$comments = [
$news[0]['id'] = [<comment array>],
<so on>
];
That's the way most framework use to have data bound in result set.
Solved it with the help of Alex(thx) and MulipleIterator. This is how it worked for me (maybe someone has a better solution).
foreach($db->query("SELECT news.id, news.position, news_text.date, news_text.text, news_images.image
FROM news
LEFT OUTER JOIN news_text ON news.id=news_text.id
LEFT OUTER JOIN news_images ON news_images.id = news.id
ORDER BY position") as $row)
{
$news_id[] = $row['id'];
$news_text[] = $row['news_text'];
$news_images[] = $row['news_images'];
$values = new MultipleIterator();
$values->attachIterator(new ArrayIterator($news_id));
$values->attachIterator(new ArrayIterator($news_text));
$values->attachIterator(new ArrayIterator($news_images));
}
foreach($values as $value)
{
list($news_text, $news_images, $news_id) = $value;
{
echo '$news_text';
echo '$news_images';
foreach($db->query("SELECT comment FROM news_comment WHERE id = $news_id ") as $row)
{
echo "{$row['comment']}";
}
}
}

PHP: Loop over a grouped SQL query array but echo one value once for each “grouping”?

I’ve a small piece of code I’ve tried to wrap my brain around for some hours now.
I’m trying to create a query which retrieves some elements and in the end group them by a selector.
I’ll try to demonstrate: I’m querying all the members in my organization. Each member is a member of a “department” and there can be several members in each department, but only one department for each member.
So I’ve created the query to select all members in my organization group by departments.
When I’m displaying it using a simple foreach($my_query as $q) … I want to output $q->department_name but only once for that department. Right now it says “Marketing” under all five members and then it changes to “HR” for all those members. I’ve tried some different methods such as array_unique, creating a function that checks for the string to see if it is the same and other but with no result.
I could create two foreach loops but if it is at all possible not to I would prefer that because two foreach loops would affect the performance.
Any help or suggestion would be very much appreciated.
Sinerely
- Mestika
--- Edited ---
By the way, my query looks like this:
SELECT *
FROM wp_term_taxonomy AS cat_term_taxonomy
INNER JOIN wp_terms AS cat_terms ON cat_term_taxonomy.term_id = cat_terms.term_id
INNER JOIN wp_term_relationships AS cat_term_relationships ON cat_term_taxonomy.term_taxonomy_id = cat_term_relationships.term_taxonomy_id
INNER JOIN wp_posts AS cat_posts ON cat_term_relationships.object_id = cat_posts.ID
INNER JOIN wp_postmeta AS meta ON cat_posts.ID = meta.post_id
WHERE cat_posts.post_status = 'publish'
AND meta.meta_key = 'active'
AND meta.meta_value = 'active'
AND cat_posts.post_type = 'member'
AND cat_term_taxonomy.taxonomy = 'deparment'
GROUP BY cat_terms.slug, cat_term_relationships.object_id
$prev_department = NULL;
foreach ($my_query AS $q)
{
if ($prev_department != $q->department_name)
echo '<h2>'. htmlentities($q->department_name, ENT_COMPAT, 'UTF-8') .'</h2>';
// ...
$prev_department = $q->department_name;
}

Categories