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.
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 requesting your advice about the following:
I have two tables:
Customers and Orders.
I am printing the data of customers inside a table using a while loop:
$sql = "SELECT * FROM wccrm_customers where status = '1' order by date desc";
$result = mysql_query($sql, $db);
while ($daten = mysql_fetch_array($result)) { ?>
echo $daten[id];
echo $daten[name] . ' ' . $daten[vorname];
echo $daten[email];
echo $daten[telefon];
} ?>
Now I try to add a new field in this list: Purchased YES/NO. As we have more customers then buyers, we want to show whether someone has bought or not:
The Connection between this two tables is the first/lastname in both tables!
So if customer.name = orders.name and customer.firstname = orders.firstname I want to echo "YES" if not then "NO"
I tried with a JOIN, but here I just get the results who are in both table:
SELECT *
FROM wccrm_customers AS k
INNER JOIN wccrm_orders AS o
ON o.namee = k.name AND o.firstname = k.firstname
but I need to have all of the customers and the ones who are in both lists marked...
Is this possible? If yes: How can I achieve this?
Thank's for your advice!
Kind regards,
Stefan
This has nothing to do with PHP, or with while loops; you just need to form your join properly:
SELECT DISTINCT
`k`.*,
`o`.`namee` IS NOT NULL AS `Purchased`
FROM `wccrm_customers` AS `k`
LEFT JOIN `wccrm_orders` AS `o`
ON
`o`.`namee` = `k`.`name`
AND `o`.`firstname` = `k`.`firstname`
Read more about the different join types: http://www.sql-join.com/sql-join-types/
(images courtesy of that site, which also contains an example and discussion of almost exactly what you're trying to do!)
By the way, you must have missed the massive red warning banner in the manual about using the deprecated (now removed) mysql_* functions. You should stop doing that! Use MySQLi or PDO instead.
a shorter one
SELECT DISTINCT k.*, IF(o.namee IS NULL, 'no', 'yes') purchased
FROM
wccrm_customers AS k
LEFT JOIN wccrm_orders AS o USING (namee,firstname)
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']."%' ";
Ive got the query below :
$sql = "SELECT `scanners`.`KordNo`, `scanners`.`BundleNumber`
FROM `scanners`, `TWOrder`, `Stock`
INNER JOIN `TWORDER` ON `scanners`.`KordNo` = `TWOrder`.`KOrdNo`
AND `scanners`.`Date` = '" . $date . "'
INNER JOIN `Stock` ON `TWOrder`.`Product` =`Stock`.`ProductCode`
AND `Stock`.`ProductGroup` NOT BETWEEN 400 AND 650
AND `scanners`.`Scanner` IN (
ORDER BY `scanners`.`KordNo` ASC";
foreach($scanner as $x)
{$sql .= $x . ",";}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
$return[] = $row;
}
When i echo the sql on php my admin i get the error not a unique table/alias stock;
can someone advise?
Since you're using explicit JOINs, drop the other two tables off of the FROM clause.
...
FROM `scanners`
INNER JOIN `TWORDER` ON `scanners`.`KordNo` = `TWOrder`.`KOrdNo`
...
On line 2 you have...
FROM `scanners`, `TWOrder`, `Stock`
Then you have some INNER JOINs on to TWOrder and Stock.
That's mixing syntax (, and JOIN) which is messy. Stick to JOIN
It means that TWOrder and Stock are mentioned Twice in the query
If you REALLY need to include those table multiple times in one query, you need to give them alias names, so they can be distiguished from each other.
But I think it's probably a mistake and that Line 2 should just be
FROM `scanners`
Then, also, I'm not sure how you got that to compile. You have IN ( and then an ORDER BY clause, to which you append a list of values. You should append the list before the ORDER BY and then append the ORDER BY after you've finished the loop.
I am trying to set up a filter system for a small shop I am developing. Basically, I am working the results off a list of variables. the page, products.php if there is no querystring will show all products. However, if there is a variable present I want it to alter the select statement where necessary.
however, I am having problems filtering. If i use the AND statement for all variables it does not filter appropriately neither does the OR. So if i wanted black size 5 shoes it would show all size fives regardless of color.
Is there a better approach to take with this as is becoming a fair old head scratcher!
if ($queryString == NULL){
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
GROUP BY store_products.prod_id";
}else{
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
where store_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat' GROUP BY store_products.prod_id";
}
example variable string
products.php?sale=&cat_id=1&size=&color=Yellow
Try building your WHERE criteria before running the query.
String:
products.php?sale=&cat_id=1&size=&color=Yellow
myfile.php
$criteria = "WHERE 1 ";
if (isset($_GET['sale']) {
$criteria .= "AND tore_products.sale=$_GET['sale'] ";
}
if (isset($_GET['cat_id']) {
$criteria .= "AND store_products.cat=$_GET['cat_id'] ";
}
if (isset($_GET['color']) {
$criteria .= "AND tore_products.color=$_GET['color'] ";
}
And so on then run your query:
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id
$criteria
GROUP BY store_products.prod_id";
And please remember to clean your $_GET variables prior to querying with them using mysql_real_escape_string, mysqli or PDO!
$query = "SELECT * FROM store_products
JOIN store_cat on store_products.cat=store_cat.cat_id
JOIN prod_sizes on store_products.prod_id=prod_sizes.product_id
JOIN prod_color on store_products.prod_id=prod_color.product_id ";
if {$queryString != NULL){
$query .= " WHERE tore_products.sale='$sale' OR prod_color.color='$color' OR prod_sizes.size='$size' OR store_products.cat='$cat'"
}
$query .=" GROUP BY store_products.prod_id;"
Then you execute your Query :)