我在Php做一个聊天应用程序。我面临的问题是,只有当我发送第二条消息时才显示第一条消息。例如,如果我必须看到第4个发送的消息,那么我必须发送第5个消息或刷新页面。请帮助找出问题所在。简化代码如下:
<!DOCTYPE html>
<html>
<head>
<title> Chatting project</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script src="js/script.js"></script>
</head>
<body>
<div id="container">
<header>
<h1><span>Chatting project</span></h1>
</header>
<div id="shouts">
<ul>
<!-- 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['name']; ?>: <?php echo $row['shout']; ?> [<?php echo $row['date']; ?>]</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
$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>
答案 0 :(得分:1)
问题出现在您的代码中,在INSERTING
之后您是SELECTING
。那些线:
<?php
$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);
?>
应该在SELECT
行之前:
<?php
$connection = mysqli_connect("localhost", "root", "", "tru");
$query = "SELECT * FROM shouts ORDER BY id Desc LIMIT 8";
$shouts = mysqli_query($connection, $query);
?>
所以它会像:
<?php
$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);
}
$query = "SELECT * FROM shouts ORDER BY id Desc LIMIT 8";
$shouts = mysqli_query($link, $query);
// close connection
mysqli_close($link);
?>
在您的情况下,您在将新数据添加到数据库之前获取数据,所以在您从数据库SELECT
开始的时候,还没有新行。