我正在尝试插入两个表,但出现此错误
Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`
下面是我的插入代码
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
但是当我做这样的事情时它会起作用
$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";
我只是将 $field1amount
更改为 $field2amount
但我不想那样做,我还想获取 $field1amount
的值并插入它
请提供任何帮助,谢谢
最佳答案
问题是因为您传递的数字中有一个逗号,而不是字符串。您需要传入 "40,000.00"
或 40000.00
。 MySQL 将其解释为两个值:40
和 000.00
。
使用准备好的语句将缓解这种情况(以及您的安全问题),因为绑定(bind)会将 40,000.00
解释为字符串。让您入门的一个非常基本的示例是:
$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);
/*
- the "s" below means string
- NOTE you should still validate the $_POST value,
don't just accept whatever is sent through your form -
make sure it matches the format you're expecting at least
or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();
关于PHP ~ 列数与第 1 行的值数不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42031702/