I have following code in order to capture data from the previous page. Its working fine, the data is passing true, just the problem is the only variable that has characters ($itemName). I simply cannot insert in mysql column. Its not type setting or character set. I suspecting its something to with a fact that the text is coming from array. Any ideas?
if(isset($_POST["cantidad"]) && count($_POST['cantidad'])>0) {
foreach($_POST["cantidad"] as $key => $value) {
$cantidad = $value;
$value = $_POST["cantidad"][$key];
$idItem = $_POST['hiddenField'][$key];
$itemName = $_POST['hiddenName'][$key];
$query = "INSERT INTO `inventarioStat` SET `fecha` = $timestamp, `idItem` = $idItem, `nombreItem` = $itemName, `cantidad` = $value";
///// this section is to check do data pass true and they do
echo "<br>";
echo "value:" . $value . "<br>";
echo "id:" . $idItem . "<br>";
echo "name:" . $itemName . "<br>";
mysql_query($query);
}
}
echo "<br>";
$query = "INSERT INTO `inventarioStat` SET `fecha` = $timestamp, `idItem` = $idItem, `nombreItem` = $itemName, `cantidad` = $value";
This line is incorrect and extremely unsafe. The issue is that you are not quoting your strings in the SQL query. You need quotes around the $itemName
value.
You also need to be escaping the values here. This code is wide open to SQL injection. If you use it, you will probably get hacked.
Try this:
foreach($_POST["cantidad"] as $key => $value) {
$cantidad = $value;
$value = mysql_real_escape_string($_POST["cantidad"][$key]);
$idItem = mysql_real_escape_string($_POST['hiddenField'][$key]);
$itemName = mysql_real_escape_string($_POST['hiddenName'][$key]);
$query = "INSERT INTO `inventarioStat` SET `fecha` = '$timestamp', `idItem` = '$idItem', `nombreItem` = '$itemName', `cantidad` = '$value'";
mysql_query($query);
}
This code is better , but not perfect. It's safer, but not 100% safe.
You should upgrade to using PDO or MySQLi and prepared statements ( PDO docs or MySQLi docs ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.