php连接到数据库

时间:2023-03-10 00:13:58
php连接到数据库

html代码:

<form action="php_mysql_add.php" method="post">
用户名: <input type="text" name="user"/> <br/>
标题: <input type="text" name="title"/> <br/>
内容: <textarea name="content" id="" cols="30" rows="10"></textarea> <br/>
<input type="submit" name="submit" value="发布留言"/> <br/>
</form>

连接到数据库的代码:

if(@$_POST['submit']){
//设置表单变量
$user = $_POST['user'];
$title = $_POST['title'];
$content = $_POST['content'];
//连接到数据库
$conn = @mysql_connect("localhost","root","root") or die("数据库连接失败,请检查你的网络,稍后再试试");

//选定数据库

      mysql_select_db("test");

       //执行SQL语句(查询)

       mysql_query("set names 'utf8'");

    $sql = "INSERT INTO `test`.`message` (`id`,`user`, `title`, `content`, `lastdate`) VALUES (NULL, '$user', '$title', '$content', now())";
mysql_query($sql);
//关闭数库
mysql_close($conn);
}
?>

添加、选定、删除

<body>
<table width=500 border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#add3ef">
<?php
while($row = mysql_fetch_array($result)){
?>
<tr bgcolor="#eff3ff">
<td>标题:<?php echo $row['title'] ?> 用户:<?php echo $row['user'] ?></td>
</tr>
<tr bgColor="#ffffff">
<td>内容:<?php echo $row['content'] ?>
       
<a href="php_mysql_del.php?messageid=<?php echo $row['id'] ?>">删除</a></td>
</tr> <?php
}
?>
</table>
</body>