Processing Data using Web Form - php

I have a database that stores data input from a website. I have designed a form to retrieve some of the data from the database. My issue is, I want some of the form fileds to auto populate with data from certain table columns. i don't know the PHP code to insert into the form fileds to do this.
The form looks like this:
http://onlinestudentsadmission.com/schooldemo/studentsdataform.php
The table has the following columns:
userid last_name first_name year friendly_url has_pic Gender Orphan Admmission School County
I want the form to pull the data in year, County, and School columns and populate the field options. What code do I insert into those form fields?
The form submits to studentdatadisplay.php which am yet to code since I dont know how it should look like so as to get the data from the data retrieval form and format it to a table depending on the search criteria.
Any help will be appreciated alot.

If your HTML form inputs have the name attributes set, and your form action is actually posting to the right URL, you don't have to do anything else to your form.
Have a read through this guide for PHP form handling. Basically, the name attributes for each of your inputs will be an element in the $_POST object available to your in your future studentdatadisplay.php script. You'll do any database queries in that script file.

Are you talking about drop-down list that is automatically populated with the different values from a column (such as year, County or School)?
If so, the PHP at the top of your page should look something like this:
<?php
$con=mysqli_connect("localhost","username","password","myDatabase");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$lookupYear = mysqli_query($con,"SELECT DISTINCT year AS value FROM tblStudents ORDER BY year ASC");
$lookupCounty = mysqli_query($con,"SELECT DISTINCT County AS value FROM tblStudents ORDER BY year ASC");
$lookupSchool = mysqli_query($con,"SELECT DISTINCT School AS value FROM tblStudents ORDER BY year ASC");
?>
Then when you're ready to list each one in the body HTML of your page, generate a dropdown option for each one using this example:
<select name="year">
<?php
while($row = mysqli_fetch_array($lookupYear))
{
echo "<option value=\"" . $row['value'] . "\">" . $row['value'] . "</option>";
echo "\n";
}
?>
</select>
I hope that helps.

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

Link next to each row in sql table result in php to display full data for that row

