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%'...
Related
I've developed a database, where i have three sets of columns:
- Username
- Feeling
- Remark
The entry's for feelings are all the same, because they're being selected from a dropdown menu. I'm looking for a way to count the amount of same results and then echo it on a site with PHP, but I can't get any further than this:
<?php
$con=mysqli_connect("localhost","username","password", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT COUNT(*) FROM thefeels WHERE feeling = 'Happy'";
$result = mysqli_query($con, $query);
var_dump($result)
?>
In this code I want to count the amount of times happy occurs in a column, but even that is not working. How can I count the amount of times the same results is in a column?
So if Happy is there four times and Sad two times it should display:
Happy: 4
Sad: 2
This is a basic Counting Rows task. You will find some examples in the official documentation.
In your case it would be:
$query = "SELECT feeling, COUNT(*) as count FROM thefeels GROUP BY feeling";
$result = mysqli_query($con, $query);
Now you can use the "old school" way (which you will find in many totorials):
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row['feeling']}: {$row['count']}<br>";
}
or move forward and separate data fetching from data processing and data output with:
$feelingCounts = $con->fetch_all(MYSQLI_ASSOC);
And do what ever you need with the fetched data. For example:
var_dump($feelingCounts);
Use conditional aggregation:
SELECT COUNT(CASE WHEN feeling = 'Happy' THEN 1 END) as Happy,
COUNT(CASE WHEN feeling = 'Sad' THEN 1 END) as Sad
FROM thefeels
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
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']);
I would like to have a loop which will go through all elements, and if LoggedIn='1' then it should take country from this row, and then I will connect to the other table, and increment this row, where country=country from 1st table, but I don't know how to start this loop (I mean I don't know how to do if LoggedIn='1', then take this row's country). This is my code:
<?php
require_once("config.php");
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$take = "SELECT * FROM acc WHERE LoggedIn='1'";
$data = mysqli_query($dbc, $take);
while($row = mysqli_fetch_assoc($data))
{
}
?>
just correct your sql
SELECT * FROM acc WHERE LoggedIn = "1"
no need to filter the data in php if you can narrow down your results with sql
now I dont know what you with incerent mean so I wait for an edit or comment to help your further
OK, first off this isn't a great question. A simple Google search should help you to your solution - every tutorial of MySQL will cover SELECT and WHERE query's, every PHP tutorial will cover iterative loops.
You don't want to query the whole database and then loop over it within PHP when you can limit that dataset by simply using
SELECT country FROM table WHERE loggedin = 1
I have a form which has a postcode field (text) and a school field (selection) and what i am trying to do is to populate the selection field with schools from a database :
<?php
$conn = mysqli_connect("localhost", "twa312", "dam6av9a");
mysqli_select_db(twa312, $conn)
or die ('Database not found ' . mysqli_error() );
</form>
Have you worked with joins in SQL before? You can do a select without them, but its much cleaner/faster/easier.
You'd do something like:
SELECT school_info.name AS name, local_schools.postcode AS postcode FROM school_info INNER JOIN local_schools ON local_schools.schoolID = school_info.schoolID
This will grab everything from both tables where your ID is matched.
Give that a try. Your PHP array should end up the same. $var['name'] and $var['postcode']