Sending dynamic select form to a MySQL database using POST - php

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

Related

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']);

How to display detail information from database when primary id onchange

i have a table in mysql that contain courseid and coursename. I manage to fill the dropdown menu with courseid from table using php. Now i would like to display coursename each time user select courseid in droplist for example when they select cd123 system will display "multimedia" (information from db based on courseid). Thanx
<body>
<select id="coursecodeID">
<?php
include ('config.inc');
$sql = "SELECT * FROM coursetest";
$rs = mysql_query($sql);
echo "<option>-Please select-</option>";
while($row = mysql_fetch_array($rs))
{
echo "<option value=\"".$row['courseid']."\">".$row['courseid']."</option>\n ";
}
?>
</select>
</body>
Well you just need to do a SELECT Statement that gets the coursename by courseID
Example: select coursename from coursetest where courseid=(Here you put the selected index)
thats its
Feel free to ask me any questions
Simply use $row['coursename'] like this
echo "<option value=\"".$row['courseid']."\">".$row['coursename']."</option>\n";
This is a very basic question so I suggest you read on more tutorials/books/whatever you find useful.
You should know that the mysql_* functions are deprecated, meaning that they won't be developed any further. So in new code it is suggested to use PDO or MySQLi instead.
Do you want the text to show somewhere outside of the dropdown?

PHP Select List To Drive Table Display

I'm having a tough time figuring out how to have a select list drive what is returned in a table. Scenario, there are a list of projects, pending what project your user has access to a subset of items are returned.
Here is some code:
query:
$q = "SELECT DISTINCT projectid, projectname FROM projects where active=1";
select list construction:
//variable for projects list select list name
$dropdown = "Projects Lists \n <select name=\"ProjectsLists\">";
//loop results
while ($row = mysql_fetch_assoc($result)){
$dropdown .= "\r\n<option value='{$row['projectid']}'>{$row['projectname']}</option>";
}//end while
$dropdown .= "\r\n</select>";
echo $dropdown;
Then what i'd like to do is display items returned from a query that needs to be run when the select list is select:
$s_query = "SELECT contentname, contentlocation FROM projectscontent WHERE projectname=<select list value>";
I'm having trouble figuring out if i can capture the selected value. If so, how? I thought i could maybe do $_GET['selectlistname']; but i don't think that is right.
you have to use jquery event .change() this will help you for what you want.
For example:
Add an id in you select options
like $dropdown = "Projects Lists \n <select id=\"mylist\" name=\"ProjectsLists\">";
now with jquery use something like this:
$('#mylist').change(
//provide you selected value
var proName = $(this).val();
//call ajax
$.ajax({
url: 'queryPage.php',
data: 'proName=' + proName,
success: function(data){
$('#result').html(data);
}
});
);
queryPage.php:
//$_REQUEST['proName'] provide you select product name
$productname = mysql_real_escape_string( $_REQUEST['proName'] );
// Now start your query
$s_query = "SELECT contentname, contentlocation FROM projectscontent
WHERE projectname='$productname' ";
now start to run the query and echo the result here on the same page, this will return the data to the page from where you call queryPage.php.
I personally use jQuery DataTables for this type of functionality. I generate a dropdown or group of dropdowns, then on click of a button I update my DataTable element. There are several tutorials on how to do this on the website.
I'm a little concerned, though, that your tables are a bit wonky. This should be very straightforward, and might require more tables than you're telling us about. I'd personally link my two tables on projectid if I was using the structure you're showing above. Then, I'd add an additional table (via inner join on userid) that links users.userid, permissions, and projectid. This would be queried into the second query in your example above to handle permissions.
When I'm generating my dropdown, I'm keeping that simple too. Each <option> would have a value = projectid and the display value would be the project name. On change of the select element listing the projects, I'd run a query (ajax preferrably) to get myself all the project details joined with permissions with where clauses to limit my results to the user, based on permissions. No need to do exotic "merged" values, etc.

Multiple textbox search using PHP and MySQL

I have a table in MySQL with 5 data fields: id, name, total marks, percentage, and rank. I already fetch and displayed all data, but I want search and display by 3 fields name: total marks, and rank. These 3 will be entered in text boxes.
Please mention the particular query for this 3 fields search.
As you've had to ask this question, I'd like to first of all point you towards the MySQL manual and the PHP manual. However, I'll also give you some pointers.
First of all, you'll need to post these search values to your PHP code. This can be done using a form.
<form method="POST" action="script.php">
<input name="name" type="text" />
<input name="total_marks" type="text" />
<input name="rank" type="text" />
<input type="submit" value="Search" />
</form>
Then, you'll need to access these values in your PHP script as such.
// script.php
$name = mysql_real_escape_string($_POST['name']);
$total_marks = mysql_real_escape_string($_POST['total_marks']);
$rank = mysql_real_escape_string($_POST['rank']);
// I'll leave SQL injection protection up to you
Finally, you'll need to pass these queries to an SQL query to retrieve the items from your database. As you haven't posted your exact scheme, you'll have to modify this to suit your needs. Also, I've left the actual database loading/access to you.
// script.php
$sql = "SELECT * FROM `table` WHERE (
`name` = '{$name}' AND
`total_marks` = '{$total_marks}' AND
`rank` = '{$rank}'
)";
Rather than passing the variables directly to the SQL query and using mysql_real_escape_string or similar functions, I'd look in to using PDO for security and for some database abstraction.
If I understand you correctly
Select *
FROM Keys
WHERE name = 'stringName' AND total_marks = numberTotalMarks AND rank = procent

populate select box with mysql data

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!

Categories