我有一个db.php文件,这里建立了与数据库的连接
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "aigsonlinedb";
$con = new mysqli($host,$user,$pass,$db_name);
function formatDate($date){
return date('g:i a', strtotime($date));
}
?>
这里的“Index.php”文件是一个表格,应该从数据库中发送和检索数据
<?php
include 'db.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Chat System in PHP</title>
<link rel="stylesheet" href="style.css" media="all"/>
<script>
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.getElementById('chat').innerHTML = req.responseText;
}
}
req.open('GET','chat.php',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
</head>
<body onload="ajax();">
<div id="container">
<div id="chat_box">
<div id="chat"></div>
</div>
<form method="POST" action="index.php">
<input type="text" name="name" placeholder="enter name"/>
<textarea name="msg" placeholder="enter message"></textarea>
<input type="submit" name="submit" value="Send it"/>
</form>
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$msg = $_POST['msg'];
$query = "INSERT INTO chat (name,msg) VALUES ($name','$msg')";
$run = $con->query($query);
if($run){
echo "<embed loop='false' src='chat.wav' hidden='true' autoplay='true'/>";
}
}
?>
</div>
</body>
</html>
chat.php,从数据库中提取数据
<?php
include 'db.php';
$query = "SELECT * FROM chat ORDER BY id DESC";
$run = $con->query($query);
while($row = $run->fetch_array()) :
?>
<div id="chat_data">
<span style="color:green;"><?php echo $row['name']; ?></span> :
<span style="color:brown;"><?php echo $row['msg']; ?></span>
<span style="float:right;"><?php echo formatDate($row['date']); ?></span>
</div>
<?php endwhile;?>
唯一的问题是数据无法发送到数据库。
答案 0 :(得分:0)
在String的结尾; vor SQL语句。并且双引号中的PHP变量和值中的额外双引号用于定义sql
的数据类型