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']);
Related
I am currently developing an application which allows the user to pick an option from a dropdown, and list table data based on this option, and done so dynamically. I was pondering the thought of a search bar which allows the user to search for a country name (within a continent) and list said country name upon searching. The part which confuses me is can I make it so that the user can pick a continent from the dropdown, and input a country name into the search bar then click the same button and receive the listing?
I understand the importance of picking relevant code however I think it would be important for the reader to see both my home page, and action page to understand what I am trying to achieve.
Here is the index code:
require_once('repeat_code.php');
$db = dbConn();
//Make an SQL statement
$sqlContinents = "SELECT DISTINCT ID as contID, Name as contName from w_Continent order by contName;";
//Execute SQL statement
$stmt = $db->query($sqlContinents);
//Start a form
echo "<form action='listCont.php' method='get'>\n";
//Start a select box
echo "<select name='contID'>\n";
//Loop through all continents
while ($continent = $stmt->fetchObject()) {
//Display each one as an option in the dropdown
echo "\t\t<option value='{$continent->contID}'> {$continent->contName} </option>\n";
}//end loop
// end select box
echo "</select>\n";
// display submit button
echo "<input type='submit' value='Find Country' />\n";
// end form
echo "</form>\n";
Here is the action page:
if(!empty($contID)) {
//Connect to the database
require_once('repeat_code.php');
$db = dbConn();
//Create SQL statement using ID
$sqlCountries = "SELECT w_Country.Name, w_Continent.Name as 'contName', w_Country.Region as 'regionname', w_Country.HeadOfState, w_Country.Capital
FROM w_Continent JOIN w_Country on w_Continent.ID = w_Country.Continent
WHERE w_Continent.ID = '$contID'";
//Execute statement to get a record set back
$stmt = $db->query($sqlCountries);
// Start a table
echo "<table border='1'>\n";
// Start a header row
echo "<tr><th>Country</th><th>Continent</th>\n";
//Loop through the record set
while ($continent = $stmt->fetchObject()) {
//Display each student in a row
echo "\t<tr><td>{$continent->Name}</td><td>$continent->contName</td>\n";
}//End loop
//end the table
echo "</table>";
Any help is appreciated.
Create a drop down and input box in a single line.
Drop Down Contain the continent and input box is empty.
In database create 2 tables in following format.
Continent Table
id | Continent_name
Countries Table
id | country_name | continent_id
Now run query in first table and display all the continent in drop down.
now when user select the continent name from the drop down and also write country name in the search box, then you have to query like this.
<form method="post">
<input type="hidden" name="command" value="search">
<select name="select_box">
<option value ="1">Asia</option>
<option value ="2">Africa</option>
</select>
<input type ="text" name="search_box" placeholder="Type Country">
</form>
Now Run PHP code like below.
if($_REQUEST['command']=='search'){
$continent_id = $_REQUEST['select_box']; //suppose user select asia
$country_name = $_REQUEST['search_box']; // suppose user type "Pakistan"
//now execute below query in countries table.
$query ="select * from countries where continent_id='$continent_id' and country_name like '%$country_name%'";
}
At the moment, I have a page that is displaying some posts. News posts, blog posts etc. What I want to achieve is having checkboxes so the user can check off, whatever kind of post he/she wants to see.
I should for instance be able to check off ´news´ and ´talking points´ and only see posts with those categories, and not see posts with the category ´blog´ for instance.
My current query looks like this (gets all posts, no matter the category). I believe some jQuery should be involved but I am not sure. How can I connect checkboxes with the query?
Can anyone help me with this?
$sql = "SELECT * FROM articles ORDER BY id DESC";
EDIT
I have tried this, but whenever I use the checkboxes, nothing is shown but I do not get an error?
My code:
<?php
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
$categories = $_POST['check_list'];
// Loop to store and display values of individual checked checkbox.
foreach($categories as $selected){
echo $selected."</br>";
}
}
}
?>
<br /><br />
<?php
if(!empty($_POST['check_list'])){
$sql = "SELECT * FROM articles ORDER BY id DESC WHERE `category` IN (".implode(',',$categories).")";
} else {
$sql = "SELECT * FROM articles ORDER BY id DESC";
}
Each checkbox should have a value. When you submit your form (probably a $_POST) you will see on the backend which checkboxes are checked. You can inspire from this tutorial: https://www.formget.com/php-checkbox/
IMPORTANT - You should filter the form data before using it in your SQL query. You can inspire from here: http://php.net/manual/en/function.filter-input.php
And you should prepare the variable before using it in the SQL Query:
$unsafe_variable = $_POST["user-input"];
$safe_variable = mysql_real_escape_string($unsafe_variable);
Now that you know which checkboxes are checked, you need to change the SQL query in order to filter by them.
So I suppose the checkboxes values are numbers (representing id's). So you will have an array called $ids that will contain all the checked checkboxes. Your mysql query will become something like:
$sql = "SELECT * FROM articles WHERE `id_category` IN (".implode(',',$ids).") ORDER BY id DESC";
Multiple categories selection system for Article
Earlier M using two tables
articles & categories and save category ID in articles table
But in this system I can save only one category ID per article
I want to save Article in Multiple categories
While searching I found same question on StackOverflow
I understand the whole concept of adding one more table of relationship & saving Article ID & Category ID in this table.
But not aware how to implement multiple selection system using arrays in New Article Form & Edit Article Form.
earlier I am showing Select in my form to display categories list in Add Article & Edit Article Page.
pls someone explain me How to show categories list in multiple checkbox style in my form so user can select multiple categories and then after POST how to get checkbox data and run query to insert data in both Article Table & New Relationship table with selected categories ID
want to display category List like this screenshot
Many Many Thanks...
EDIT:
I use echo '<input type="checkbox" name="selcats[]" value="$catid"> ' .$catname;
to display Categories check box
Its showing in a row side by side.
how to change display like screenshot i.e. list with scrollbar
& need to process this array and insert in new table while inserting article in databse.
EDIT 2
got the checkbox display correct in a scroll list by using a div :D
<div style="height: 150px; width: 200px; overflow: auto;">
In my case, I use a "tag system", for instance: You have an article with one category, nothing will change that... In adition, you can create another field in the article table with the relevant words (or whatever you want) and separete them with spaces or commas.
// Get the data from your database
$tags = 'world, travel, turism, cities';
// Separate the values
$tags = explode(", ", $tags);
// Create a link for each one
foreach($tags as $t)
{
echo ' ' . ucfirst($t) . ' ' . "\r\n";
}
It should output:
World
Travel
Turism
Cities
And it means that you can SELECT articles that have the title LIKE the tag, or whatever you want to search.
Is that what you was looking for?
You basically require two tables, with this structure
table_categories
_____________________________
| id | title |
-----------+---------------+
table_category_detail
______________________________________________
| id | categoryId | articleId |
-----------+---------------+------------------
To extract all categories, select all from the table_categories and put up into the select menu with mutiple selection enabled.
Next, when posted get the selected box values and insert into table_category_detail one by one
This is how you create a select box
$query = "SELECT * FROM table_categories";
$result = mysql_query($query);
echo '<select multiple="multiple">';
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['id'].'">'.$row['title'].'</option>';
}
echo "</select>";
Or a Multiple Check Box
while($row = mysql_fetch_assoc($result)) {
echo '<input type="checkbox" name="selcats[]" value="'.$row['id'].'"> ' .$row['title'];
}
After the post:
// Here write codes to insert the article first
$articleId = mysql_insert_id(); //get the id
$values = $_POST['selcats'];
foreach($values as $value) {
$query = "INSERT into `table_category_detail` VALUES(NULL, $value, $articleId)";
$result = mysql_query($result);
}
I am trying to use a dynamic select form to send information to a MySQL database. The user will be able to choose their school, and then select their major from within that school's list (all retrieved from a MySQL table). I then want to send that information to a different table in the database to be stored.
This is what I have for the code thus far:
<select name="school">
<php
$sql = "SELECT school_name, school_id FROM school_table ORDER BY school_name";
$query = mysql_query($sql,$conn);
while($row = mysql_fetch_array($states))
{
echo ("<option value=$row[school_id]>$row[school_name]</option>");
}
?>
</select>
I don't know how to make the second select, which would ideally recognize the school_id from the first table and match it with the corresponding school_id on the second table, which also lists the majors at that school. Also, I don't know how to send the form when it is finally done to a MySQL table.
You could either use a simple form to submit the value from the combobox to the server (as HTTP POST or HTTP GET) and use the value as a variable in you SQL statement or you could use a simple AJAX request to send the necessary information to your php script. Anyway, your serverside code should look like this:
//process.php
$myRetrievedValue = $_POST["school"];
$mySqlStm = "SELECT * FROM foo WHERE bar = '".mysql_escape_string($myRetrivedValue)."'";
On the client side you code could look like this (using a simple form and no AJAX stuff):
<form action="process.php" method="post">
<select name="school">
<php $sql = "SELECT school_name, school_id FROM school_table ORDER BY school_name";
$query = mysql_query($sql,$conn); while($row = mysql_fetch_array($states)) {
echo ("<option value=$row[school_id]>$row[school_name]</option>"); } ?>
</select>
<input name="" type="submit" />
</form>
Please remember: Whenever you use a user input in you query use prepared statements (or at least escape methods as above) to avoid SQL injections.
answer is to select from both tables in one SELECT using joins:
http://dev.mysql.com/doc/refman/5.0/en/join.html
INNER JOIN
SELECT `school_table`.`school_name`,
`school_table`.`school_id`,
`2ndTable`.`school_id`,
`2ndTable`.`major`,
FROM school_table,2ndTable
WHERE `school_table`.`school_id`=`2ndtable`.`school_id`
ORDER BY school_name
or a
LEFT JOIN (returning all columns in the left)
SELECT `school_table`.`school_name`,
`school_table`.`school_id`,
`2ndTable`.`major`,
`2ndTable`.`school_id`
FROM school_table
LEFT JOIN on `school_table`.`school_id`=`2ndtable`.`school_id`
ORDER BY school_name
I have some trouble with this.
I have one database with the following tables:
Countries -> All countries of the world are added
Cities -> The cities are also added
user_profile -> The profile of the user with the fields "country" & "city".
Everything works fine, even the populating of the boxes is working. But I don't know how to get the SELECTED value of the user for both country & city.
I have the following code:
Select Country: <br />
<select id="countries">
<option value="">--</option>
<?php
$sql = "SELECT country, title FROM countries ORDER BY title ASC";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo "<option value=\"".$row['country']."\">".$row['title']."\n ";
}
?>
</select>
Select City: <br />
<select id="cities">
<option value="">Select one</option>
<?php
$sql = "SELECT country, title FROM cities ".
"ORDER BY title ASC";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo "<option class=\"".$row['country']."\" value=\"".$row['title']."\">".$row['title']."\n ";
}
?>
</select>
Now I need to check in the table user_profile which country & city he chose and show it to him.
I also use jchained (jquery plugin) to make both select boxes working together.
How can I achieve this? If I need to post anything else, please let me know.
Thanks in advance.
You have a lot of missing code here but I will try to help.
I am going to start by assuming that you have already stored the users selections in the user_profile table and that they are foreign keys to to correct relations.
To get the selected id's for repopulating the select boxes with the selected flag use:
SELECT country, city FROM user_profile where id = $user_id;
To get the text values you would do something like:
SELECT country.title as country, city.title FROM user_profile LEFT JOIN countries ON user_profile.country = country.id LEFT JOIN cities ON user_profile.city = cities.id WHERE user_profile.id = $user_id;
If you are not storing them as foreign key relations but instead by string title in the user_profile table you will need to do this:
SELECT country.title as country, city.title FROM user_profile LEFT JOIN countries ON user_profile.country = country.title LEFT JOIN cities ON user_profile.city = cities.title WHERE user_profile.id = $user_id;
You can then use these results to either display to the user or set the "SELECTED" flag in the options box.
Do you just mean you don't know what to do after they select the values? If so then you would just use the form to post the values to the new page. On the receiving page you can run a query to Update the user's profile.
Sorry if my response isn't detailed enough ><
edit Oh, I may see what you mean now. You're able to store it correctly but you want the correct option to be flagged as selected if it's what the user has previously set? If that's it then you can query for the value, then inside of the while loop just add a check to see if $user_country == $row['country'] and if so echo ' SELECTED '. Hope that helps!