PHP/MYSQLI: INNER JOIN search bar query issues - php

This is my first time creating a search bar.
The search bar is located on the index/home page, it processes UK postal codes for a online food delivery service.The idea of the search bar is to see what restaurants deliver to the users address. The search bar successfully redirects the users to the menu selection page. However, this is where my issue begins.
Silly me, had already created a dynamic menu selection page, so the moment a new restaurant is created in the admin panel it automatically shows on this page. It works successfully apart from at the moment, it shows all the restaurants in the DB, no matter the area or postal code.
As this is the page the user is directed to on searching their postcode,I am now trying to combine my dynamic menu selection page with the search bar query, So for example if the user types in E14 ABU, all the restaurants in E14 will appear on this page. Sounds straight forwards, however because the restaurant details which is called in the restaurant menu page is in one table and the postcodes in another i have used a INNER JOIN to join the both of them. But the query doesn't work.
I know the query works as it was used to print out the dynamic menu selection page. My query is printing back my or die of "could not search!". I have used
var_dump($sql)
and
if (!$sql) {
die('Invalid query: ' . mysql_error());
}
But nothing prints, which is confusing.
Just a blank white page.
Code
output='';
//return to home page if not entered via search
if(isset($_POST['search'])){
$searchq= $_POST['search'];
$sql=mysqli_query($dbc,"SELECT Rest_Details.Resturant_ID, Rest_Details.Resturant_name, Rest_Details.Res_Address_Line_1, Rest_Details.City_name,
Rest_Details.Avg_Del,Delivery_Pcode.Pcode
FROM Rest_Details
INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Restaurant_ID
WHERE Delivery_Pcode.Pcode LIKE '%$searchq'") or die ("could not search!");
}
Further down the page.
print("$output");
I am only trying to print the restaurant name at the moment, until i can get the query working.
My webpage is successfully connected to the DB, i have error handlers and the search bar name is search.
Any suggestions? would be appreciated

If your field names is cerrect then try this :
$sql=mysqli_query($dbc,"SELECT Rest_Details.Resturant_ID, Rest_Details.Resturant_name, Rest_Details.Res_Address_Line_1, Rest_Details.City_name, Rest_Details.Avg_Del,Delivery_Pcode.Pcode
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Restaurant_ID
WHERE Delivery_Pcode.Pcode LIKE '%".$searchq."'") or die ("could not search!");
I hope you will get your result.

Escape string then make query.
$searchq = mysqli_real_escape_string($dbc, $_POST['search']);
$result = mysqli($dbc, "SELECT dpc.Pcode, rd.Resturant_ID, rd.Resturant_name, rd.Res_Address_Line_1, rd.City_name, rd.Avg_Del FROM Delivery_Pcode dpc INNER JOIN Rest_Details rd ON dpc.Restaurant_ID = rd.Restaurant_ID WHERE dpc.Pcode LIKE '%$searchq'");
$results = [];
while($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
// print results array
print_r($results);
You have to make sure the Delivery_Pcode.Pcode is a VARCHAR type
Read about Sanitizing User Input

Related

Pulling data from multiple mysql tables

Hello I am creating an API for my android application and pulling posts from database so far I successfully pull the posts with its photo and caption yet I have no idea how to pull the posts user profile picture and username which are stored in my users table. Please anyone to point me in the right direction would be a saviour. This is the code I use in php to pull the post's details
$sql = "SELECT * FROM Posts";
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
}
What you want is a join. A good reference for the basics can be found on w3schools.
Basically (and without knowing the details of your database) there has to be a connecting ID in both tables, in this case a user id. For example:
SELECT
Posts.id,
Posts.user_id,
Posts.caption,
Posts.photo,
Users.user_id,
Users.username,
Users.profile_pic
FROM Posts
INNER JOIN Users ON (Users.user_id = Posts.user_id);
This will get every post and for each post it will fetch the relevant line(s) from the Users table (where the user_id is the same as in the post).

Show certain code depending on mysql query? (php)

I need a little kickstart here.
We're just learning php in school and we have this project where we're making a website for movie browsing. So we wanna be able to select genre, and show all movies from that genre using a MySQL database. We're all clear on the SQL queries and such, my question is rather how I make the browser show movies depending on SQL query?
Let me explain. Say we're movies.com
So on movies.com/genre is where you select the genre right, and on movies.com/display is where you're supposed to see the movies from the genre selected. So, clicking on "Comedy" should take you to movies.com/display and show you only the comedy movies. Selecting "Drama" should take you to the same site (movies.com/display) and show you only the drama movies.
Problem here is that we just don't know where to begin, it became a problem when switching page to show certain sql queries depending on what you selected in a previous page. I am not sure how to Google it, but just a link or a suggestion will help. I'm sure it can't really be too hard.
Thanks in advance.
Start with the html to choose a genre:
<form action="display.php" method="POST">
<select name="genre">
<option value="drama">Drama</option>
<option value="comedy">Comedy</option>
<option value="thriller">Thriller</option>
<option value="horror">Horror</option>
</select>
<input type="submit" value="Submit"/>
</form>
Here we have a form with a dropdown menu to select the genre. The forms action goes to display.php
Create display.php where we can get the submitted value and put that into our query:
// get the submitted value
$genre = $_POST['genre'];
// set a default genre if the POST genre is empty
if(empty($genre)) {
$genre = 'comedy';
}
// connect to database
$link = mysqli_connect("localhost", "my_user", "my_password", "db_name");
// check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: (" . mysqli_connect_errno() . ") ";
}
// build the query
$query = "SELECT * FROM movie WHERE genre = '".$genre."'"; // unsafe !!
$query = "SELECT * FROM movie WHERE genre = '".mysqli_real_escape_string($link, $genre)."'"; // safer
// execute query
$result = mysqli_query($link, $query);
// check result
if (!$result) {
echo 'Query unsuccessfull!';
}
// show values
while($row = mysqli_fetch_assoc($result)) {
echo $row['title'];
echo $row['description'];
echo "<br/>";
}
// close connection
mysqli_close($link);
I would suggest having a table of genres. That way you can display the list of genres easily for a user to select from (ie, you could populate an HTML forms select list from that table). The list of genres would have a unique id (an integer) and a text description, so when the list of produced you display the description but have a value that is the id.
Then have a table of movies (I presume you already have this). Each movie would be identified by a unique integer id field/
Lastly a table of movies to genres. This would just link the id of the movie to the id of the genre(s) for the movie. This way you can have a movie linked to several genres if required.
Doing it this way also means that the values you return from the HTML forms can just be integers, which are easily made safe (just use the php intval() function).
In use you would provide a list of genres as a SELECT list. When the user selects an item and submits the form the id of the selected genre is returned to the script. The script can then do a query that joins the tables together, checking the genre is the selected genre that has been returned to the script.
For example.
tbl_genres
id
genre_name
tbl_movies
id
movie_name
tbl_genre_movie
genre_id
movie_id
Then to get the details for a returned genre id:-
$sql = "SELECT *
FROM tbl_genres
INNER JOIN tbl_genre_movie
ON tbl_genres.id = tbl_genre_movie.genre_id
INNER JOIN tbl_movies
ON tbl_genre_movie.movie_id = tbl_movies.id
WHERE tbl_genres.id = ".intval($_POST['genre_id']);

Show query result for logged in user

I got some great help in my last question, someone directed me to go learn about database tables and stuff, since then I blasted through most of the things I was stuck on!
Unfortunately I've reached another problem which I can't seem to fix.
I can merge two tables and get results, but I can't seem to get the results of the user that is logged in. For example, I display the amount of 'gold' the user has at the top left corner, I have 7 users that have 100 gold assigned to them and I only want them to be seen when the user that the gold belongs to is logged in, if you get me? Here's what it looks like all the time, whether logged in or not: http://imgur.com/kgqgnPc
here's the code
$sql = 'SELECT `stats`.`id`, `stats`.`gold`, `users`.`id` FROM stats, users WHERE username = username';
$con=mysqli_connect("localhost","root","","game");
mysqli_select_db($con,'game');
$retval = mysqli_query($con,$sql);
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysqli_fetch_array($retval, MYSQL_ASSOC))
{
echo "Gold :{$row['gold']} <br> ".
"--------------------------------<br>";
I'm 90% sure it's to do with the "select/from/where" part but I've done lots of research and can't get it right :(
Database structure: http://imgur.com/DR40iv8 (Sorry, I don't know how to get it without the command line)
I see that you have the gold in one table and the users in another. The gold in the gold table should point to what user owns the gold. Like for example owner_id pointing to the users id. Then you should be able to do like this:
$sql = "SELECT stats.id, stats.gold, users.id, users.username FROM stats, users WHERE users.username = '$username' AND stats.owner_id = users.id";
This tells to find user with the username specified in $username, and the gold with owner_id the same as the users id matching that username.
Hope this helps
Try:
SELECT `stats`.`id`, `stats`.`gold`, `users`.`id` FROM stats, users WHERE stats.username = users.username
Because username is common to both tables (I assume), it's important to explicitly state which table username is coming from.
Edited to add:
You would still need to specify which username you want from the results of the joined tables.
$sql = 'SELECT `stats`.`id`, `stats`.`gold`, `users`.`id` FROM stats, users WHERE `stats`.username = `users`.username AND `users`.`'.$yourUserVariable.'`;

Retrieve and display comments/queries from database

I'm developing in php/sql a web application where users will be able to post items that they'd like to sell ( kinda like ebay ). I want non-members to be able to comment on the items or ask queries about items.
My problem is I want to display each item as well as any comment/query made about that item, in a similar manner as the way Facebook wall works.
I want to "append comments"(if any) to each item. The comments table is linked to the items table via column item_id. And the items table is linked to users table via column user_id. I have left joined users table with items table to display item details, i tried to left join comments table as well so that there are 3 joined tables.
That fails because no comments are displayed and only one item is displayed, despite there being multiple entries in each table. Here is the code i,m using.
$database->query
('
SELECT sale.*, query.*, users.id AS userid, users.username as user
FROM sale
LEFT JOIN users ON sale.user_id = users.id
LEFT JOIN query on sale.id = query.item_id
where category = "$category" ORDER BY sale.id DESC
');
$show = " "; //variable to hold items and comments
if ($database->count() == 0) {
// Show this message if there are no items
$show .= "<li class='noitems'>There are currently no items to display.</li>" ;
} else {
$show .= "<li>";
while ( $items = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show item details in html
";
while( $query = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show queries below item details
";
}
$show .= "</li>" ;
}
Welcome to Stackoverflow!
I recommend you taking a look at pdo. If you are already using mysql_ functions, then I recommend you switch. More on that can be found here.
Now that your pointed to the direction of to what functions to use when connecting/running queries, you now should create your tables. I use phpmyadmin for managing my database, I find it very good, but it's up to you what you use. Once you've decided on the service you use to manage your database, you should then learn how to use it by doing some google searches.
Now you need to set up your table and structure it correctly. If you say you're having items, then you should make a table called items. Next create the columns to the properties of the items. Also I recommend reading about Database Normalization, which is a key aspect of setting up your SQL tables Etc.
Once you have everything set up, you've connected to your database successfully Etc. You now need to set up the "Dynamic Page". What I mean by this is, there's only one page, say called 'dynamic', then a variable is passed to the url. These are called GET HTTP requests. Here's an example of what one would look like: http://example.com/item?id=345.
If you've noticed, you'll see the ? then the id variable defined to 345. You can GRAB this variable from the url by accessing the built in PHP array called $_GET[]. You can then type in your variable name you want to fetch into the []'s. Here's an example.
<?php
$data = $_GET['varname']; // get varname from the url
if(isnumeric($data)){ // is it totally made out of numbers?
$query = "SELECT fieldname FROM table WHERE id=:paramname";
$statement = $pdo->prepare($query); // prepare's the query
$statement->execute(array(
'paramname'=>$data // binds the parameter 'paramname' to the $data variable.
));
$result = $statement->fetch(PDO::FETCH_ASSOC); // grabs the result of the query
$result = $result['fieldname'];
echo 'varname was found in the database with the id equal to:'.$data.', and the result being: '.$result;
}
?>
So now you can see how you can grab the variable from the url and dynamically change the content with-in the page from that!
Hope this helped :)

JSON-PHP/MySQL - Retrieving info from DB

I am using a JSON script ot print out a list of information (later it is sent to my iPhone application, all works fine on that end) with a specific value in a row in my table in my db.
I have managed to do this, however I am looking to expand my search results.
Working Code - obviously i setup
$link = mysql_connect ($host, $uid, $pwd) or die ("Could Not Connect");
mysql_select_db($db) or die("Could Not Connect to Database");
$arr = array();
$rs = mysql_query("SELECT id, story, releasedate, title, youtube, picture FROM movies WHERE category='Action'");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
I guess where line #4 is, at the end of that, I would like to to do the following, but cannot find any sample code for it.
Example Code:
......from Movies WHERE category CONTAINS 'Action'");
that obviously does not work and I get an error, pretty much my category row has multiple values for movies, ie DRAMA,Action Sustepnse etc in one row, as some movies are a mix of categories now a days, and would like it filtered out properly without the hassle of adding addition category rows in my db
you can do this
this will select movies that belong to one of these genres
WHERE category IN ('action', 'horror', 'comedy')
but if you want to search if the category contains action or drama or horror you need
WHERE category LIKE '%Action%' OR category LIKE '%Drama%'...

Categories