how to pre populate fields based on search results of data base - php

I am new to stack overflow and really appreciate all the help. I currently have a database with basic columns, name id company etc. I created a search query that shifts through this list based on firstname, lastname, or timestamp date. I was able to print the results on the query page of the search but want this to pre populate on the same form page as a new entry. i was able to link from the query page to the form page but am not sure how to populate these results on the form page.
my current query page prints as the following :
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div id="container" style="width:750px;background-color:#FFFE8D;margin-left: 250px">
<div id="Back" style="float:left; background-color:#FFFE8D;">
<form action="http://localhost/contractor/existingcontractorpage3.php">
<input type="submit" value="Back">
</form>
</div>
<div id="Is this the Contractor?" style="float:right; background-color:#FFFE8D;">
<form action="http://localhost/contractor/redirectcontractorpage.php">
<input type="submit" value="Next">
</form>
</div>
<div id="info" style="width:750px;height:95px; text-align: center">
<h3> If this is the contractor, please move on to the next page using the corresponding button above. </h3>
<h3> Please enter the exact information on the next page. </h3>
</div>
<div id="results" style="width:750px;height:225px; text-align: center">
<?php
$host = "localhost"; //server
$db = ""; //database name
$user = ""; //databases user name
$pwd = ""; //password
mysql_connect($host, $user, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$searchTerm = trim($_GET['searchname']);
// Check if $searchTerm is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
else
{
$sql = "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ', ARRIVAL) like '%$searchTerm%'";
$query = mysql_query($sql);
$count=mysql_num_rows($query);
if(($count)>=1)
{
$output = "";
while($row = mysql_fetch_array($query))
{
$output .= "First Name: " . $row['FIRSTNAME'] . "<br />";
$output .= "Last Name: " . $row['LASTNAME'] . "<br />";
$output .= "Arrival: " . $row['ARRIVAL'] . "<br />";
}
echo $output;
}
else
echo "There was no matching record for the name " . $searchTerm;
}
?>
</div>
<br> </br>
<br> </br>
</body>
</html>
Now ideally i would want the results to pop up here, and if possibly have a radio button to the right of each result( if there is ever more than one) to select and continue to the form page to pre populate each field. the form page is simply like this:
<form action="insert_submit.php" method="post">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" />
<br>
</br>
Last Name: <input type = "text" name="LASTNAME" id="LASTNAME"/>
<br>
</br>
Purpose: <input type = "text" name="PURPOSE" id="PURPOSE"/>
<br>
</br>
Company: <input type = "text" name="COMPANY" id="COMPANY" />
<br>
</br>
Who here to see: <input type = "text" name="WHOHERETOSEE" id="WHOHERETOSEE"/>
<br>
</br>
<input type="submit" value="Submit">
<br>
</br>
</form>
thanks so much! hope to hear back soon as this is my last straw on my project.

The simplest way to do this is to pull the data from the database like you're doing, except where you want to add the form into the page. Then in your loop print out form fields:
You need to give each radio a unique name. You could use an incrementing id, or you could give it the same as the row name.
Method 1:
while($row = mysql_fetch_array($query))
{
$output .= "<label>First Name: " . $row['FIRSTNAME'] . "</label><input type=\"radio\" name = \"radio[]\" value=\"".$row['FIRSTNAME']." ".$row['LASTNAME']."\"/>";
..
..
}
You will then be able to get the values from the radio buttons by using GET or POST when the from is submitted.
Setting name = "radio[]" puts all the values in an array which you can get on the next page once the form is submitted.
On the next page after form submission, $_POST['radio'] or $_GET['radio'] will return an array of all the values which you specify. Notice how the value attribute has been filled in above. Do this for each of the rows.
Also be careful about using my_sql connections. It's depreciated as of PHP 5.5.0. Use mysqli or PDO instead, it's more secure. http://ie1.php.net/function.mysql-connect
Check it this link. it compares and provides examples on both

I don't see where you're connecting the query search and form page, but you could create the link back containing the data in GET params in the url, since I don't see password or private material in these fields. Then use php to populate the forms.
$url = "your_form_page?";
while($row = mysql_fetch_array($query))
{
$url .= "fname=" . $row['FIRSTNAME'];
$url .= "&lname=" . $row['LASTNAME'];
$url .= "&arrival=" . $row['ARRIVAL'];
}
// $url = your_form_page?fname=bob&lname=jones&arrival=blah
Then to populate the form..
<form action="insert_submit.php" method="post">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" value="<?php echo $_GET['fname']; ?>" />
Hopefully this helps or at least gets you thinking in the right direction.

Related

PHP How to choose which table to display and then keep that table displayed after a form submission

I'm trying to use an HTML dropdown form in order to let the user choose which table from the database to display. This part works fine, but I want them to be able to add to whichever table they choose. I've created the form for it but once they hit submit on that form it unloads the table they selected and fails to add the data to the table.
This is the code for the main page; body.php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form - PHP/MySQL Demo Code</title>
</head>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<div>
<label for="dbselect">Select Table:</label><br>
<select name="dbselect" id="dbselect">
<option value=""><-- Choose Table --></option>
<option value="messages">messages</option>
<option value="messages2">messages2</option>
</select>
</div>
<div>
<button type="submit">Select</button>
</div>
</form>
<?php
session_start();
include 'get.php';
$_SESSION["dbselect"] = filter_input(INPUT_POST, 'dbselect', FILTER_SANITIZE_STRING);
if ($_SESSION["dbselect"] == "messages") {
dbMessages("*");
include 'Forms/contact_form.php';
}
if ($_SESSION["dbselect"] == "messages2") {
dbMessages2("*");
}
?>
</body>
This is the code that actually prints the tables, which I believe works fine; get.php:
<?php
function display_data($data) {
$output = "<table>";
foreach($data as $key => $var) {
//$output .= '<tr>';
if($key===0) {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= "<td>" . $col . '</td>';
}
$output .= '</tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
else {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
}
$output .= '</table>';
echo $output;
}
function dbMessages($selector) {
include 'db.php';
$query = "SELECT $selector FROM messages";
$res = mysqli_query($conn,$query);
display_data($res);
}
function dbMessages2($selector) {
include 'db.php';
$query = "SELECT $selector FROM messages2";
$res = mysqli_query($conn,$query);
display_data($res);
}
And this is the code that is supposed to display the form and upload the data into the table; contact_form.php:
<?php
include 'db.php';
if ((isset($_POST["Submit"])) && (!empty($_POST["txtName"])) && (!empty($_POST["txtPhone"])) && (!empty($_POST["txtEmail"])) && (!empty($_POST["txtMessage"]))) {
$txtName = $_POST['txtName'];
$txtEmail = $_POST['txtEmail'];
$txtPhone = $_POST['txtPhone'];
$txtMessage = $_POST['txtMessage'];
$query = "insert into messages(ID, name, email, phone, message) values (NULL,
'$txtName', '$txtEmail', '$txtPhone', '$txtMessage')";
$res = mysqli_query($conn , $query);
mysqli_close($conn);
unset($_POST);
echo "<meta http-equiv='refresh' content='0'>";
}
echo '
<fieldset>
<legend>Contact Form</legend>
<form name="frmContact" method="post" action="index.php?send=1" target="_self">
<p>
<label for="Name">Name </label>
<input type="text" name="txtName" id="txtName" >
</p>
<p>
<label for="email">Email</label>
<input type="text" name="txtEmail" id="txtEmail">
</p>
<p>
<label for="phone">Phone</label>
<input type="text" name="txtPhone" id="txtPhone">
</p>
<p>
<label for="message">Message</label>
<textarea name="txtMessage" id="txtMessage"></textarea>
</p>
<p> </p>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit">
</p>
</form>
</fieldset>
'
?>
This is the observed process:
I select which table to display using dropdown menu and hit select.
Selected table successfully appears with its form.
I enter data into form and hit submit.
The dropdown menu returns to it's default state and the table unloads.
Entered data fails to be added to table.
This is the expected process:
I select which table to display using dropdown menu and hit select.
Selected table successfully appears with its form.
I enter data into form and hit submit.
Selected table stays on the page and submitted data is successfully added.
It should be noted that the contact_form.php file is only for the first table, messages, and not for messages2.
This line in your body.php:
$_SESSION["dbselect"] = filter_input(INPUT_POST, 'dbselect', FILTER_SANITIZE_STRING);
runs every time that page is called, regardless of whether the form containing the dropdown has been submitted or not.
This therefore overwrites the Session value before your code has chance to check what it is. This means that when the contact form is submitted, it still tries to get the dbselect value from $_POST, will fail, and therefore set the Session value incorrectly, removing what was set when the table selection form was last submitted.
You just need to check whether that form has been submitted before overwriting the Session value.
Also FILTER_SANITIZE_STRING is deprecated, you should stop using it, and you don't need that sort of filter in this context anyway.
if (isset($_POST["dbselect"])) {
$_SESSION["dbselect"] = $_POST["dbselect"];
}

Pull and post data from MySQL using dropdown menu

I'm a complete newbie in php & MySQL
Basically what I want to do is be able to retrieve data from a table
in MySQL database and put it in a drop down menu .
After I fill in the other fields I want to data from the drop down menu to be written to another table in the same database .
This is my insert.php file
<?php
#### INSERTS A SINGLE CUSTOMER IN Company-->Customer Database with UTF8 Change for special German Characters - Cyrilic Doesnt work - Other change then utf8 ???
#### Getting Data from Index.php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "company";
//making an array with the data recieved, to use as named placeholders for INSERT by PDO.
#### Getting DAta from Index.php
$data = array('CustomerName' => $_POST['CustomerName'] , 'Address1' => $_POST['Address1'], 'Address2' => $_POST['Address2'], 'City' => $_POST['City'], 'PostCode' => $_POST['PostCode'], 'CountryID' => $_POST['CountryID'], 'ContactName' => $_POST['ContactName'], 'ContactEmail' => $_POST['ContactEmail'], 'ContactPhone' => $_POST['ContactPhone'], 'ContactFax' => $_POST['ContactFax'], 'Website' => $_POST['Website']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); ### Database Connect with Special characters Change
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query with named placeholders to avoid sql injections
$query = "INSERT INTO customer (CustomerName, Address1, Address2, City, PostCode, CountryID, ContactName, ContactEmail, ContactPhone, ContactFax, Website )
VALUES (:CustomerName, :Address1, :Address2, :City, :PostCode, :CountryID, :ContactName, :ContactEmail, :ContactPhone, :ContactFax, :Website )";
//statement handle $sth
$sth = $dbh->prepare($query);
$sth->execute($data);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$dbh = null;
?>
And this is the source from the html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New Product</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="CustomerName">CustomerName:</label>
<input type="text" name="CustomerName" id="CustomerName">
</p>
<p>
<label for="Address1">Address 1:</label>
<input type="text" name="Address1" id="Address1">
</p>
<p>
<label for="Address2">Address 2:</label>
<input type="text" name="Address2" id="Address2">
</p>
<p>
<label for="City">City:</label>
<input type="text" name="City" id="City">
</p>
<p>
<label for="PostCode">Post Code:</label>
<input type="text" name="PostCode" id="PostCode">
</p>
<p>
<label for="CountryID">Country ID:</label>
<input type="text" name="CountryID" id="CountryID">
</p>
<p>
<label for="ContactName">Contact Name:</label>
<input type="text" name="ContactName" id="ContactName">
</p>
<p>
<label for="ContactEmail">Contact Email:</label>
<input type="text" name="ContactEmail" id="ContactEmail">
</p>
<p>
<label for="ContactPhone">Contact Phone:</label>
<input type="text" name="ContactPhone" id="ContactPhone">
</p>
<p>
<label for="ContactFax">Contact Fax:</label>
<input type="text" name="ContactFax" id="ContactFax">
</p>
<p>
<label for="Website">Website:</label>
<input type="text" name="Website" id="Website">
</p>
<input type="submit" value="Add Records">
</form>
</body>
</html>
So I wanna add this php code that pulls out the country list and prefixes for the phone numbers and then when I hit the submit button the actual output of the drop down menu to we written in the customers table
<p>
<label for="CountryID">Country:</label>
<?php
$servername = "localhost";
$username = "root";
$password ="";
$dbname = "company";
$con_qnt = mysqli_connect($servername, $username, $password, $dbname);
if(!mysqli_connect("localhost","root",""))
{
die('oops connection problem ! --> '.mysqli_connect_error());
}
if(!mysqli_select_db($con_qnt, "company"))
{
die('oops database selection problem ! --> '.mysqli_connect_error());
}
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='label'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryName' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
<name="CountryID" id="CountryID">
</p>
I don't even know if this is doable - I searched for long time but couldn't find anything that is kind of what I need . Mostly I found hard coded html dropdown menus . In fact hard coding this will work for the countries but it wont work if I want it to be able to show lets say products in a drop down menu . Thank you all in advance .
Hi I just made a quick sample to answer your question on how to populate dropdown using data from database.
In this example, I used
JQuery's AJAX Function
so first, for the backend, (this is just a quick sample to select data. Do not use this as a pattern for your future codes
<?php
$dbh = new PDO("mysql:host=localhost;dbname=dbhelp", 'root', 'pup');
$stmt = $dbh->prepare("SELECT * from t_country");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
?>
I repeat. This is just for quick reference. Do not use it as a pattern for your code.
So using that code, we have now selected data from our table country and usedjson_encode to make it in json format. read more about this here. http://php.net/manual/en/function.json-encode.php.
Next one is the frontend(HTML part)
<body>
// empty dropdown button to be filled by data from database
<select id="country">
</select>
//include the jquery library
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax ({
url : 'dropdown_database.php', // the url from which the data will be pulled
success: function(data) {
var country = $.parseJSON(data); // parse the json format data
$.each(country, function(i, d) {
$('#country').prepend('<option>'+ d.country +'</option>'); // this one adds the <option></option> tag in the dropdown
});
}
});
});
</script>
If I got you right, you want to replace this:
<p>
<label for="CountryID">Country ID:</label>
<input type="text" name="CountryID" id="CountryID">
</p>
With a dropdown so you can quickly pick the country from the dropdown instead of memorizing the ID for each individual country. And to create the select you are using this code:
<p>
<label for="CountryID">Country:</label>
<?php
// some code here that I removed to avoid noise
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='label'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryName' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
<name="CountryID" id="CountryID">
</p>
That should work fine... after you fix some issues:
If you want to replace the input with the select, the select should have the same name as the input so the value is processed automatically. Right now the select has "label" as the name and there is a strange (and incorrect) name tag. To fix this:
Get rid of the unnecessary name tag.
Replace the name attribute in the select with value "CountryID":
echo "<select name='CountryID'>";
The option value should be the country ID so, unless the ID is the country name (not the best choice), you are not using the right value. Change that line too:
echo "<option value='" . $row['CountryID' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
(Considering CountryID as the ID, replace it for the right column name).
And I think with those two changes, the rest of the code should work just fine with insert.php that wouldn't require any updates at all. Finally it would look something like this:
<p>
<label for="CountryID">Country:</label>
<?php
// some code here that I removed to avoid noise
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='CountryID'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryID' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
</p>

Can't display data in my php sessions

I'm having a problem with my sessions forms. It's probably a simple answer but I can't seem to figure it out.
My html:
<body>
<h1>Hobby Selection Page<br /></h1>
<form method="post" action="page1.php" id="hobbies" >
<p>
<label for="Name">Name: </label>
<input type="text" id="name" name="name"/>
</p>
<p>What is your favorite thing to do?<br/>
<select name="hobby">
<option value="movies">Movies</option>
<option value="read">Reading</option>
<option value="music">Music</option>
<option value="other">My hobby is not listed here</option>
</select>
<br/><br/>
<input type="submit" value="Submit Form"/> <input type="reset" value="Clear Form"
/>
</p>
</form>
</body>
First php page (page1.php):
<?php
session_start();
echo 'Click the link below';
$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";
// Second page
echo '<br />page 2';
?>
Second php page (page2.php):
<?php
// page2.php
session_start();
echo 'Your favorite activity:<br />';
echo $_SESSION['name'];
echo $_SESSION['hobby'];
echo '<br />page 1';
?>
My aim is to input data from the first html page and then send it to the first php page (to recieve the session variables) and then to be directed to the second php page where it should retrieve the session variables and display the input data I have entered/selected. I am able to get the html and php pages to display and be linked from one page to the next but I am unable to display (in first php page) the data I have inputted from the html page.
your first page1.php should be like this.
<?php
session_start();
echo 'Click the link below';
$_SESSION['name'] = $_POST['name'];
$_SESSION['hobby'] = $_POST['hobby'];;
// Second page
echo '<br />page 2';
?>
You are not getting data because you are storing string in $_SESSION not the text you entered in fields.
In page1.php
Replace
$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";
By
$_SESSION['name'] = $_POST['name'];
$_SESSION['hobby'] = $_POST['hobby'];
You're missing a few things. First give your submit button a name, like this:
<input type="submit" value="Submit Form" name="my_submit" />
Then, on page1.php, change this:
$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";
To something like this:
// Check if form was submitted. If so, get inputs.
if (isset($_POST['my_submit'])) {
$_SESSION['name'] = $_POST['name'];
$_SESSION['hobby'] = $_POST['hobby'];
}
That should get you started in the right direction. Later, you can add some validation to ensure that $_POST['name'] and $_POST['hobby'] are filled in correctly before assigning them to the $_SESSION

Php Undefined index, when storing a variable

Problem: Need to store field value when doing this query on my database. Have a couple pages that's using this same syntax but for some odd reason this isn't cooperating..
HTML
<form method="post" action="listPage.php">
<fieldset>
<legend>Pull some data</legend>
<label for="name">Name</label>
<input type="text" name="name" id="name" maxlength="255" />
<hr />
<br />
<input type="submit" value="find event" />
</fieldset>
</form>
listPage.php
<?php
//CONNECT TO DATABASE
$user="root";
$password="";
$database="db";
$connection=mysql_connect('localhost',$user,$password);
#mysql_select_db($database) or die( "Unable to select database");
echo "NOT running...";
//STORE ALL DATA FROM PREVIOUS FORM
if (isset($_POST['name'])) {
$name = mysql_real_escape_string($_POST['name']);
$query="SELECT event FROM events WHERE event='$name'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
echo "running...";
while ($row = mysql_fetch_array($result))
{
echo $row['event'] . " // ";
echo "<br />";
}
}
mysql_close($connection);
?>
Check to see if the post value is set before doing anything with it. (Also, don't forget to call mysql_real_escape_string() on it).
It may not be set if this code occurs on the page when it initially loads or is refreshed after having data posted to it.
// Don't attempt any of this unless you actually have a $_POST value
if (isset($_POST['name'])) {
$name = mysql_real_escape_string($_POST['name']);
$query="SELECT event FROM events WHERE event='$name'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
while ($row = mysql_fetch_array($result))
{
echo $row['event'] . " // ";
echo "<br />";
}
}
I couldn't quickly find any documentation regarding possible reserved words for POST or html form variables, so I went to
http://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_form_method_post
and changed fname field to name, (clicked edit and click me button) and the POST variable was not passed or recognized.
So you might consider changing the name of your field to something other than name.

HTML/PHP Survey not passing to MySQL database properly

I'm trying to make a small survey that populates the selections for the dropdown menu from a list of names from a database. The survey does this properly. I want to submit the quote the user submits with this name into a quote database. The quote text they enter into the field goes in properly, however, the name selected from the menu does not get passed in. Instead I get a blank name field.
I understand some of my code is out of context, but the name is the only thing that does not get passed in properly.
On form submit, I include the php file that submits this data to the database:
<form action="<?php $name = $_POST['name']; include "formsubmit.php";?>" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<input type="submit" value="Submit!" />
</form>
The variable $name comes from this (which populates my dropdown menu):
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
echo "</select>";
And here is my formsubmit.php:
<?php:
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
header("Location: quotes.php");
if (#mysql_query($sql)) {
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
Your form action stuff looks weird, but regardless, I think the problem you're having has to do with not setting $name = $_POST['name'] like you're doing with $quotetext = $_POST['quotetext']. Do that before the sql statement and it should be good to go.
edit to try to help you further, I'll include what the overall structure of your code should be, and you should tweak it to fit your actual code (whatever you're leaving out, such as setting $query for your name options):
file 1:
<form action="formsubmit.php" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<select name='name'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
?>
</select>
<input type="submit" value="Submit!" />
</form>
formsubmit.php:
<?php
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$name = $_POST['name'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
$nyme = htmlspecialchars($temp['name']);
echo "<option value='$nyme'>$nyme</option>";
}
echo "</select>";-
This way you will receive the value of the name in $_POST array
and you have to get that value out of $_POST array as well you need to change the
code add the following line to get the name in your script.
$name = $_POST['name'];
you need to change the form action tag
<form action='formsubmit.php' .....>
and in that file after successful insertion you can redirect the user to whereever.php.
so it was fun explaining you every thing bit by bit change this now in your code as well.
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}

Categories