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;
Related
I need som help - I really cant see where I do the mistake!
I need to below code to remember the variable for loading the next page. The page loads using a link like:
editgallery.php?folder=big_fish&id=459
Now I want the below codes to remember the folder variable: big_fish for generating the next link. In the bottom of the codes I use a "location" to load the next page. It looks like:
header("Location: galleries.php?folder".$folder." ");
It should send the user back to the page they came from when clicking "update" in the form in the below codes:
if(!$_POST["submit"])
{
include "header.php";
$query = mysql_query("select name, type, folder, description , displaydate from galleries where id = '".$_GET["id"]."' ");
$row = mysql_fetch_row($query);
$name = $row[0];
$type = $row[1];
$folder = $row[2];
$description = $row[3];
$displaydate = $row[4];
?>
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>" name="myform" id="myform">
<center><table width="<?=$setting["tablewidth"]?>" class="admintable" cellpadding="<?=$setting["cellpadding"]?>">
<tr>
<td class="adminheader" colspan="2"> <b>Edit Gallery:</b></td>
</tr>
<tr>
<td class="admincell"> Name:</td>
<td class="admincell">
<input type="text" name="name" value="<?=$name?>" size="40"></td>
</tr>
<tr>
<td class="admincell"> Category:</td><td class="admincell">
<?=$folder?>
</td>
</tr>
<tr valign="top">
<td class="admincell"> Display Date:</td>
<td class="admincell" align="">
<input style="border-style:hidden" type="text" value="<?=$displaydate?>" id="from" id="<?php echo $_REQUEST["from"]; ?>" name="displaydate" size="40">
(yyyymmdd - Like <?=date('Ymd');?> or <?=date('Y-m-d');?>)</td>
</tr>
<tr valign="top">
<td class="admincell"> Description: </td><td class="admincell">
<textarea id="Enter you description of the photo set here" name="description"><?=$description?></textarea></td>
<!-- http://ckeditor.com/ -->
<script>
CKEDITOR.replace( 'description' );
</script>
</tr>
<tr>
<td class="admincell" colspan="2"><input type="hidden" name="id" value="<?=$_GET["id"]?>"><center>
<input type="submit" name="submit" value="Update"></center></td>
</tr>
</table></center>
</form><center>
<p>
</table></center>
<?
include "footer.php";
}
else
{
mysql_query("update galleries set name = '".$_POST["name"]."', description = '".$_POST["description"]."' , displaydate = '" . $_POST["displaydate"] . "' where id = '".$_POST["id"]."' ");
header("Location: galleries.php?folder".$folder." ");
//header("Location: galleries.php");
}
Can anyone see why the $folder name from the link is not saved for the location link - why cant the codes "transfer" it from the editgallery.php?folder=big_fish&id=459 link and to the location like: ("Location: galleries.php?folder".$folder." ");
Please advice.
You're missing an equals sign:
header("Location: galleries.php?folder".$folder." ");
should be
header("Location: galleries.php?folder=".$folder." ");
You might want to consider using http_build_query to handle building the URL.
You are vulnerable to SQL injection attacks, and have typos:
header("Location: galleries.php?folder=".$folder." ");
^---missing
Essentially you're generating a link that looks like
galleries.php?folderfoo
instead of
galleries.php?folder=foo
Apart from the missing =, I don't see how you are setting your variable (or database connection...).
You probably want something like:
header("Location: galleries.php?folder=" . $_GET['folder']);
You should also switch to PDO or mysqli and prepared statements as the mysql_* functions are deprecated and you have an sql injection problem.
Edit: Note that when a POST request is made / $_POST["submit"] is set, only the last two lines of the script are executed:
A mysql query without a database connection
A header() call with an undefined $folder variable.
I'm just going to re-write my answer here.
Your code could use some cleanup. Here are some items that I would fix:
<input style="border-style:hidden"
type="text"
value="<?=$displaydate?>"
id="from"
id="<?php echo $_REQUEST["from"]; ?>"
name="displaydate"
size="40">
You have two id's there. No bueno.
<textarea id="Enter you description of the photo set here" name="description"><?=$description?></textarea>
Not really a good idea to have your ID contain spaces. Did you mean to use the title attribute?
<input type="hidden" name="id" value="<?=$_GET["id"]?>">
This is good. And I think this is where your main problem lies. You need to add another hidden input with folder
<input type="hidden" name="folder" value="<?=$_GET["folder"]?>">
This way, when the form is posted, the folder will be sent in the form of $_POST['folder'].
Then, here:
header("Location: galleries.php?folder".$folder." ");
Should become:
header("Location: galleries.php?folder=".$_POST['folder']);
Try that and let us know what happens please.
I seem to have an issue inserting the post values into my database, and i don't see the error in the coding. I've been looking at it for a while now and to me everything looks right, however when i use the form and submit the data the page reload but no data get inserted into the database.
It would be much appreciated if someone could help me identify the error in the coding.
If you have any questions feel free to ask!
Kind regards Jim
FORM
<?php
//Show the form if the user is a Admin
if(isset($_SESSION['username'])){
$username == $_SESSION['username'];
$results = $mysqli->query("SELECT authority FROM users WHERE username='$username' LIMIT 1");
while($row = $results->fetch_object()){
$aut = $row->authority;
}
}
if($aut == 1){
?>
<form action="index.php" method="post">
<table>
<tr>
<td> Title: </td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td valign="top"> News: </td>
<td><textarea name="information"></textarea></td>
</tr>
<tr>
<td> <input type="hidden" value="news"> </td>
<td><input type="submit"></td>
</tr>
</table> <hr>
</form>
MYSQLI
<?php
}
//Insert into the database
if(isset($_POST['news'])){
$title = $_POST['title'];
$information = $_POST['information'];
$mysqli->query("INSERT INTO `news` (`title`, `information`) VALUES ( '".$title."', '".$information."')");
}
<input type="hidden" value="news"> should be <input type="hidden" name="news">
That's why isset($_POST['news']) will never be true.
Beside that silly typo problem your code suffers from two real disasters.
You have no error reporting, which renders you helpless against such silly mistakes
You are adding your data directly into query, while ought to use placeholders for that.
I am not sure what was intended with the backticks and periods in your original query. In my limited experience my queries take the form of:
$mysqli->query("INSERT INTO news(title, information) VALUES ('$title', '$information')");
I would say that priority #1 is getting some debugging information in the form of return values for your php functions or access to php error logs.
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 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).
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.