php未将数据插入mysql但未显示错误

qacovj5a  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(324)

我试图使用php和html表单将数据输入mysql数据库,但是数据没有保存到数据库中,即使它显示它已经保存了。请告诉我如何确保表单条目保存到数据库中。
html格式

<form action="newproduct.php" method="post">
<table>
<tr>
<td>Username</td>
<td><input name="user" type="text"></td>
</tr> ...

<button type="submit">Go</button>
</form>

PHP

<?php
$servername = "localhost";
$username = $_POST["user"];
$password = $_POST["pass"];
$dbname = "bakefree_products";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO ".$_POST["range"]." (productname, image, frompricesize, paypalcode, productdesc, allergystandard, allergyglutenfree, allergyvegan, allergygfvegan)
VALUES ('".$_POST["productname"]."', '".$_POST["image"]."', '".$_POST["frompricesize"]."', '".$_POST["paypalcode"]."', '".$_POST["productdesc"]."', '".$_POST["allergystandard"]."', '".$_POST["allergyglutenfree"]."', '".$_POST["allergyvegan"]."', '".$_POST["allergygfvegan"]."')";

if (mysqli_query($conn, $sql)) {
    echo "New product created successfully.";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

//show new number of products
$sql = "SELECT * FROM".$_POST["range"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "There are ".$result->num_rows ." products.";
} else {
    echo "<br><br>There are no products in ".$_POST["range"];
}

mysqli_close($conn);
?>

结果
新产品创建成功。
测试中没有产品

mm9b1k5b

mm9b1k5b1#

实际上,插入应该可以正常工作,但是您需要在这里检查select查询的语法,

//show new number of products
$sql = "SELECT * FROM ".$_POST["range"]; // Added a space after `FROM`

它应该正确地获取数据并显示字符串, There are X products.

相关问题