我有问题将此插入我的数据库我认为当我尝试将我的prdocutPrice字符串或股票字符串转换为decimal和int值时.我很确定我正在休息,有人可以帮我确认吗?
<?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";
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
在INSERT语句中没有正确引用任何字符串值.用单引号括起来.
此外,第一件事是第一件事 - 确保调用mysql_real_escape_string()所有字符串输入值,因为它们目前容易受到SQL注入攻击.
$name = mysql_real_escape_string($_POST['productName']);
$description= mysql_real_escape_string($_POST['productDescription']);
$price= floatval($_POST['productPrice']);
$stock= intval($_POST['productStock']);
Run Code Online (Sandbox Code Playgroud)
此外,您正在调用mysql_query()两次而不是将SQL字符串存储到您的变量中$query.
// Quote the string values,
// store the SQL as a variable then pass it to mysql_query()
$query = "INSERT INTO products (name, description, price, stock) VALUES ('$name', '$description', $price, $stock)";
$result = mysql_query($query);
Run Code Online (Sandbox Code Playgroud)
调用echo mysql_error();将有助于调试SQL语句的问题.
最后,我要添加一个注释 - 除了调用intval()或floatval()传递的字符串之外$_POST,验证数字实际上是数字通常是个好主意.否则,如果它们是非数字值,它们将被强制转换为0,当您可能根本不应该插入它时,您将在数据库中获得零(因为它是无效数据).
if (is_numeric($_POST['productPrice'])) {
$price = floatval($_POST['productPrice']);
}
else // non numeric value, don't do the insert with bad data
Run Code Online (Sandbox Code Playgroud)
对于正整数或零整数,我喜欢使用ctype_digit():
if (ctype_digit($_POST['productStock'])) {
$stock = intval($_POST['productStock']);
}
else // bad input value, don't do insert
Run Code Online (Sandbox Code Playgroud)