0
<?php
    session_start();
    $con=mysqli_connect("localhost","root","","accting");
    $query = "USE accting";
    $result = mysqli_query($con,$query);

    $query = "INSERT INTO document (docDate, supplierName, refNo, vatReg, vpGoods, viGoods, nvPurchases, totalAmt, book, cash, account, termsMonth, termsDay) VALUES ('{$_POST['invoiceDate']}', '{$_POST['supplierName']}', '{$_POST['refNo']}', '{$_POST['vatReg']}', '{$_POST['amtVat']}', '{$_POST['vatInput']}', '{$_POST['nonVat']}', '{$_POST['total']}', '{$_POST['bookType']}', '{$_POST['cash']}', '{$_POST['account']}', '{$_POST['termsMonths']}', '{$_POST['termsDays']}',)";
    $result = mysqli_query($con, $query);

    echo "Add document successful.";
?>

不管有没有这个$query = "USE accting";命令,尽管页面打印添加文档成功,条目仍然没有添加到数据库中。这里有什么问题?

4

3 回答 3

2

问题很可能是该VALUES部分的尾随逗号。

您还应该考虑另一种传递变量的方法,因为那里存在SQL 注入漏洞。这是一个例子:

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, "ii", $_POST['x'], $_POST['y']);
mysqli_stmt_execute($stmt);
于 2013-10-25T00:32:01.640 回答
1

There are a number of things wrong here. I suspect it's failing because there's a trailing comma within your VALUES braces. However, the most worrying thing for me is that it looks like you're pumping user input direct from the POST array straight into the database, making this code vulnerable to SQL injection.

See mysqli_real_escape_string() for more information on that.

Also, mysqli_query() returns false upon failure, so I'd check for this and if it happens call mysqli_error() to find out what went wrong. Only if mysqli_query doesn't return false should you announce that the document has been added successfully!

于 2013-10-25T00:38:22.817 回答
0

您需要转储 $_POST 数组以查看是否真的发送了任何数据。

session_start();
var_dump($_POST);

然后在每次 SQL 调用后回显你的 sql

echo $query;

最后,您确实应该在插入数据库之前验证输入($_POST 数组),正如已经说明的那样,因为存在 sql 注入风险。

于 2013-10-25T00:42:12.957 回答