I am working on a project to upload images into a directory and store image paths in database table. The image upload work fine but my text input for name is not working. I need your help.
if(isset($_POST['upload']))
{
$path=$path.$_FILES['file_upload']['name'];
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>";
echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>';
$img=$_FILES['file_upload']['name'];
$query="insert into imgtables (name,imgurl,date) values('$name',STR_TO_DATE('$dateofbirth','%d-%m-%y'),'$img',now())";
if($sp->query($query)){
echo "<br/>Inserted to DB also";
}else{
echo "Error <br/>".$sp->error;
}
}
else
{
echo "There is an error,please retry or ckeck path";
}
}
?>
The form is as follows:
<form action="gallery.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td width="108">Select File</td>
<td width="260"><label><input type="file" name="file_upload"></label></td>
</tr>
<tr>
<td></td>
<td><label><input type="submit" name="upload" value="Upload File"></label></td>
</tr>
</table>
</form>
Obviously the variable $name is empty or undefined and this is why all the other columns are populated and not this one. Also since the query is valid you don't get any error.
You can confirm this with a simple :
echo($name);
Not related to your problem :
Your code seems vulnerable to SQL injection : use prepared statement to prevent this.
Is register_globals turned on? If so you should really consider turning it off. To know why, have a look at Why is REGISTER_GLOBALS so bad?.
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 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'm having trouble with this form. I want the user to be able to edit an item in the datebase. They chose which item they want to edit on one page and get sent with a GET to the editing page. The GET has the id of the item they need to edit.
The editing page loads with the details of the item inserted into the user form (apart from the name of the file) this field is left blank. I am trying to do some logic that checks if the user has chosen a file.
If they haven't then this field should be ignored as I will presume the user is happy with the file that is already uploaded.
If they chose a file then this means they want this to be the new picture. Only then do I want to run the logic to upload the picture and insert its name into the database.
I'm getting my POST details by saying:
$clean_pic = $_POST['pic'];
I am then saying if it's blank do nothing otherwise run the upload:
if($clean_pic = ''){}
else{
It's not working. Any ideas how I should find out if its blank? Cut down code:
if (isset($_POST['add']))
{
// validate 'pic': must consist of alphanumeric characters only.
$_POST['pic'] = isset($_POST['pic']) ? $_POST['pic'] : '';
//if(preg_match('/\.(jpg|gif|jpeg)$/i',$_POST['pic']))
//{
$clean_pic = $_POST['pic'];
//}
//else
//{$error++; $errmsg .= 'Invalid pic. ';}
}
if (isset($_POST['add']) && ($error==0))
{
if (!isset($_POST['pic'])) { echo"test1";}
else {echo"test222";}
/*tied this too but it didnt work (it will always display result 1):
if (!isset($_POST['pic'])) { echo"test1";}
if (isset($_POST['pic'])) {echo"test222";}*/
}
else //output error messages
{
/////////render form
?>
<form enctype="multipart/form-data" action="" method="post" id="save"><fieldset>
<table id="site-form">
<tr>
<td class="one_of_three"><label>Item Name: </label></td>
<td class="two_of_three"><input type="text" name="fileName" id="fileName" value="<?php echo"$db_name";?>"/></td>
<td><label class="errors" id="fileNameError"> </label></td>
</tr>
<tr>
<td class="one_of_three"><label>Picture: </label></td>
<td class="two_of_three"><input type="file" name="userfile[]" id="pic"/></td>
<td><label class="errors" id="picError"> </label></td>
</tr>
<tr>
<td class="one_of_three"> </td>
<td class="two_of_three"><input name="add" id="save_button" type="submit" value="Update"/> Cancel.</td>
<td> </td>
</tr>
</table>
</fieldset></form>
<?php }?>
What about if (!isset($_POST['pic']))?
You cant access the file using 'id' attribute ('pic'). You have to use the value of 'name' attribute ('userfile'). You can check whether the file is uploaded or not using $_FILES array in php.
if(isset($_FILES) && isset($_FILES['userfile']) && (trim($_FILES['userfile']['name']) != '') ) {
//Your upload code here
}
else
{
//No file uploaded
}
You need to check to things :
one is $_POST['pic'] is an array
second one is in the form you have to use enctype="multipart/form-data" attribute.
I wrote a simple form from which a user will change his/her name , Facebook Name and image
here is the profile.php code with the form
<!!--edit form--!!>
<div id="edit">
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1"
bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" cellpadding="1" cellspacing="1"bgcolor="#FFFFFF">
<tr>
<form method="POST" action="save_profile.php">
<td colspan="3"><strong>Username<br><? echo $row['session'];?></strong></td>
<td colspan="3"><strong>Name</strong><input type="text" name="name" id="name"
value="<? echo $row['name'];?>"/><br></td>
<td colspan="3"><strong>Facebook</strong><input type="text" name="fb" id="fb" value="<? echo $row['facebook'];?>"/></td>
<td colspan="3"><strong>Image</strong><input type="text" name="img" id="img" value="<? echo $row['img'];?>"/></td>
<input type="hidden" name="pros" />
<input type="submit" value="Save" />
</form>
and this is the save_profile.php
<?
include"sp-includes/sp-config2.php";
$resultz = mysql_query($slctq);
while($rowqw = mysql_fetch_array($resultz, MYSQL_ASSOC))
{
if($_POST['pros']){
$name=$_POST['name'];
$fb=$_POST['fb'];
$img=$_POST['img'];
$do =mysql_query("UPDATE profile SET name='$name', facebook='$fb', img='$img' WHERE id='$rowqw[id]'");
}
echo $rowqw['id'];
}
?>
I dont Know where i am wrong..
First of all, PLEASE SANITIZE YOUR QUERIES. Your query is completely open for exploitation right now and that might entirely be the reason why it fails.
Write your query like this:
mysql_query('UPDATE profile SET name="'.mysql_real_escape_string($name).'", facebook="'.mysql_real_escape_string($fb).'", img="'.mysql_real_escape_string($img).'" WHERE id="'.mysql_real_escape_string($rowqw['id']).'";');
Also, note that the rowqw index should be written as 'id' instead of id.
The problems with your code:
You are not checking for errors. Use mysql_error().
You are not checking your input (if it's valid or not). You should be binding parameters or escaping with mysql_real_escape_string.
Put the query in a separate string. Something like $query = "UPDATE ..."; $do = mysql_query($query);. It is useful for debugging. You know what the exact query you are sending is.
You are using $rowq[id] the wrong way. When in a string you either use the . notation, you concatenate multiple strings; or you enclose it in {$rowq[id]}.
When you do all this, you'll solve the problems yourself. Read the docs too.
Change the code to
$do = mysql_query("UPDATE profile SET name = '$name', facebook = '$fb', img = '$img' WHERE id = '$rowqw[id]'");
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.