这实际上是我的数据库的问题,而不是我的表单或我的isset。 如果有人想知道我最终如何解决这个问题,我会在这里概述一下。
我按照in.k建议并使用与表单中相同的查询,然后添加几行以生成一些错误代码,如下所示:
// query execution
$wr_pro = "INSERT INTO products (name, description, price, cat_id) VALUES ('$name', '$description', '$price', '$categories')";
$result = $db->query($wr_pro);
print "$db->error()";
if ($db->connect_error) {
die("Connection failed: ");
}
if ($result === TRUE) {
echo "Product added successfully!";
}
else {
echo "Problem loading to database...";
}
当我加载页面时,我收到一个数据库错误,告诉我需要为所有空字段设置默认值(这是导致问题的空标记字段)。
所以是的,基本上我没有正确设置我的数据库。 但我现在知道错误代码很棒。
--------------原始问题----------------- 我对此非常陌生,所以如果我错过了一些非常明显的内容,或者我的代码有点乱,我很抱歉。
我正在尝试创建一个将新产品条目写入现有mysql数据库表的页面。
从其他问题来看,我试过了:
它无法写入数据库的错误没有显示,也没有写入数据库,所以我认为它的isset不起作用?但我很容易出错。
我非常确定与数据库的连接是否正常,因为表单有一个从数据库中选择的类别部分,并在页面上显示正常。
我不知道它是否相关,但我在WAMP本地运行它。
任何能指出我正确方向的人,我都会非常感激。
----我的代码
<?php
include("includes/connection.php");
include("includes/head.html");
include("includes/header.php");
?>
<div class="pagecontent">
<h1> Create New Product:</h1>
<!-- form submission action-->
<?php
if (isset($_POST['submitwrpro'])) {
// escape user inputs
$name = mysqli_real_escape_string($db, $_POST['name']);
$description = mysqli_real_escape_string($db, $_POST['description']);
$price = mysqli_real_escape_string($db, $_POST['price']);
$categories = mysqli_real_escape_string($db, $_POST['category_id']);
// query execution
$wr_pro = "INSERT INTO products (name, description, price, cat_id) VALUES ('$name', '$description', '$price', '$categories')";
if(mysqli_query($db, $wr_pro)){
echo "Product added successfully!";
}
else{
echo "Error writing to database $wr_pro. " . mysqli_error($db);
}
}
?>
<!-- form entry -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<table>
<tr>
<td>Name</td>
<td><input type='text' name='name'></td>
</tr>
<tr>
<td>Price</td>
<td><input type='text' name='price'></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name='description'></textarea></td>
</tr>
<tr>
<td>Category</td>
<td>
<!-- read product categories from the db -->
<?php
$req_cat = "SELECT cat_id, name FROM categories";
$result = $db->query($req_cat);
echo "<select class='form-control' name='category_id'>";
echo "<option>Select category...</option>";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()){
extract($row);
echo "<option value=\"" . $row['cat_id'] . "\">" . $row["name"] . "</option>";
}
}
else {
echo "no results";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td></td>
<td>
<button name="submitwrpro" type="submit">Create</button>
</td>
</tr>
</table>
</form>
</div>
<?php
include("includes/footer.php");
?>
答案 0 :(得分:0)
我不认为您正确连接到db。我没有看到连接文件,但是你在select中的表单中得到的结果有不同的连接方式。我浏览了表格,没有发现任何错误。试试这样的事情
$connection = "INSERT INTO products (name, description, price, cat_id) VALUES ('$name', '$description', '$price', '$categories')";
$result = $db->query($connection);
echo "Product added successfully!";