PHP学习笔记(二):数据库连接

来源:互联网 发布:网络逗比表情图片大全 编辑:程序博客网 时间:2024/06/06 15:04

一、连接数据库,插入数据老是插入不了,但是在控制台可以?

原因:数据库设计有问题,主键没有设置成自增长,第一次主键默认是0可以插入,但是第二次的时候,主键0已经存在,所以不能插入,所以会出现,第一组数据可以插入,但是以后的数据老是插入失败

解决办法:

      (方案一):写sql的时候,把主键的值也写上

      (方案二):将主键设置成自增长

用方案二比较好:

代码不变,如下:

<?php$conn=mysqli_connect("localhost","root","root","db_guessbook");//设置编码格式,否则中文在数据库中显示乱码mysqli_query($conn,"set names utf-8");<pre name="code" class="html"><pre name="code" class="html">//插入数据
mysqli_query($conn,"INSERT INTO tb_user(username) VALUES ('11')");//插入变量同理insert into tb_user(username) values('$username');
/*下面这些是测试用的,可以没有
 // Check connectionif (mysqli_connect_errno($conn)){echo "Failed to connect to MySQL: " . mysqli_connect_error();}// Perform queries$result=mysqli_query($conn,"SELECT * FROM tb_user");//查看数据$first=mysqli_fetch_row($result);echo $first[0];*/
 mysqli_close($conn);?>



0 0