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.
Related
I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
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.
I'm trying to do something simple to learn how to do a query and then put the answer into a box. I have a HTML file that looks like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="results.php" method="post">Search: <input name="term" type="text" /><br />
<input name="submit" value="Submit" type="submit" />
<p>Answer: <input name="answer" type="text" /></p>
</form>
</body>
</html>
And the php code is:
<?php
$hostname = 'host.com';
$username = 'ratetable';
$password = 'mypassword';
$term = (int) $_GET['term'];
try
{
$db = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
//echo 'Connected to database<br />';
foreach($db->query('SELECT * FROM rates WHERE mileage<= ' . $term . ' ORDER BY mileage DESC LIMIT 1') as $row) {
echo "<input type='text' name='answer' value='" . $row['ratepermile'] . "'>";
}
}
catch (PDOException $e) {
echo $e->getMessage();
throw($e);
}
?>
So I'm trying to put ratepermile, a field in the database, into the 'answer' text box. What I get is the screen clears, but no form and no result, even after I comment out the 'connected to database' echo line and use something that I know exists in the database.
How can I keep the form on screen and echo to the text box?
Thanks for looking.
Your form is POSTing the data (method="post"), but your PHP script is looking in the $_GET aray.
You need to get the data from $_POST instead.
$term = (int) $_POST['term'];
As well as the above POST issue. If you wish to keep the form on the page and not reload the page you need to look into AJAX.
You can use $_REQUEST in order to avoid these confusions. Whether you use method="post" or method="get", you can fetch the value through this.
I want to show the selected ID data in the form and EDIT it and UPDATE in the database. I selected the data from the database and put it in the input tag but it doesn't work. Please help!
<html>
<body>
<?
$db = mysql_connect("localhost", "root","");
mysql_select_db("db_ncs",$db);
$id = $_GET['s_id'];
if($id)
{
$result=mysql_query("SELECT * FROM tbl_student WHERE s_id=$id");
$row = mysql_fetch_assoc($result);
}
?>
<form method="post" action="update.php">
Name:<input type="Text" name="name" value="<?php echo $row['s_name'];?>" /><br>
Contact:<input type="Text" name="contact" value="<?php echo $row['s_contact'];?>" /><br>
Address:<input type="Text" name="address" value="<?php echo $row['s_address'];?>" /><br>
E-mail:<input type="Text" name="email" value="<?php echo $row['s_email'];?>" /><br>
<input type="submit" name="update" value="Update">
</form>
<?
if(isset($_POST['update']))
{
$name = $_POST['s_name'];
$contact = $_POST['s_contact'];
$address = $_POST['s_address'];
$email = $_POST['s_email'];
$sql = "UPDATE tbl_student
SET (s_name='$name', s_contact='$contact', s_address='$address', s_email='$email')
WHERE s_id=$id";
$res = mysql_query($sql);
if($res)
{
echo "Upadate Successfull!";
}
else
{
echo "Sorry!";
}
}
?>
</body>
</html>
You forgot to pass the id.
Add this between the <form> tags.
<input type="hidden" name="s_id" value="<?php echo $id;?>" />
You also need to make your methods consistent. The form submits the data via method="get" but you ask for it via $_POST. You also need to make the input names consistent with the names you ask for, by either adding or removing the "s_" in the appropriate places.
Not really an answer to your question, but i have to point you to some omissions in your code:
if $_POST['update'] is set, that doesn't mean the other variables are also set. They can be empty if user didn't enter anything in a field. You should check if every $_POST or $_GET variables are set by using isset or empty.
your code is so insecure! You should escape every variable before using it in a query. Use mysql_real_escape_string() for that. I also suggest you to use strip_tags() along with escaping.
In the form you have method="get" but you use $_POST in your PHP code. Try to define your form as below:
<form method="post" action="update.php">
Your SQL query should be (added quotes):
$sql = "UPDATE tbl_student
SET (s_name='$name', s_contact='$contact', s_address='$address', s_email='$email')
WHERE s_id=$id";
Try adding this after mysql_query:
$result = mysql_query($sql) or die(mysql_error());
Do not use mysql_* functions, they are no longer maintained: use PDO of MySQLi.
Doesn't he have to use the $row = mysql_fetch_assoc($result) to get the results?
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
http://php.net/manual/en/function.mysql-query.php
above is just an example.
update:
$result=mysql_query("SELECT * FROM tbl_student WHERE s_id=$id");
$row = mysql_fetch_assoc($result); // I think you have to add this line here, don't you?
?>
<form method="post" action="update.php">
<input type="hidden" name="s_id" value="<?php echo $id;?>" />
Name:<input type="Text" name="name" value="<?php echo $row['s_name'];?>" /><br>
Contact:<input type="Text" name="contact" value="<?php echo $row['s_contact'];?>" /><br>
Address:<input type="Text" name="address" value="<?php echo $row['s_address'];?>" /><br>
E-mail:<input type="Text" name="email" value="<?php echo $row['s_email'];?>" /><br>
<input type="submit" name="update" value="Update">
</form>
update 2:
when you are going to update, the method up there $id = $_GET['s_id']; is still looking for a param called 's_id' will come via HTTP GET, but it doesn't!
a quick workaround may be this,
<form method="post" action="update.php?<?php echo $id;?>">
and don't forget to add,
$id= $_POST['s_id']; after $email = $_POST['s_email'];!
update 3:
Hmm, You still need this <input type="hidden" name="s_id" value="<?php echo $id;?>" /> and don't forget to add,
$id= $_POST['s_id']; after $email = $_POST['s_email'];!
Your form has fields like name="contact", but when you try to get the values you use $_POST['s_contact']. These need to match.
The reason you need the hidden s_id field in the form is so that you will update the same row that was edited. Your UPDATE statement contains WHERE s_id=$id, so you need to get the original id this way. It's hidden because you don't want the user to be able to change the ID when editing.
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>';
}