我正在开发一个聊天网络应用程序。问题是每当每次在数据库中插入空消息时加载页面。
代码如下
<!-- Insert MySQL datbase into HTML -->
<?php
$connection = mysqli_connect("localhost", "root", "", "tru");
$query = "SELECT * FROM shouts ORDER BY id Desc LIMIT 8";
$shouts = mysqli_query($connection, $query);
?>
<!-- Insert MySQL datbase into HTML -->
<?php while ($row = mysqli_fetch_assoc($shouts)) : ?>
<li> <?php echo $row['shout']; ?> <b> Sent at </b><?php echo $row['Time']; ?></li>
<?php endwhile; ?>
</ul>
</div>
<footer>
<form action="index.php" method="post">
<label>Shout Text: </label>
<input type="text" name="shout" placeholder="Enter your message here">
<input type="submit" id="submit" value="SHOUT!" >
</form>
<?php
<!-- Insert into MySQL datbase -->
$link = mysqli_connect("localhost", "root", "", "tru");
$sql = "INSERT INTO shouts (name,shout) VALUES ('$_POST[name]','$_POST[shout]')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
</footer>
</div>
</body>
</html>
答案 0 :(得分:1)
def create
requestor = current_user
@meeting_with_params = meeting_params
@meeting = Meeting.new(@meeting_with_params)
respond_to do |format|
if @meeting.save
format.html { redirect_to home_url, notice: 'Your lex was successfully requested! Click Plan Meeting ' }
format.json { render :show, status: :created, location: @meeting }
else
format.html { render :new }
format.json { render json: @meeting.errors, status: :unprocessable_entity }
end
end
end
有了if sentece,你就解决了。如果设置了POST名称变量,它只会添加一条记录。
答案 1 :(得分:1)
你无条件insert
一行,所以这是预期的。那么,条件应该是什么?当然,在页面加载时,您不希望仅在POST时insert
喊叫。所以你需要测试请求是否是帖子:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// insert the row
}
但即使是POST,也需要测试它是否有效,所以检查姓名和喊叫:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ((isset($_POST["name"])) && (isset($_POST["shout"])) && ($_POST["name"]) && ($_POST["shout"])) {
//insert the row
}
}
请注意SQL injection。