Inserting SQL statement into PHP variable - php

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

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.

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!

Having trouble using inner join sql command with Joomla query

I am attempting to use inner join to select the stop date of a user's subscription. Here is the code sample:
Global $_CB_framework;
$myId = $_CB_framework->myId();
$db = JFactory::getDbo();
$stopDateQuery = $db->getQuery(true);
$stopDateQuery->select($db->quoteName(array('#__cbsubs_subscriptions.user_id', '#__cbsubs_payment_items.subscription_id', '#__cbsubs_payment_items.stop_date')));
$stopDateQuery->from($db->quoteName('#__cbsubs_subscriptions'));
$stopDateQuery->innerJoin($db->quoteName('#__cbsubs_payment_items' ON '#__cbsubs_subscriptions.id'='#__cbsubs_payment_items.subscription_id'));
$stopDateQuery->where($db->quoteName('#__cbsubs_subscriptions.user_id')." = ".$db->quote($myId));
$db->setQuery($stopDateQuery);
$stopDateQueryResults = $db->loadRow();
$stopDate = $stopDateQueryResults['2'];
echo 'stop Date:'.$stopDate;
I have run the statement directly into phpMyAdmin and the table will join with no problem. I am sure that it has something to do with my formatting of the statement. Any suggestions?
The innerJoin line has syntax errors. Change to:
$stopDateQuery->innerJoin($db->quoteName('#__cbsubs_payment_items') . ' ON #__cbsubs_subscriptions.id = #__cbsubs_payment_items.subscription_id');
innerJoin() takes a string which should be in the format of an SQL join without the join type. for example:
$obj->innerJoin('table_a on table_a.id = table_b.id');

Use PHP variables in MySQL Query with LIKE '%%'

I'm building a search function for my site, however the MySQl query won't read the PHP variables, and I don't mean errors, it just seems to think they're NULL.
My current code is:
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
$sql = "SELECT * FROM Books";
if($_POST['find']!="")
{
if($_POST['field'] == "Books")
{
$sql = "SELECT *
FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
WHERE books.BookName LIKE '%''".($_POST['find'])."''%'
GROUP BY books.BookName
ORDER BY authors.AuthorID";
}
else if ($_POST['field'] == "Authors")
{
$sql = "SELECT *
FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
WHERE authors.Forename LIKE '%J.%'
AND authors.Surname LIKE '%%'
GROUP BY books.BookName
ORDER BY authors.AuthorID";
}
}
$result = mysql_query($sql, $conn) or die("Can't run query");
$loopnumber = 1;
if (mysql_num_rows($result) ==0 ){echo "No Results have been found";}
The POST variable does contain data as I've tested by echo'ing it, however my site just gives the "No Results have been found" message meaning the query retuned no results.
Even if I pass the POST into a normal variable I get the same results.
However if I remove the "LIKE '%%'" and have it look for and exact match from typing in the search on the site it works fine.
Edit: Hmmmm, just made it so I pass the POST into a variable like so..
$searchf = "%".$_POST['find']."%";
and having that variable in the WHERE LIKE makes it work, now I'm just curious as to why it doesn't work the other way.
I seems to love quotation marks too much, and should go to bed.
Well first of all, I am guessing you are getting a MySQL syntax error when trying to execute that first query. This line:
WHERE books.BookName LIKE '%''".($_POST['find'])."''%'
Should be
WHERE books.BookName LIKE '%".$_POST['find']."%'
Because right now you are getting
WHERE books.BookName LIKE '%''ABC''%'
when you should be getting
WHERE books.BookName LIKE '%ABC%'
I don't admit to understand what you are doing with your second query, which just hard codes and has %% as one of the search criteria, which is, in essence meaningless.
Its in your LIKE expression. If in $_POST['find'] the value is LOTR the query would be
WHERE books.BookName LIKE '%''LOTR''%'
and the resault would be empty. Just remove the double ' and it should be work.
Try this way:
$sql = "SELECT *
FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
WHERE books.BookName LIKE '%".$_POST['find']."%'
GROUP BY books.BookName
ORDER BY authors.AuthorID";
It should be work
use this, worked for me:
$query_casenumber = "SELECT * FROM pv_metrics WHERE casenumber='$keyword' OR age='$keyword' OR product='$keyword' OR eventpreferredterm='$keyword' OR patientoutcome='$keyword' OR eventsystemclassSOC='$keyword' OR asdeterminedlistedness='$keyword' OR narrative LIKE '%".$_POST['keyword']."%' ";

Query error MySQL php

Im new to php and my sql in trying to get all the results from this table if nothing is selected but for some reason its always displaying one result. Any ide why
$query = "SELECT *, ROUND(AVG(d.rating),0) FROM restaurant AS r, review AS d WHERE 1=1 ";
if($vicinity) $query .= "AND r.vicinity=\"$vicinity\" ";
if($cuisine) $query .= "AND r.cuisine=\"$cuisine\" ";
if($price) $query .= "AND r.price=\"$price\"";
if($name) $query .= "AND r.name LIKE \"%$name%\"";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
and im only getting the first item on the table
I would look into PDO personally. You can find out a lot about it in the manual here.
guessing you're only getting one result because the avg call without a group by is triggering some interesting behavior. try adding a group by, and i'm guessing you also want to associate the restaurants and reviews with a join. eg:
$query = "SELECT *, ROUND(AVG(d.rating),0) FROM restaurant AS r LEFT JOIN review AS d on r.id = d.restaurant_id WHERE 1=1";
...
...
$query .= ' GROUP BY r.id';
$result = mysql_query($query);
per the thread, sounds like you should look into prepared statements as well :). and the SELECT * should probably also just be SELECT r.* - the data returned as part of the * results from the rating won't be meaningful after the group by (the r.* and round(avg(d.rating),0) values should be though)
Try to use prepared statements and get results and use iterator to parse and print in a loop will get. See also this tutorial.

Categories