I have a problem with my PHP form. Whenever I refresh the page, the old data automatically inserted to my database. My codes are:
<?php
if(isset($_GET['send'])){
isset($_GET['name'])?$name = $_GET['name']:"";
isset($_GET['score'])?$score = $_GET['score']:0;
$con = mysql_connect('localhost','root','') or die(mysql_error());
mysql_select-db('student',$con) or die(mysql_error());
$qry = mysql_query('INSERT INTO student(name, score) VALUES('$name', $score)') or die(mysql_error());
$display = mysql_query('SELECT * FROM student',$con) or die(mysql_error());
echo '<table border=1>';
while($rows = mysql_fetch_array($display)){
echo '<tr>';
echo "<td>$rows['id']</td>";
echo "<td>$rows['name']</td>";
echo "<td>$rows['score']</td>";
echo '</tr>';
}
echo '</table>';
}
?>
please help me solve this problem.
A common way to prevent duplicate form submission is to make use of the Post/Redirect/Get Pattern.
You would need to change your forms method to Post then. After successful form submission you redirect to the form again but making the redirect a get request. The form will be reset then (empty values).
Edit:
Now as I see it, your script can actually do something similar: After insertion into the mysql Database you can redirect it to itself removing the get parameters:
<?php
if(isset($_GET['send'])){
isset($_GET['name'])?$name = $_GET['name']:"";
isset($_GET['score'])?$score = $_GET['score']:0;
$con = mysql_connect('localhost','root','') or die(mysql_error());
mysql_select-db('student',$con) or die(mysql_error());
$qry = mysql_query('INSERT INTO student(name, score) VALUES('$name', $score)') or die(mysql_error());
header('Location: myscriptsurl.php');
exit;
}
$display = mysql_query('SELECT * FROM student',$con) or die(mysql_error());
echo '<table border=1>';
while($rows = mysql_fetch_array($display)){
echo '<tr>';
echo "<td>$rows['id']</td>";
echo "<td>$rows['name']</td>";
echo "<td>$rows['score']</td>";
echo '</tr>';
}
echo '</table>';
?>
So you have a problem.
And since you cannot avoid a refresh of the screen...
If you are doing a form post, you might consider sending a location
header AFTER you inserted the record:
<form action="process.php" method="POST">
<input type="text" name="number">
<input type="sumbit">
</form>
then from process.php:
// do you usual inserts in the database based on the post
header("Location: http://www.example.com/thanks.php");
// do not forget the exit, since your script will run on without it.
exit;
In that way your script will process the posting, and then redirects the
browser to thanks.php.
A reload of thanks.php will not result in a fresh db insert.
U have used GET method so every time page refresh it will fetch the value from URL.
Try using POST method...It will solve your Problem and don't forget to Put Condition for POST
if(isset($_POST))
{
/* Your Insert Code */
}
Related
Im writing a page in HTML and PHP that connects to a Marina database(boats,owners etc...), displays all of the owners last names in a drop down list and then displays all the boats under the last name that was chosen.
here is my relevant code...
$sql = 'select LastName from Owner';
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$values[] = array(
'LastName' => $row['LastName']
);
}
echo '<form align="left" top="200" action="page2.php" method="post">
<p>Select an owner:</p>
<select top="200" name="form1" id="form1">';
foreach($values as $v){
echo '<option value="'.$v['LastName'].'">'.$v['LastName'].'</option>';
}
echo '</select>
<input type="submit" value="Submit">
</form>';
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql = 'select BoatName from MarinaSlip,Owner where MarinaSlip.OwnerNum = Owner.OwnerNum and Owner.LastName = '.$form1;
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values[] = array(
'BoatName' => $row['BoatName']
);
}
echo '<ol>';
foreach($values as $v){
echo '<li>'.$v.'</li>';
}
echo '</ol>';
}
I have managed to properly display the last names in the drop down list and keep the name chosen as a variable but I am running into a few errors that I cannot solve.
1) when I attempt to reload the page(using Firefox) I get a message "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier" So i was wondering how I could code it so that I don't need to have data being sent initially.
2)After a last name is submitted and I attempt to run a query to match all the boats under that last name I get an error that the $result variable is not a MYSQLI result type even though I used the same code earlier in the script.
I am new to HTML and PHP so any help is greatly appreciated.
That message happens when you reload a page that was the result of a form submission. It means it has to resubmit the form to reproduce the same result. The way to prevent it is to have the form redirect the user to a page that displays the result, rather than displaying the result itself. This can be complicated unless the form submission just makes a change to the database, and then you want to display the contents, rather than display something dependent directly on the form submission.
You need to put quotes around the name:
$sql = 'select BoatName from MarinaSlip,Owner where MarinaSlip.OwnerNum = Owner.OwnerNum and Owner.LastName = "'.$form1.'"';
But it would be better to use a parametrized query. See How can I prevent SQL injection in PHP?
I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.
Notice: Undefined index: perm_tipo in C:\xampp\htdocs\admin_reg_usuario.php on line 6
I get this error from my PHP page where is supposed to receive a value from a
html select form, I send this info with POST, this is the code from my select:
<select name="perm_tipo">
<?php
$con=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("test",$con) or die(mysql_error());
$sql = "SELECT id_permiso,tipo_permiso FROM cat_permisos";
$rs = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($rs)){
echo "<option value='".$row["id_permiso"]."'>".$row["tipo_permiso"]."</option>";
}
mysql_free_result($rs);
mysql_close($con);
?>
</select>
and another php page to use the values I use this
$permiso = $_POST['perm_tipo'];
I'm not quite sure what I'm doing wrong, the syntax and name are fine.
EDIT: now is working,the var_dump($_POST); code made it work??, =S
Okay so you're submitting the form to the same PHP page.
That means when you first visit the page, $_POST is empty. After you click submit $_POST is populated when the form is sent to the same page with perm_tipo.
What you need to make sure is that $_POST is sent to your PHP page with isset. This will detect when your form is submitted. This will also not execute the code when $_POST is empty which is why you get that "Notice:" error.
<?php
if (isset($_POST['perm_tipo']))
{
$con=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("test",$con) or die(mysql_error());
$sql = "SELECT id_permiso,tipo_permiso FROM cat_permisos";
$rs = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($rs)){
echo "<option value='".$row["id_permiso"]."'>".$row["tipo_permiso"]."</option>";
}
mysql_free_result($rs);
mysql_close($con);
}
?>
I have a form page in which either an INSERT or an UPDATE query is submitted, depending on the presence/absence of an ID (and when there's an ID it's used to retrieve the record and pre-populate the form). In either case, the processing is in form.php so the form's action is itself (action="/form.php">). My problem is that when form.php reloads post-submit, the URL has an empty ID so the page enters 'INSERT' mode, rather than 'UPDATE' mode. What's the best practice way to resolve this?
What operator/condition should I add to this 'if' ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
... to include post-submit empty ID URL (i.e., form.php?ID=)
OR,
How do I pass `$newID = mysql_insert_id();1 to the form's action? (I've tried a number of variations here w/out success)
$newID = mysql_insert_id();
... [ snip ] ...
<form method="post" action="/html/form.php?ID=<?php echo $newID; ?>">
I'm reading about hidden inputs and sessions but it's not yet clear to me how to use either to solve this problem. Lastly, since it isn't absolutely necessary that I reload the form page, I'm increasingly tempted to move the form processing/db queries to another page (e.g., process.php) to hopefully simplify; any opinions on this? What's best/common practice?
Many thanks in advance,
svs
Common practice should be to keep data posting separate from data displaying. This prevents accidental adds on a user's first arrival to the page as well as accidental double-posts if the user hits refresh.
In addition, keeping the logic separate makes the code more readable and maintainable in the future.
The approach you should probably look for is:
view.php?ID=<record to view> // Only displays a record already in the DB
add.php // The add record form with action="process_add.php"
process_add.php?Field1=<>&Field2=<>... // Receives data from add.php, puts it in
// the database and then forwards back to
// view.php or add.php as you see fit.
EDIT: While I have GET arguments on process_add.php, they are only there to demonstrate that they are being passed. They should be sent as POST arguments in and actual implementation.
here is an example of such a code, using templates.
working CRUD application based on the idea of passing id
dunno, though, why do you need to pass freshly generated id.
<?
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
$name = mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE $table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO $table SET name='$name'";
}
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) { //listing part:
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
include 'list.php';
} else { // form displaying part:
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
?>
templates:
form.php
<? include TPL_TOP ?>
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
<? include TPL_BOTTOM ?>
and list.php:
<? include TPL_TOP ?>
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
<? include TPL_BOTTOM ?>
not sure how feasable this is, but I have just rolled my own user search form, which simply queries my database and returns all the results with any given username, or similar using the LIKE 'some_username%' statement.
My search works great, and im really chuffed with myself as I am a php and mysql novice.
I used a mysql_fetch_assoc($result) statement, and then used a while loop to echo out each row from the database into an html table.
What I would then like to be able to do, is select a record from the table, and open a new page, which is populated with all the fields for that record, which I can then use to edit and update the user settings.
I thought perhaps one way to do it, is to perhaps echo out a form instead? that way I can have a button next to each row, to post the fields into some php code on my new page? I thought this may be a bit clunky though, and not sure how I would go about echoeing out a different form for each row.
Don;t know if anyone had any ideas on the best way to do this? If you need any code examples of what im working with, I can post them here.
Thanks very much!!
Eds
not a form but a hyperlink.
I wonder why you aren't familiar with this way of opening new pages as it is used everywhere.
just create a hyperlink
name
here is a sketch example of such an application, editing only one field, but you can add any number as well:
a main script:
<?
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
$name = mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE $table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO $table SET name='$name'";
}
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) { //listing part:
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
include 'list.php';
} else { // form displaying part:
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
?>
and two simple templates responsible for output,
one for the displaying the form, form.php
<? include TPL_TOP ?>
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
<? include TPL_BOTTOM ?>
and one to display the list, list.php
<? include TPL_TOP ?>
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
<? include TPL_BOTTOM ?>
always start php like this <?php, usually php manual configuration do not support short tag like this <?.
for hyperlink just use view record
It is just query string and get id on next page like this
$id = $_GET['id'];
Hope u will understand..