I am having issues inserting this into my database I think tis when I try to convert my prdocutPrice string or stock string into decimal and int values. I am pretty certain I am doing the rest right can someone confirm for me?
<?php
if (isset($_POST['addSubmitted'])) {
$errors = array();
require_once ('mysql_connect.php');
//This gets all the other information from the form
$name=$_POST['productName'];
$description=$_POST['productDescription'];
$price= floatval($_POST['productPrice']);
$stock= intval($_POST['productStock']);
if (empty($errors)) {
//Writes the information to the database
mysql_query("INSERT INTO products (name, description, price, stock) VALUES ($name, $description, $price, $stock)");
$result = mysql_query($query);
if (mysql_affected_rows() == 1) {
// Show thank you message
echo '<span style="color:green;">Your product has been added.</span>';
} else {
echo '<font color="red">We were unable to add your product to the database.</font>';
}
} else {
echo '<font color="red"><h3>Error!</h3>
The following error(s) occured:<br /></font>';
foreach ($errors as $msg) {
echo " - <font color=\"red\">$msg</font><br />\n";
}
}
}
?>
None of your string values are correctly quoted in the
INSERTstatement. Surround them in single quotes.Also, first thing’s first — be sure to call
mysql_real_escape_string()on all the string input values, as they are currently vulnerable to SQL injection attacks.Further, you are calling
mysql_query()twice instead of storing the SQL string into your variable$query.A call to
echo mysql_error();would have helped to debug the problems with your SQL statement.Finally, one more note I’ll add – in addition to calling
intval()orfloatval()on strings passed from$_POST, it is usually a good idea to verify that the numbers are actually numbers. Otherwise if they are non numeric values, they will be cast to 0 and you’ll get zeros in your database when you probably shouldn’t have inserted it at all (since it is invalid data).For positive or zero integers, I like to use
ctype_digit():