html form INSERT INTO database - php

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 ...
}

Related

$_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;

Adding post values to database using mysqli

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.

database saving and retrieving the last saved value

I have a confusion in mind regarding a logic.. it is a form that i first want to validate then I want to save in database and then i want to display it on another page.
I have validated it (transferring (i.e. form action) the form to the same page), I have saved it in database, and now I m trying to display the data on another page.
What I have thought, that I'll save the data to the db and transfer some unique value to another page, maybe some sort of number auto generated by database related to the same form.
now I have problem how to do it? Any ideas guys?
Since it is a logic hence I am tagging php, MySQL and JS
Call mysql_insert_id() once you perform INSERT operation something like this,
$lastInsertedId = mysql_insert_id(); # Assuming you have an auto increment column in your table.
header('Location: view.php?id='.$lastInsertedId);
Than in your view.php get the id & fetch record to display it,
$id = $_GET['id'];
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
After insertion query,use
$lastID = mysql_insert_id();
After then you can redirect to another page like,
header("location:view_page.php?id=$lastID");
Than in view_page.php page,use
$lastID= $_GET['id'];
after then fetch record from database to display data.
NOTE: It will work only when your database table has autoincremented field as index key.
Using mysql_insert_id() is a way. But If you do not want to query your database and still have that then you can do it this way . Below goes the example
<form name="frm" method="POST" action="display.php">
<input type="text" name="your_name" value="" />
<input type="text" name="age" value="" />
<input type="submit" name="save" value="Save" />
</form>
Now in your display.php page
<?php
// DO YOUR DATABASE CONNECTIVITY
$name = $_POST['your_name'];
$age = $_POST['age'];
$query = "insert into table_name values('$name','$age')";
if(mysql_query($insert)) {
?>
<table>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td><?php echo $name;?></td>
<td><?php echo $age;?></td>
</tr>
</table>
<?php } else { echo "No Insertion"; } ?>
Remember mysql_* function are depreciated. So avoid those. Also check for sql injection

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.

insert php values $row into database in another .php file

I have a table with php values (table.php )retrieve from mysql database.
I want to insert this particular value into another database with the insertion code inside another php file (admin.php)
How should I go about doing it?
Code from table.php
<tr>
<td class="brack_under cell_1">
<?php
$row = mysql_fetch_row($data);
echo "<a>".$row[2]."</a>";
?>
</td>
<td class="cell_2"> </td>
<td class="cell_3"> </td>
<td class="cell_4"> </td>
<td class="cell_5"> </td>
<td class="cell_6"> </td>
</tr>
Code from admin.php
<?php
it is something like : $a = $_POST[ $row[2] ]; ???
$sql="INSERT INTO matchTable (schInitial, schName,position)VALUES
('$_POST[ $row[1] ]','$_POST[$row[2] ]','top8')";
mysql_close($con)
?>
According to the comment discussion and your comments, I'm gonna try to help you a bit here (hopefully I got the point)
You need to POST a <form ...> to your script. Unless you do that, there is no $_POST available. E.g.:
<form method="post" action="myscript.php">
<input type="hidden" name="some_var" value="player1" />
<input type="submit" />
</form>
This gives the following in myscript.php where you can do your filtering and insertion and stuff.
print_r($_POST);
// output: array( 'some_var' => 'player1' );
Which means, according to your tries (and to keep it understandable)
$a = $_POST['some_var']
// $a is now 'player1'
So, the only thing you need to do: create a form beneath your table, put some hidden fields in it with data you need to do your math things, and put a submit button in it.

Categories