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']."%' ";
Related
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."%' ";
I am using the code below to search my database based on keywords given by the user. It seems to work fine for the most part, but i am searching both based on location and keywords. This is where I have the issues.
If i put no location in and search it returns all results regardless of location, which is fine. If i put in a location that does not exist and some keywords, It returns all results matching the keywords and seems to ignore the location.
Also if i leave the keywords empty and search by a location that does exist, it seem that it ignores the location again and just returns all results.
So it would seem my logic for setting the location is not working.
$keys = explode(" ",$tag);
$search_sql = "SELECT DISTINCT providers.* FROM providers JOIN provider_tags ON providers.id = provider_tags.provider_Id JOIN tags ON provider_tags.tag_id = tags.id WHERE tags.tag_name LIKE '%$tag%' OR providers.provider_name LIKE '%$tag%' OR providers.provider_contact_name LIKE '%$tag%' OR providers.provider_features LIKE '%$tag%' ";
foreach($keys as $k){
$search_sql .= " OR tags.tag_name LIKE '%$k%' OR providers.provider_name LIKE '%$k%' OR providers.provider_contact_name LIKE '%$k%' OR providers.provider_features LIKE '%$k%' ";
}
$search_sql .= " AND (providers.provider_town LIKE '%{$location}%' OR providers.provider_local_area LIKE '%{$location}%' OR providers.provider_postcode LIKE '%{$location}%')";
echo $search_sql;
$gettags = mysqli_query($con, $search_sql) or die(mysqli_error($con));
You are adding a bunch of OR conditions in a loop and then a big AND condition for the location. Your AND condition is checked with the last OR of the loop. If any of the others OR in the condition is true then you get a result no matters the AND condition.
Edit :
You'll probably get the results you want if you :
wrap every OR conditions with parenthesis;
wrap all the OR conditions together.
Something like :
$search_sql = "SELECT DISTINCT providers.* FROM providers JOIN provider_tags ON providers.id = provider_tags.provider_Id JOIN tags ON provider_tags.tag_id = tags.id WHERE ( (tags.tag_name LIKE '%$tag%' OR providers.provider_name LIKE '%$tag%' OR providers.provider_contact_name LIKE '%$tag%' OR providers.provider_features LIKE '%$tag%') ";
foreach($keys as $k){
$search_sql .= " OR (tags.tag_name LIKE '%$k%' OR providers.provider_name LIKE '%$k%' OR providers.provider_contact_name LIKE '%$k%' OR providers.provider_features LIKE '%$k%') ";
}
$search_sql .= ") AND (providers.provider_town LIKE '%{$location}%' OR providers.provider_local_area LIKE '%{$location}%' OR providers.provider_postcode LIKE '%{$location}%')";
I have very limited to zero knowledge about SQL or DBs, so apologies in advance.
I am attempting to make a table like structure within a webpage, a column for meal name, and a column for ingredients - it is also searchable via a button.
EDIT:
Thanks for all the replies, they have been most helpful.
The error no longer happens, however now I get no results from the database, but no error.
include("inc/dbConn.php"); /////$db_conx
if(isset($_POST["search"])){
$searchq = $_POST["search"];
$sql ="
SELECT main_meal.name, ingred.name
FROM main_meal
JOIN meal_ingred on meal_ingred.meal_id = main_meal.id
JOIN ingred ON ingred.id = meal_ingred.ingred_id
WHERE ingred.name LIKE '%$searchq%'";
$results = $db_conx->query($sql);
var_dump($results);
if($results->num_rows){
while ($row =$results->fetch_object()){
echo "{$row->name} ({$row->name})<br>";
}
}
}
For clarification here is my structure:
(Sorry for external link, I dont have enough reputation to post images.)
http://i30.photobucket.com/albums/c340/Tyrage/Untitled-2_zpsc48126b3.png
The $results dumps:
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) }
It is quite obvious I don't have a clue what I am doing, so any help is appreciated.
Thanks.
you're lacking a relation table here, which will store connection between meals and ingredients.
also you had error in your query because at first you've tried to use a/b naming correctly, to name a column, and then you user it to name a table.
IMHO you should do something like this (with relation table added):
if(isset($_POST["search"])){
$searchq = $_POST["search"];
$sql ="
SELECT main_meal.name AS a, ingred.name as b
FROM main_meal
JOIN rel_meal_ingred on rel_meal_ingred.meal_id = main_meal.id
JOIN ingred ON ingred.id = rel_meal_ingred.ingred_id
where ingred.name LIKE '%$searchq%'";
$results = $db_conx->query($sql);
if($results->num_rows){ //////line 15
while ($row =$results->fetch_object()){
echo "{$row->a} ({$row->b})<br>";
}
}
}
You could try this?
SELECT *
FROM main_meal
JOIN meal_ingred ON meal_ingred.meal_id = main_meal.id
JOIN ingred ON meal_ingred.meal_id = main_meal.id
WHERE ingred.ingredName LIKE '%bread%'
LIMIT 0 , 30
with the php as follow:
<?php
if(isset($_POST["search"])){
$searchq = $_POST["search"];
$sql ="
SELECT *
FROM main_meal
JOIN meal_ingred ON meal_ingred.meal_id = main_meal.id
JOIN ingred ON meal_ingred.meal_id = main_meal.id
WHERE ingred.ingredName LIKE '%$searchq%'
LIMIT 0 , 30
";
//$results = $db_conx->query($sql);
if (!$results = $db_conx->query($sql)) {
printf("Error: %s\n", $db_conx->error);
}
$count = $results->num_rows;
if($count > 0){
while($row=$results->fetch_assoc()){
echo $row['ingredName'];
echo $row['name'] . "<br />";
$output="ff";
}
}
}
?>
Line numbers would help, to see if line 15 is the assignment to $results, or if line 15 is the $results->num_rows
I'm also assuming you have a $db_conx->connect command somewhere in your code, to open the database connection before running the query?
Your SQL query is invalid: there is no such column as ingred.name available in the WHERE clause, because you have renamed that table as b.
There is no reason to rename your tables (using AS ...) in this query. Leave that clause out. Then add a join condition (e.g, ... JOIN ingred ON (...) — omitting this will make the query return every row from main_meal.
Additionally, there is probably a SQL injection vulnerability in your code, because you are interpolating the contents of the (likely unfiltered) $searchq variable into the query. Use a query placeholder for the argument to LIKE.
EDIT: Strange I vardumpped every variable they are all a bool(false)
I'm trying to make this query. But when I click the search button nothing shows up.
Someone who can direct me in the right direction? Thanks in advance.
$STH = $DBH->query("SELECT * FROM artikel
LEFT JOIN barcode
ON artikel.barcode_id = barcode.barcode_id
LEFT JOIN debiteur
ON artikel.debiteur_id = debiteur.debiteur_id
WHERE debiteur.debiteur_naam LIKE '%$formulier%'
AND artikel.artikel_leverancier LIKE '%$leverancier%'
AND artikel.artikel_leverancier_code LIKE '%$artikelleverancier%'
AND artikel.artikel_code LIKE '%$artikelexact%'
AND artikel.artikel_omschrijving LIKE '%$artikelomschrijving%'
ORDER BY '$orderby' ASC");
Assuming you are interested in items which satisfy atleast one LIKE condition, you need to replace ANDs with ORs
$STH = $DBH->query("SELECT * FROM artikel
LEFT JOIN barcode
ON artikel.barcode_id = barcode.barcode_id
LEFT JOIN debiteur
ON artikel.debiteur_id = debiteur.debiteur_id
WHERE debiteur.debiteur_naam LIKE '%$formulier%'
OR artikel.artikel_leverancier LIKE '%$leverancier%'
OR artikel.artikel_leverancier_code LIKE '%$artikelleverancier%'
OR artikel.artikel_code LIKE '%$artikelexact%'
OR artikel.artikel_omschrijving LIKE '%$artikelomschrijving%'
ORDER BY '$orderby' ASC");
It sounds like you have to test for empty parameters. Here is one way in SQL:
WHERE ('$formulier' <> '' and debiteur.debiteur_naam LIKE '%$formulier%') or
('$leverancier' <> '' and artikel.artikel_leverancier LIKE '%$leverancier%') or
('$artikelleverancier' <> '' and artikel.artikel_leverancier_code LIKE '%$artikelleverancier%') or
('$artikelexact' <> '' and artikel.artikel_code LIKE '%$artikelexact%') or
('artikelomschrijving' <> '' and artikel.artikel_omschrijving LIKE '%$artikelomschrijving%')
Alternatively, you can build up the query clause by clause when the variables are not empty.
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.