我的代码需要帮助;不知怎的,我的代码创建了两个房间(它一次在表格中插入两行),我不知道为什么。
(我需要为每个插页都要求一个id来知道我们在哪个房子里创建一个新房间。我的数据库包含表格' house' table' room'。表&# 39; room'有一个字段' house_id'这是一个外键,在表' house'中有一个字段' id。)
那是我的php页面:
<?php
// turn autocommit off
mysqli_autocommit($con, FALSE);
// fetch the houses so that we have access to their names and id
$query = "SELECT name, id
FROM house";
$result = mysqli_query($con, $query);
// check query returned a result
if ($result === false) {
echo mysqli_error($con);
} else {
$options = "";
// create an option
while ($row = mysqli_fetch_assoc($result)) {
// $options .= "".$row['name']."";
$options .= "<option value='".$row['id']."'>";
$options .= $row['name'];
$options .= "</option>";
}
}
include('templates/add_room.html');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$price = mysqli_real_escape_string($con, $_POST["price"]);
$house = mysqli_real_escape_string($con, $_POST["house_id"]);
$query = "INSERT INTO room (price, house_id)
VALUES ('$price', '$house')";
// run the query to insert the data
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
echo "<script type= 'text/javascript'>alert('New room created successfully with the id of {$con->insert_id}');</script>";
mysqli_commit($con);
} else {
echo "There was a problem:<br />$query<br />{$con->error}";
mysqli_rollback($con);
}
}
//free result set
mysqli_free_result($result);
?>
这是我的html模板,其格式为:
<h2>Add new room</h2>
<form action='' method='POST'>
<fieldset>
<label for='price'>Price:</label>
<input type='number' name='price'>
</fieldset>
<fieldset>
<label for='house_id'>House:</label>
<select name='house_id' required>
<option value='' disabled selected>Select house</options>
<?php echo $options; ?>
</select>
</fieldset>
<button type='submit'>Add</button>
</form>
答案 0 :(得分:2)
由于您使用了两次查询功能,它会插入2行:
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
因此,您需要将该条件语句更改为:
if ($result) {
顺便说一下,使用预备语句,它比real_escape_string()
更安全:
答案 1 :(得分:0)
您要插入两次
首先来到这里:
// run the query to insert the data
$result = mysqli_query($con, $query);
然后在这里:
// check if the query went ok
if ( $con->query($query) ) {
删除第一个,你应该没问题,或者检查第一个的结果并删除第二个。
答案 2 :(得分:-1)
不是100%肯定,但看起来你运行两次INSERT查询。来到这里:
$result = mysqli_query($con, $query);
过了一会儿,当你试图检查一些东西时。当你显然试图检查某些东西时,你无意中使用了OOP风格
if ( $con->query($query) ) {