I am trying to display couple of fields from sql table and want to add a link in each row that takes user to a page that shows all results for that specific table row.
Let me explain more: I have a MySql table that has the following fields: filename, intro_data, content_data, conclusion_data. I have created a php page that displays the list of all data for the filenames & intro_data fields in that sql table using this code:
//Query to select rows or data in table
$query= "SELECT filename,intro_data FROM file_data";
$result=mysqli_query($connect, $query);
if (!$result)
{
die('Error fetching results: ' . mysqli_error());
exit();
}
echo '<table border="1">'; // start a table tag in the HTML
//Storing the results in an Array
while ($row = mysqli_fetch_array($result)) //Creates a loop to loop through results
{
echo "<tr><td>" . $row['filename'] . '</td><td>' . $row['intro_data'] . '</td><td> More Info</td></tr>';
}
echo '</table>'; //Close the table in HTML
//Closing DB Connection
mysqli_close($connect);
If you noticed in the above code, I have a "More Info" anchor tag that links to 'full_table_row_results.php'. In this page, I want it to show all the field results (filename, intro_data, content_data, conclusion_data) for that particular row. I know that I can query all results for a table like this:
$query= "SELECT * FROM file_data";
But how can I create the 'full_table_row_results.php' that queries all fields for that particular row that the user is clicking on? Since the row results are from an array, how do I know which row number in that array has the user clicked on? I am not sure how to code the More Info page.
I am stuck on this and not sure how to implement this.
One solution (as always, there's many other).
First, you need an id for each row in your table (if you do not have already one). With MySQL an auto_increment integer field does the job.
Next, you need to get the id in your php code.
$query= "SELECT id, filename,intro_data FROM file_data";
Then you use it as a parameter when you link to your full_table_row_results.php script. The link will be:
echo '<a href="full_table_row_results.php?id=' . $row['id'] . '">' /* etc. */ ;
(Adapt it in your code, I did not copy all your code to easier readability).
And in this last script you get access to this parameter with $_GET['id']. Then you can query your database for this one row only (with a WHERE clause).
Hope this help

Php select default dropdown based on dynamic dropdown

Building an edit users form for my system and having a little trouble trying to figure out how to do a selected="selected" for the value in the dropdown that goes with the users information in the database.
This is my code: http://pastebin.com/EVdUfTzN
The names of the offices are stored in one table called offices and the value of the office that the patient went to is stored in patients. Basically I want to select the information from both tables and add a selected option on it.
Here is picture of the offices table
Here is a picture of the patients table
Do you understand what i am trying to do? Maybe even simplify it so its one query with INNER JOIN
Try this (replace lines 25-29):
<?php
while ($dd_loc_row = mysql_fetch_array($dd_loc_result)) {
echo "<option value=\"" . $dd_loc_row['office_id'] . "\"".($row['pat_loc'] == $dd_loc_row['office_id'] ? ' selected="selected"' : '').">" . $dd_loc_row["office_name"] . "</option>";
}
?>

Retrieve data from query filled drop down box

I have made a dropdown box that is filled by a query that looks for company names from company name database, these names also have and ID number that I don't want displayed but are looked up in the query. I need the ID number to link to sites of the company so somehow when I hit the submit button on the site page it finds the ID number by looking at the position value and relating that to the position on the query array I just don't know what to do. If it helps this is how I fill the dropbox:
mysql_select_db("DB", $con);
$query = "SELECT Company_Name, ID FROM company_table";
$result = mysql_query($query) or die(mysql_error());
$options ='';
$num = 0;
while ($row=mysql_fetch_array($result)) {
$num = $num+1;
$options.= "<OPTION VALUE=\"$num\">".$row["Company_Name"];
}
<SELECT NAME=thing>
<OPTION VALUE=0>Choose
<?=$options?>
</SELECT>
Any Ideas?
There are two immediate ways this can be done. One is to keep it the way you have it using an index, $num; the other way is to use the actual company id field, ID. If you stick with the index of $num, when the user submits the form (i.e. - selects a company), you will have to re-query the database and re-loop through the results to find the specific company (or you could use a LIMIT/OFFSET; notes at end of answer).
I would recommend using the actual company id in your form:
while (($row = mysql_fetch_assoc($result))) {
$options.= '<option value="' . $row['ID'] . '">' . $row["Company_Name"] . '</option>';
}
This will generate a list of options, like you currently have, except the value of each will be the specific company id. When the user submits the form, let's assume the form is using POST, you can get the ID with:
$companyId = (isset($_POST['thing']) && is_numeric($_POST['thing'])) ? intval($_POST['thing']) : false;
$results = mysql_query('SELECT * FROM company_table WHERE ID=' . $companyId);
.. and then process as you desire.
I use $_POST['thing'] in the above example as that is what your code-example has the select field named. Also, I make the assumption that ID is an integer.
If the actual ID needs to remain hidden, as specified, the index of $num can be used with MySQL's LIMIT/OFFSET as follows:
$selectedCompany = (isset($_POST['thing']) && is_numeric($_POST['thing'])) ? intval($_POST['thing']) : -1;
if ($selectedCompany >= 0) {
$query = "SELECT Company_Name, ID FROM company_table LIMIT " . $selectedCompany . ", 1";
// process as desired
}
An option is to add a "created" field to the company table that is a timestamp, or just a 2nd column that is a random UUID column. Then set the value of the dropdown to this column so you don't show ID but you will still know the record since you are using the "other" id as well.
I actually use this method in one of my programs where it was the same situation as you, the client didn't want the ID to be shown.
If you don't want to go with this method (because you don't want a 2nd column) you could just md5 hash the ID or some other hashing method.
Then you would do
SELECT * FROM company where md5(id) = "$value".
The downside to this method is that it is an expensive query, since you won't be using an index and it has to compute all the md5 hashes for each id.

Sending dynamic select form to a MySQL database using POST

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

Categories