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
}
}
Related
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.
$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!
Hi guys in the code below you can see what my JSON returns.
{"lifehacks":[{
"id":"2",
"URLtoImage":"http:\/\/images.visitcanberra.com.au\/images\/canberra_hero_image.jpg",
"title":"dit is nog een test",
"author":"1232123",
"score":"2",
"steps":"fdaddaadadafdaaddadaaddaadaaaaaaaaaaa","category":"Category_2"}]}
What the JSON returns is fine. The only problem is it is only displaying lifehacks if it has one like or more. So what should I change about my Query so it would display lifehacks without likes aswell.
//Select the Database
mysql_select_db("admin_nakeitez",$db);
//Replace * in the query with the column names.
$result = mysql_query("select idLifehack, urlToImage, title, Lifehack.Users_fbId, idLifehack, steps, Categorie, count(Lifehack_idLifehack) as likes from Lifehack, Likes where idLifehack = Lifehack_idLifehack AND idLifehack > " . $_GET["id"]. " group by idLifehack;", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['idLifehack'];
$row_array['URLtoImage'] = $row['urlToImage'];
$row_array['title'] = $row['title'];
$row_array['author'] = $row['Users_fbId'];
$row_array['score'] = $row['likes'];
$row_array['steps'] = $row['steps'];
$row_array['category'] = $row['Categorie'];
//push the values in the array
array_push($json_response,$row_array);
}
echo "{\"lifehacks\":";
echo json_encode($json_response);
echo "}";
//Close the database connection
fclose($db);
I hope my problem is clear like this. Thank you in advance I can't figure it out myself.
You need a LEFT JOIN here. Your query has an INNER JOIN.
select
idLifehack,
urlToImage,
title,
Lifehack.Users_fbId,
idLifehack,
steps,
Categorie,
count(Lifehack_idLifehack) as likes
from Lifehack
left join Likes on idLifehack = Lifehack_idLifehack
where idLifehack > whatever
group by idLifehack;
There's an excellent explanation of the different join types here.
A couple additional points...
Use prepared statements in your PHP. Your code is wide-open to SQL Injection, which has ruined careers and led to millions of innocent people having their personal information stolen. There are plenty of web sites showing how to do this so I won't go into it here, though I'll say my favorite is bobby-tables.
Avoid the implicit join anti-pattern in your queries. This is an implicit join:
FROM a, b
WHERE a.id = b.id
Use explicit joins instead; they separate your join logic from your filtering (WHERE) logic:
FROM a
INNER JOIN b ON a.id = b.id
I'm new to mysql.
I wanted to develop a simple tagging system for my blog and came across this "Toxi" Solution of making 3 tables.
So, I have 3 tables:
`blog` containing `id` and `title`.
`blog_tags` containing `id` and `tags_id` and `blog_id`.
`tags` containing `id` and `name`.
tags_id is connected to Internal Relation to id in tags table.
Similarly, blog_id is connected to Internal Relation to id in blog table.
So, when in my function (where I get the array of all tags pertaining to a single blog) I execute a query for example (passing blog id as the parameter in the function),
$result = mysql_query("SELECT tags_id FROM blog_tags WHERE blog_id = '".$id."'");
$tags = array();
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_assoc($result)) {
$tags[] = I don't know what should come over here?
}
return $tags;
Or is there any other way to execute queries in this Toxi implementation?
UPDATED You need a simple JOIN. Your query should look like
SELECT bt.tags_id, t.name
FROM blog_tags bt JOIN tags t
ON bt.tags_id = t.id
WHERE bt.blog_id = n -- < n is an id of a blog
Here is SQLFiddle demo.
Now php is pretty straightforward
$sql = "SELECT bt.tags_id, t.name
FROM blog_tags bt JOIN tags t
ON bt.tags_id = t.id
WHERE bt.blog_id = $id";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$tags = array();
while($row = mysql_fetch_assoc($result)) {
$tags[] = $row['name'];
}
...
On a side note: switch to PDO or mysqli. mysql_* extension is deprecated. In PDO you can use a syntactic sugar fetchAll(). And more importantly learn to use prepared statements. Right now your code is vulnerable to sql-injections.
I need your help with a small thing. I have two tables I need to get a list of the names and IDs of the people from the first table. Then use this list to get the services associated to these people.
Please keep in mind that I need both the name and ID to identify the service.
The query is similar to the following:
$query = "SELECT id, name from person where customerType='specificType';
$result = mysql_query($query,$this->connection);
After that I loop through the result of this query to get the services list:
While ($list=mysql_fetch_array($result))
{
$query = "SELECT serviceID, serviceName from services
where assignedToName='".$list['name']."' and assignedToID=".$list['id'];
$result2 = mysql_query($query,$this->connection);
if(!$result2 || mysql_num_rows($result2) <= 0)
{//I do nothing}
else{
if(isset($servicesList))
{
//Here is the part that is not working, How to combine the results??
$servicesList .= $result;
}
else $servicesList=$result;
}
}
//End While
if(isset($servicesList))
{ return $servicesList;}else {
return 'error';
}
Thanks in advance...
Please consider using a join and just one query.
Something like this:
SELECT
p.id,
p.name,
s.serviceID,
s.serviceName
FROM
person p
LEFT JOIN
services s
ON
(p.id = s.assignedToID
AND
p.name = s.assignedToName)
WHERE
p.customerType='specificType'