PHP通过浏览器写不进数据库
做了最新实验,我的代码发给朋友,没有改动,数据库可以正常添加代码,但是我这边就不行,是数据库问题么?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="css.css" rel="stylesheet" type="text/css">
<title>Title</title>
<?php include ("add.php")?>
</head><body>
<hr size=1>
<form action="add.php" method="post" >
用户:<input type="text" size="10" name="user"/><br>
标题:<input type="text" name="title" /><br>
内容:<textarea name="content"></textarea><br>
<input type="submit" name="submit" value="发布留言" />
</form>
</body>
</html>
<?php
header("Content-type: text/html; charset=utf-8");
include ("conn.php");
$id=$_POST['id'];
$user=$_POST['user'];
$title=$_POST['title'];
$content=$_POST['content'];
if ($_POST['submit']){
$sql="insert into message(id,user,title,content,lastdate)values('','$user','$title','$content',now())";
mysql_query($sql);
echo "<script>alert('提交成功!返回首页。');location.href='add.html';</script>";
}
?>
数据库一点变化没有
其他代码也放一下
<?php
$conn =mysql_connect("localhost", "root", "root") or die("数据库链接错误");
mysql_select_db("test", $conn);
mysql_query("set names 'utf8'"); //使用utf-8中文编码;
?>
<!DOCTYPE html>
<html lang="utf-8">
<Meta http-equiv="Content-Type" Content="text/html; Charset=utf-8">
<head>
<?php
include ("conn.php");
?>
<link href="css.css" rel="stylesheet" type="text/css">
</head>
<table width=500 border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#add3ef" >
<?php
$sql="select * from message order by id desc";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query)){ ?>
<tr bgcolor="#eff3ff">
<td>标题: <?php echo $row['title'];?> <font color="red">用户: <?php echo $row['user'];?> </td>
</tr>
<tr bgColor="#ffffff">
<td>发表内容:<?php echo $row['content'];?></td>
</tr>
<tr bgColor="#ffffff">
<td><div align="right">时间:<?php echo $row['lastdate'];?></td>
</tr>
<?php } ?>
<tr bgcolor="#f0fff0">
<td><div align="right"><a href="add.html">返回留言</a> </td>
</tr>
</table>
</html>
ID是主键,不能插入空值啊。。如果是自动增长的列,去掉id,改下面的试试
$sql="insert into message(user,title,content,lastdate)values('$user','$title','$content',now())";
打印一下POST,看看里面有没有东西,你说数据库没有变化,是指连空数据都没有插入吗?
改:
发布留言
先看看POST 里的数据有没有异常
插入数据库时用
try{
}catch(){
}
捕获一下异常。
if($_POST){
//$id = $_POST['id']; 并没有提交id参数
$user = $_POST['user'];
$title = $_POST['title'];
$content = $_POST['content'];
if($_POST['submit']){
$sql = "insert into message(user,title,content,lastdate) values('{$user}','{$title}','{$content}',now())";
//echo $sql; //调试打印出sql语句复制到数据库执行。
mysqli_query($sql);
//var_dump(mysqli_query($sql));exit; //调试查看执行返回值 true/false
echo "alert('提交成功!返回首页。');location.href='add.html';";
}
}
直接echo $sql;然后再直接命令行插入试试撒 ,看报错信息