Adding post values to database using mysqli - php

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.

Related

html form INSERT INTO database

It may be a minor error but I am currently trying to post from a html form into the database to add a new entry.
Here is the code:
<div>
<?php
$menu = "INSERT INTO content (id, path, name)
**VALUES ('".$_POST['id']."', '".$_POST['path']."', '".$_POST['name']."')";**
if ($connnect->query($menu) === TRUE) {
echo "New page added successfully";
} else {
echo "Error";
}
?>
<form action="" method="post" name="menus" id="menus">
<table style="width: 500px;">
<tbody>
<tr>
<td>
<textarea name="id" id="id"></textarea>
</td>
</tr>
<tr>
<td>
<textarea name="path" id="path"></textarea>
</td>
</tr>
<tr>
<td>
<textarea name="name" id="name"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="button" id="button" value="Upload">
</td>
</tr>
</tbody>
</table>
</form>
</div>
However obviously you cannot put each $_POST from the form into each value is there another way to do this or can someone help me?
Kind Regards,
Lewis
use sprintf which can make it a bit more readable in the order of the parameters passed to the values:
$menu = sprintf("INSERT INTO content (id, path, name) VALUES ('%s', '%s', '%s')", mysql_real_escape_string($_POST['id']), mysql_real_escape_string($_POST['path']), mysql_real_escape_string($_POST['name']));
Considering this is your full code, one major problem is that you are inserting the form contents every time the page is loaded. If your form processing is in the same page, you may want to add a simple check. For example:
<?php
if (isset($_POST['submit'])) {
# form information received, process it
}
# else continue with your normal script and display the form
?>
In this case, in a first page load the $_POST data is not set so only the form will apear. When the form is submitted though, the script will detect there is data and process it.
And explained in the comments, PHP Data Objects (or PDO for short) is a much more modern, portable and safe way to deal with databases. There are plenty of explanations over the internet on how and why; and the manual page itself is pretty straight forward to read. You can prepare statements, and then the class itself will handle all the escaping needed to make your script secure. Quick example:
# make a connection
$db = new PDO(/* database info */);
# prepare your statement with the placeholders for your data
$st = $db->prepare("
INSERT INTO content (id, path, name)
VALUES (?,?,?)
");
# execute the query with the POST data
$success = $st->execute([
$_POST['id'],
$_POST['path'],
$_POST['name']
]);
if (!$success) {
# error ...
}

$_POST does not echo a query

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;

Data entry to a particular mysql database table via php, results "undefined index error" pointing variables of another table

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.

php form mysql error to database

I have a form that does not seem to want to write its data to my database. I am somewhat new to php mysql. When I test the script the page reloads with only a "0" displayed. I am not sure what am I missing? Any help is appreciated.
form
<form action="new.php" method="POST">
<table>
<tr>
<td>Season Number: </td>
<td><input type="text" name="season_sum" size="50" value="<? echo "$season_num";?>"></td>
</tr>
<tr>
<td>Episode Number: </td>
<td><input type="text" name="eps_num" size="50" value="<? echo "$eps_num";?>"></td>
</tr>
<tr>
<td>Temp Episode Number: </td>
<td><input type="text" name="temp_eps_num" size="50"></td>
</tr>
<tr>
<td>Title: </td>
<td><input type="text" name="title" size="50"></td>
</tr>
<tr>
<td>Description: </td>
<td><textarea type="text" name="descrip" cols="50" rows="7"></textarea></td>
</tr>
<tr>
<td colspan="2"><input type="hidden" name="id">
<input type="Submit" value="New Item"></td>
</tr>
</table>
</form>
new.php
<?php
require "db.php";
//Test for user input
if (!empty($_POST[season_sum])&&
!empty($_POST[eps_num])&&
!empty($_POST[temp_eps_num])&&
!empty($_POST[title])&&
!empty($_POST[descrip]))
if ( ! empty($_POST['ID']))
$id = (int)$_POST['ID'];
else $id = 'NULL';
//Insert new entry
$query = "INSERT INTO `season` (`ID`, `season_num`, `temp_eps_num`, `esp_num`, `title`, `descrip`) VALUES ({$id}, '{$season_sum}', '{$eps_num}', '{$temp_eps_num}', '{$title}', '{$descrip}')";
// Send user back to the list once the update is successfully finished
header("Location: form.html");
?>
Disable the following line in new.php in the event the PHP code is throwing an error:
//header("Location: form.html")
Then you will need to execute the $query using mysql_query.
$query = "INSERT INTO ... ";
mysql_query($query);
you are never actually sending the query, just defining the query string. To send it you netted to use mysql_query ($query).
See documentation for more details. http://php.net/manual/en/function.mysql-query.php
Not sure about the "0" but in general your code looks like you chopped things out for readability. If not...
if (!empty($_POST[season_sum]) && !empty($_POST[eps_num]) && !empty($_POST[temp_eps_num]) && !empty($_POST[title]) && !empty($_POST[descrip]))
{
if ( !empty($_POST['ID']))
$id = (int)$_POST['ID'];
else
$id = 'NULL';
// mysql_real_escape_string() example
$descrip = mysql_real_escape_string($_POST['descrip']);
//Insert new entry
$query = mysql_query("INSERT INTO `season` (`ID`, `season_num`, `temp_eps_num`, `esp_num`, `title`, `descrip`) VALUES ({$id}, '{$season_sum}', '{$eps_num}', '{$temp_eps_num}', '{$title}', '$descrip')") or die(mysql_error());
// Send user back to the list once the update is successfully finished
header("Location: http://www.yoursite.com/form.html");
exit;
}
I didn't put in the escaping since it is easier just to suggest you wrap your db insert strings with mysql_real_escape_string(). Aside that you never actually run a query, and you do not wrap your if statement with curly braces. I don't even know what the page would think to do in this condition.
Try applying these changes and let us know if the error persists.
note - I added exit after your header location. Also, I put a full url path in as somewhere or another I heard this was better practice. I have no backing for that claim though. Just a thing I heard somewhere.
mysql_real_escape_string() explanation:
to use it you must have a connection open. This is usually handled in your db class so if you discover it doing nothing, look into mysql_connect();
To use, just call like so:
$sql = mysql_query("SELECT * FROM `table` WHERE `id` = '".mysql_real_escape_string($string_to_escape)."'");
It will not add the single quote wrapper. All it does is help sanitize the string to prevent common sql injection attacks.

Only inserts in to database once then fails

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.

Categories