报错的源代码:
<?php //初始化连接数据库的数据 $servername="localhost"; $username="root"; $password="root"; $dbname="mydb"; //创建连接 $conn=new mysqli($servername,$username,$password,$dbname); //检测连接 if($conn->connect_error){ die("连接失败!".$conn->connect_error); } $sql = "INSERT INTO user (username, password, sex,age) VALUES ('张三', '123456', '男',22)"; if ($conn->query($sql) === TRUE) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
问题出在我的phpStudy中mysql的端口设置的是:3366(因为与本地的mysql有冲突,所以修改成这样)
解决方法:
将$servername = "localhost";改成 $servername = "localhost:3366";