I have a web-based form that accepts student information. After I've Inserted data I want it to be still available even if I refresh the browser It would mean that 2 rows are the same but I dont want to insert the same data again. How can this be possible?
My code are here:
<form method="post" action="insert.php" >
<table>
<tr>
<td width="22%"> Name</td>
<td width="4%"></td>
<td width="74%"><input type="text" name="name" > </td>
</tr>
<tr>
<td>Information </td>
<td></td>
<td><input type="text" name="infomn" ></td>
</tr>
<tr>
<td>Email </td>
<td></td>
<td><input type="text" name="email" ></td>
</tr>
<tr>
<td>Password </td>
<td></td>
<td><input type="password" name="password" ></td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td></td>
<td></td>
<td ><input type="submit" name="submit" value="Insert" >
</td>
</tr>
</table>
</form>
insert.php:
include("connect.php");
if($_POST['submit']){
$name=$_POST[name];
$info=$_POST[infomn];
$emal=$_POST[email];
$password=$_POST[password];
$query = "insert into student(name,designation,email,password) values('$name','$info','$emal','$password')";
mysql_query($query) or die("not successfully insert".mysql_error());
?>}
I would check if your values have been filled before attempting to insert your data.
if ($_POST['name']) {
//Validate, escape, insert...
} else {
//Display form...
}
Please please please make sure the data you insert into the database is escaped, especially if you're working with student data.
At the moment it looks like this:
Info is posted to insert.php
You are located in insert.php and the variables posted exist aswell.
The database execution is performed with the existing data.
You refresh.
You never really leave the page because the refresh makes you go to the same page, so the browser assumes that the posted data should not be deleted but used again.
To avoid this, you must add
header("Location: index.php");
Or some similar code, to make sure that the user won't stay on the same page after the database execution is performed.
insert.php:
include("connect.php");
if(isset($_POST['submit'])) { // put isset() for checking if it submitted or not
$name=$_POST['name'];
$info=$_POST['infomn'];
$emal=$_POST['email'];
$password=$_POST['password'];
$query = "insert into student(name,designation,email,password)
values('$name','$info','$emal','$password')";
if(mysql_query($query)) {
header('Location:your_form_page.php'); // redirect to avoid inserting data while refreshing
}else {
mysql_error() };
}
recommendation : Try use PDO How can I prevent SQL injection in PHP?
Browser refresh posts the last action (again) to the server.
Use the Post/Redirect/Get pattern (http://en.wikipedia.org/wiki/Post/Redirect/Get) i.e. redirect always after successful action (in your case database insert).
Related
The page is basically a form for adding new products to the products table in the database. The form must include image upload as well. The function is supposed to echo the query before inserting any data to the database. However, every time I press on the submit button it doesn't show the query, and the form just resets itself. I tried different solutions, yet they don't work. I changed the form action to a new php page, and still not working. I also tried to use two different browsers, and tried display error codes. Is there something messing in the code?
<!DOCTYPE>
<?php
include("../includes/db.php");
?>
<html>
<head>
<title>Insert a Product</title>
<script src="//tinymce.cachefly.net/4.3/tinymce.min.js"></script>
<script>tinymce.init({selector:'textarea'});</script>
</head>
<body>
<form name="submit" action="insert_product.php"method="POST"enctype="multipart/from-data">
<table align="center" width="800">
<tr align="center">
<td colspan="8"><h4>Insert New Post Here</h4></td>
</tr>
<tr>
<td align="right"><b>Product Title:</b></td>
<td><input type="text" name="pro_name" /></td>
</tr>
<tr>
<td align="right"><b>Product Price:</b></td>
<td><input type="text" name="price"/></td>
</tr>
<tr>
<td align="right"><b>Product Image:</b></td>
<td><input type="FILE" name="product_image" id="product_image"/></td>
</tr>
<tr>
<td align="right"><b>Product Color:</b></td>
<td><input type="text" name="Color"/></td>
</tr>
<tr>
<td align="right"><b>Product Location:</b></td>
<td>
<select name="location">
<option>Select a Location</option>
<?php
$get_location = "select * from location";
$run_location = mysqli_query($conn, $get_location);
while ($row_location=mysqli_fetch_array($run_location)){
$Loc_name = $row_location['Loc_name'];
$location_id = $row_location['location_id'];
echo "<option value='$location_id'>$Loc_name</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="right"><b>Product Supplier:</b></td>
<td><input type="text" name="pro_supplier"/></td>
</tr>
<tr>
<td align="right"><b>Product Cost:</b></td>
<td><input type="text" name="cost"/></td>
</tr>
<tr>
<td align="right"><b>Product Keywords:</b></td>
<td><input type="text" name="pro_keywords"/></td>
</tr>
<tr>
<td align="right"><b>Product Description:</b></td>
<td><textarea name="Pro_desc" cols="20" rows="10"/></textarea></td>
</tr>
<tr align="center">
<td colspan="7"><input type="submit" name="submit" value="Insert Product Now"/></td>
</tr>
</form>
</body>
</html>
<?php
if (isset($_POST['submit']) && isset($_FILES['product_image'])){
$pro_name = $_POST['pro_name'];
$price = $_POST['price'];
$Color = $_POST['Color'];
$cost = $_POST['cost'];
$pro_desc = $_POST['pro_desc'];
$pro_keywords = $_POST['pro_keywords'];
$product_image = $_FILES['product_image']['name'];
$product_imgtmp = addslashes (file_get_contents($_FILES['product_image']['tmp_name']));
echo $insert_product =
"insert into products
(pro_name, price, Color, cost, Pro_desc, pro_keywords, product_image)
VALUES
('$pro_name','$price','$Color','$cost','$pro_desc','$pro_keywords','$product_image')";
if ($conn->query($insert_product) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $insert_product . "<br>" . $conn->error;
}
}
?>
Edit: After going through the code again and with an even finer tooth comb, have noticed a few more errors. Consult my Edit: also below.
Firstly, have you a typo here, being from instead of form:
enctype="multipart/from-data"
^^^^
which should have read as:
enctype="multipart/form-data"
^^^^
Then your <form name="submit"> and submit button <input type="submit" name="submit" both bear the same name attribute of submit.
Remove name="submit" from <form>, that's a conflict.
Having added an else{ echo "Something went wrong..."; } to your conditional statement would have fallen into it from the get go.
Error reporting would have also helped you out here.
http://php.net/manual/en/function.error-reporting.php
Now, whatever is inside db.php is unknown to us. Since you're using the MySQLi API to query with, the connection for it must be the same one, mysqli_ and not mysql_ or PDO, should that be the case.
Different MySQL APIs do not intermix.
"However, every time I press on the submit button it doesn't show the query"
Your conditional statement:
if (isset($_POST['submit'])
&& isset($_FILES['product_image']))
is checking if both the submit is pressed AND-&& the file is set.
You may want to use an || (OR) here instead, if that file is ever "not set/empty".
For user provided input, use a conditional !empty(), it's better.
So, make sure that both conditions are met.
That could be changed to:
if ( isset($_POST['submit']) ){
// do something in here
if( !empty($_FILES['product_image']) ){
// do something else in here
}
else{
// you can do stuff here too for an empty file condition
}
}
HTML stickler:
<!DOCTYPE> isn't a proper doctype declaration, and should read as <!DOCTYPE html> as a minimum HTML5-supported method.
Otherwise, consult the following for all valid types:
https://www.w3.org/QA/2002/04/valid-dtd-list.html
Footnotes:
Your present code is open to an SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Edit:
Upon looking further at your code:
<textarea name="Pro_desc" and $_POST['pro_desc']. Notice the uppercase P in the name attribute?
Those POST arrays are case-sensitive and again; error reporting would have thrown you something about it, being undefined index pro_desc.
It should read as:
$_POST['Pro_desc']
Pro tip: Use the same letter-case convention throughout your code. You can quickly get lost into using mixed case variables and they are case-sensitive. My preference has always been to use all lowercase letters for variables, arrays, etc.
Be careful with that.
Plus, if you're attempting to insert the uploaded file in your database as binary, you will need to escape that data with mysqli_real_escape_string() and setting your column as BLOB or LONGBLOB, depending on the size of the file.
Also make sure that there isn't an file upload constraint size restriction.
Rerences:
http://dev.mysql.com/doc/en/blob.html
http://php.net/manual/en/mysqli.real-escape-string.php
PHP change the maximum upload file size
http://php.net/manual/en/ini.core.php
http://php.net/manual/en/features.file-upload.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
1st create spaces at the form code:
<form name="submit" action="insert_product.php" method="POST" enctype="multipart/from-data">
Then on your PHP code do not echo the operation i.e.
Change this
echo $insert_product =
"insert into products
(pro_name, price, Color, cost, Pro_desc, pro_keywords, product_image)
VALUES
('$pro_name','$price','$Color','$cost','$pro_desc','$pro_keywords','$product_image')";
to this
$insert_product =
"insert into products
(pro_name, price, Color, cost, Pro_desc, pro_keywords, product_image)
VALUES
('$pro_name','$price','$Color','$cost','$pro_desc','$pro_keywords','$product_image')";
echo $insert_product;
I have an php form utilizing several inputs that is driving a kiosk page. If a text input is blank I want this update a separate input with the word "hidden" If there is text I would like the word "visible" to show. Currently my code works if you click submit twice but will not work on the first submit. Here is my current code:
The if function that is current working on second submit:
if (strlen($something)>0) {
$_POST['someone'] = "visible";
} else {
$_POST['someone'] = "hidden";
}
input form:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>something : </td>
<td><input type="text" id="something" name="something" value="<?php echo htmlspecialchars($something); ?>"/></td>
<td></td>
</tr>
<tr>
<td></td>
<td><?php echo $_SERVER['PHP_SELF']; ?></td>
<td></td>
</tr>
<tr>
<td>someone:</td>
<td><input type="text" id="someone" name="someone" value="<?php echo htmlspecialchars($someone); ?>"/></td>
<td></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name='submit' value="Submit"/></td>
<td></td>
</tr>
</table>
</form>
Here is the update code:
$usql = "UPDATE test SET something= '".$_POST['something']."', someone= '". $someone ."' WHERE ID='a';";
Currently the "someone" input has a display of none so it cannot be seen by the user. This is not necessary but if someone could tell me how to bypass adding an input altogether and tweak the update statement itself to update something that would be great as well! Thanks!
Any help would be appreciated!
Using session variables can save the page state, even after reload.
First page save:
session_start();
$_SESSION['someone'] = $_POST['someone'];
Then:
if(isset($_SESSION['someone']))
{
if (strlen($_SESSION['someone'])>0) {
$_POST['someone'] = "visible";
} else {
$_POST['someone'] = "hidden";
}
}
I've been working on my website's database and I had this problem recently:
I want the user to read a field of a row, when another field of the same row is submitted.
I.e:
user_id=1 user_name=Fran user_pass=Potato referedby_id=0 referedby_name=empty
When going inside www.website.com/form.php?referedby_id=1
I want the user to see "So, Fran refered you?"
I've been learning php and I decided to try this:
$referedbyid = mysqli_real_escape_string($con,$_POST["referedby_id"]); //In this case it's 1 because of the url
$sel_referedbyname = "select user_name from users where user_id='$referedbyid'"; //Then this should be the select of the user_name "Fran"
$run_referedbyname = mysqli_query($con, $sel_referedbyname); //Then a query for that select
$check_referedbyname = mysqli_fetch_field($run_referedbyname); //And this one the content of the query's result
$refername = $check_refername->user_name; //As the query result is an object I want to convert it to text
if(isset($_POST["register"]) && $check_user == 0 && $check_email == 0 && $pass == $pass2){ //If everything is right and the user/email does not already exist
mysqli_query($con,"INSERT INTO users (user_name, user_email, user_pass, refer_id, refer_name) VALUES ('$user', '$email', '$pass', '$referid', '$refername')"); //It's submitted to the database with the other values.
mysqli_close($con); //And we finish the connection with the db.
The problem is that when I try this and check the database, the referedby_name field is empty. Is it a syntax error? Or is this because it didn't convert to text properly?
In case $referedbyname is not text, how can I convert it properly? Is this because I'm using the fetch_field function wrong?
Additional info: $referedbyid is being called properly (I think) in a POST form with this html
<form action="register.php" method="post" onsubmit="validate();">
<table width="500" align="center" bgcolor="skyblue">
<tr align="center">
<td colspan="3"><h2>Registrarse</h2></td>
</tr>
<tr>
<td align="right"><b>Nombre de usuario:</b></td>
<td><input type="text" name="user" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Email:</b></td>
<td><input type="email" name="email" required="required"/></td>
</tr>
<tr>
<tr>
<td align="right"><b>ContraseƱa:</b></td>
<td><input type="password" id="pass" name="pass" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Verificar contraseƱa:</b></td>
<td><input type="password" id="pass2" name="pass2" required="required"/></td>
</tr>
<tr align="center">
<td colspan="3">
<input type="hidden" name="referedby_id" value="<?php echo $_GET["referedby_id"]; ?>"/>
<input type="submit" name="register" value="Registrarse"/></td>
</tr>
</table>
</form>
I don't know why the downvotes, I tried to be as clear and specific as I could...
Anyways, if someone else has any trouble finding the value of a specific field just use mysqli_fetch_assoc(mysqli_query($conect, $select))['name of the sql field']
mysqli_fetch_field($result) will only show you information about the field, like the type of input, name of the table, name of the column, etc.
Hope that's useful for someone with the same issue. Bye.
I'm not in a very good level in php coding. i have a php interface(code: insert.php) which has four forms that are used to enter data to four different tables in my database and data entry to the forms are independent from each other. but, when i enter data to a form, it results in "undefined index error" pointing two variables which are related to another form in the interface. and also, data is not entered to the table in the database. not all the forms cause this error.they work fine.
this is the code of 'insert.php' the form i need data to be inserted.
<form method="post" action="input.php">
<tr>
<td>ID</td>
<td><input type="text" name="cat_id" size="40">
</td>
</tr>
<tr>
<td>Description</td>
<td>
<textarea NAME="desc" COLS=31 ROWS=6></textarea>
</td>
</tr>
<tr>
<td>
</td>
<td align="right">
<input type="submit" name="submit" value="Done">
</td>
</tr>
this is the code in 'insert.php', the error variables related to.
<form method="post" action="input.php">
<tr>
<td>ItemID</td>
<td><input type="text" name="item_id" size="40">
</td>
</tr>
<tr>
<td>EPF</td>
<td><input type="text" name="epf" size="40">
</td>
</tr>
<tr>
<td>Quantity</td>
<td><input type="text" name="quan" size="40">
</td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="date" size="40">
</td>
</tr>
<tr>
<td>
</td>
<td align="right">
<input type="submit" name="submit" value="Done">
</td>
</tr>
this is the code in 'input.php'.
<?php
$cat_id=$_POST['cat_id'];
$cat_descr=$_POST['desc'];
$query_cat = "INSERT INTO 'category' ( id, description)
VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
$result_cat = mysql_query($query_cat);
?>
<?php
$item_id=$_POST['item_id'];
$epf2=$_POST['epf'];
$quan=$_POST['quan'];
$date=$_POST['date'];
$query_itemEmp = "INSERT INTO 'emp_div_item' ( epf, item ,quantity, date)
VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
$result_itemEmp = mysql_query($query_itemEmp);
?>
<?php
if( $result_emp || $result_cat || $result_item || $result_itemEmp){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
?>
the variables which the error points out are $quan and $date.. $result_item and $result_emp are query results get from other forms which work fine.please note that users dont need to enter data to all forms at a time. they can chose whatever the number of forms to be filled at a time.
plese help me to solve this problem and thank you in advance.
I think the problem is with the HTML code, you are having two seperate forms :
<form method="post" action="input.php"> ---first one
<form method="post" action="input.php"> --- second one
So when you click on first form's submit, only that form's data will be submitted (here , only cat_id and desc will be available in input.php)
And then you try access other forms values in the same input.php ($item_id=$_POST['item_id']; which is not present with the first form's data.
Hence you get this error.
Also if you will try to submit the second form, the you will get the same error for $cat_id and $cat_descr variables.
So keep all the data in a single form.
As far as your queries concerned: don't put quotes around db identifiers. Use ticks if you need to.
That being said change
$query_cat = "INSERT INTO 'category' (id, description) VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
^ ^
to
$query_cat = "INSERT INTO category (id, description) VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
and
$query_itemEmp = "INSERT INTO 'emp_div_item' (epf, item ,quantity, date) VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
^ ^
to
$query_itemEmp = "INSERT INTO emp_div_item (epf, item ,quantity, date) VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
On a side note: your code in current state vulnerable to sql-injections. Learn and use prepared statements with either mysqli or PDO. mysql_* extension is deprecated and is no longer supported.
I have a small section of code. When the table is empty this code works fine and enters in to the table fine. But then if i try again then this fails with the error?
What am i doing wrong?
Thanks
// On my Function page
function admin(){
connect();
$query = mysql_query("INSERT INTO results
(t_id, pos1, pos2, pos3)
VALUES ('$_POST[t_id]','$_POST[pos1]','$_POST[pos2]','$_POST[pos3]')")
or die ("Error.");
$b = "Updated fine</b></a>.";
return $b;
exit();
}
// Then on my main page
<?php
include ('functions.php');
if (isset($_POST['admin'])){
$admin = admin();
}
?>
<div id="content">
<div id="admin">
<form action="" method="post">
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1">
<tr>
<td width="100%"><?php echo "$admin"; ?></td>
</tr>
<tr>
<td width="100%"><label>Track <input type="text" name="track" size="25" value="<? echo $_POST[t_id]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 1<input type="text" name="pos1" size="25" value="<? echo $_POST[pos1]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 2 <input type="text" name="pos2" size="25" value="<? echo $_POST[pos2]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 3 <input type="text" name="pos3" size="25" value="<? echo $_POST[pos3]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><input class="save" type="submit" value="" name="admin"></td>
</tr>
</table>
</form>
</div>
</div>
Without seeing your table schema, I can only think you have UNIQUE t_id and you want to insert the same ID into it.
Several way to debug:
Use or die ("Error: " . mysql_error()); instead of just or die ("Error.");
Check your table schema: SHOW CREATE TABLE tablename and write it down on your question, so we can see if it's causing error.
It is hard to guess. Maybe you are entering the same values twice, and they happen to violate some unique constraint?
But you make another mistake: you forget to call mysql_real_escape(). That is bad.
Can you tell us of the error? It sounds like you're hitting a primary key violation, perhaps by trying to insert the same id more than once.
That aside, your code is riddled with security holes.
You should not be inserting variables straight from the POST into your query. All I have to do is submit '; DROP DATABASE and I can completely wreck your system.
Additionally, you're injecting values directly from POST into input fields, meaning I can set up a button on my site that submits " <script type='text/javascript'>window.location='http://mysite.com'</script> or something along those lines and take over your page.
This may sound terse, but you should do some googling or pick up a book regarding textbook security issues with websites.
EDIT: Just saw your comment about learning security. My advice is to be proactive about this sort of thing, because being reactive is often too late to fix problems.