The above query will not pull the information from the database - php

$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!

Related

Converting Query from forEach in a better solution

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.

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."%' ";

MYSQL query so it also returns values if has no value in the other table

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

php pdo where clause

I have the following code for selecting from multiple tables where the order number matches.
$orderNumber = $_GET['orderNumber'];
$sql = $db->prepare("
SELECT
*
from `KC_Orders`
INNER JOIN
`KC_Payments`
on KC_Orders.orderNumber = KC_Payments.orderNumber
INNER JOIN
`KC_OrderStatus`
on KC_Orders.orderNumber = KC_OrderStatus.orderNumber
INNER JOIN
`KC_Statuses`
on KC_OrderStatus.statusID = KC_Statuses.statusID
WHERE
orderNumber= :orderNumber");
$sql->execute(array(':orderNumber' => $orderNumber));
$orderInfo = $sql->fetchAll();
Now when I var_dump($orderInfo); it returns: array(0) { } What is wrong? All the tables include the same $orderNumber field within it. If I take the WHERE part out it works just fine except it returns every row not just one. (obviosly).
Please help us!
You need to specify what the OrderNumber is from, and the * is from (what table). So try this new code:
$sql = $db->prepare("SELECT KC_Orders.* from `KC_Orders` INNER JOIN `KC_Payments` on KC_Payments.orderNumber = KC_Orders.orderNumber INNER JOIN `KC_OrderStatus` on KC_OrderStatus.orderNumber = KC_Order.orderNumber INNER JOIN `KC_Statuses` on KC_Statuses.statusID = KC_OrderStatus.statusID WHERE KC_Orders.orderNumber= :orderNumber");
Ordernumber in where clause should have table prefix if it exists in multiple tables
Try this
$orderNumber = (int)$_GET['orderNumber'];
Then where :ordernumber is put $orderNumber
Then execute

add value to result from mysql query that will be JSON encoded in PHP?

I would like to add a value to each row that I get from my query depending on if a row exist in another table. Is there a smart way to achieve this?
This is the code I have:
$sth = mysql_query("SELECT tbl_subApp2Tag.*, tbl_tag.* FROM tbl_subApp2Tag LEFT JOIN tbl_tag ON tbl_subApp2Tag.tag_id = tbl_tag.id WHERE tbl_subApp2Tag.subApp_id = '".$sub."' ORDER BY tbl_tag.name ASC");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$query = "SELECT * FROM tbl_userDevice2Tag WHERE tag_id='".$r['id']."' AND userDevice_id='".$user."'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
$r['relation'] = true;
$rows[] = $r; //Add 'relation' => true to this row
} else {
$r['relation'] = false;
$rows[] = $r; //Add 'relation' => false to this row
}
}
print json_encode($rows);
Where the //Add ... is, is where I would like to insert the extra value. Any suggestions of how I can do this?
I'm still a beginner in PHP so if there are anything else that I have missed please tell me.
EDIT: Second query was from the wrong table. This is the correct one.
Edited Edited below query to reflect new information because I don't like leaving things half-done.
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_tag.*,
ISNULL(tbl_userDevice2Tag.userDevice_id) AS relation
FROM tbl_subApp2Tag
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDevice2Tag
ON tbl_userDevice2Tag.tag_id = tbl_tag.id
AND tbl_userDevice2Tag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = '".$sub."'
ORDER BY tbl_tag.name ASC
");
Though the above feels like the LEFT JOIN on tbl_tag is the wrong way around, but it's hard to tell as you are vague on your eventual aim. For example, if I was to assume the following
Tags will always exist
subApp2Tag will always exist
You want to know if a record in tbl_userDevice2Tag matches the above
Then I would do the following instead. The INNER JOIN means that it won't worry about records in tbl_tag that are not on the requested subApp_id which in turn will limit the other joins.
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_tag.*,
ISNULL(tbl_userDevice2Tag.userDevice_id) AS relation
FROM tbl_tag
INNER JOIN tbl_subApp2Tag
ON tbl_subApp2Tag.tag_id = tbl_tag.id
AND tbl_subApp2Tag.subApp_id = '".$sub."'
LEFT JOIN tbl_userDevice2Tag
ON tbl_userDevice2Tag.tag_id = tbl_tag.id
AND tbl_userDevice2Tag.userDevice_id = '".$user."'
ORDER BY tbl_tag.name ASC
");
you have to do all the job in a single query.
Why can't you just $r['append'] = "value"; before adding $r to the array?

Categories