每当我想在行中插入记录时,我都会遇到问题,它只插入行的最后一个值
这是我的插入服务器记录行为代码:
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO ordering (productCode, Name, paymentMethod, Quantity, TotalPrice) VALUES (%s, %s, %s, %s, %s)",
GetSQLValueString($_POST['productcode'], "int"),
GetSQLValueString($_POST['Name'], "text"),
GetSQLValueString($_POST['PaymentMethod'], "text"),
GetSQLValueString($_POST['quantity'], "int"),
GetSQLValueString($_POST['totalprice'], "double"));
mysql_select_db($database_perfume_connection, $perfume_connection);
$Result1 = mysql_query($insertSQL, $perfume_connection) or die(mysql_error());
$insertGoTo = "member_perfume_homepage.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
答案 0 :(得分:0)
您正在执行的SQL是:
INSERT INTO ordering (productCode, Name, paymentMethod, Quantity, TotalPrice) VALUES (%s, %s, %s, %s, %s)
只插入一行。这就是SQL的语法。此外,您应该注意到,您只需要解析$ _POST一次,因此它不会检索您在sprintf使用的行中使用的多个值。
在一个SQL查询中插入多行的正确语法是:
INSERT INTO ordering (productCode, Name, paymentMethod, Quantity, TotalPrice) VALUES (%s, %s, %s, %s, %s), (%s, %s, %s, %s, %s), (%s, %s, %s, %s, %s);
如果您确实希望使用sprintf函数准备SQL查询,则需要将3倍以上的参数传递给该方法。
$insertSQL = sprintf("INSERT INTO ordering (productCode, Name, paymentMethod, Quantity, TotalPrice) VALUES (%s, %s, %s, %s, %s)",
GetSQLValueString($_POST['productcode'], "int"),
GetSQLValueString($_POST['Name'], "text"),
GetSQLValueString($_POST['PaymentMethod'], "text"),
GetSQLValueString($_POST['quantity'], "int"),
GetSQLValueString($_POST['totalprice'], "double"),
GetSQLValueString($_POST['productcode'], "int"),
GetSQLValueString($_POST['Name'], "text"),
GetSQLValueString($_POST['PaymentMethod'], "text"),
GetSQLValueString($_POST['quantity'], "int"),
GetSQLValueString($_POST['totalprice'], "double"),
GetSQLValueString($_POST['productcode'], "int"),
GetSQLValueString($_POST['Name'], "text"),
GetSQLValueString($_POST['PaymentMethod'], "text"),
GetSQLValueString($_POST['quantity'], "int"),
GetSQLValueString($_POST['totalprice'], "double"));
这应该可行,但我不建议使用这种方式,而是考虑更好的解决方案。
此外,不推荐使用mysql_ *函数。请改用PDO或MySQLi。在PHP手册中阅读它们:http://php.net/manual/en/book.pdo.php或http://php.net/manual/en/class.mysqli.php