$servername = "127.0.0.1:3306";
$username = "root";
$password = "";
$dbname = " ";//数据库名
// 创建连接
$conn = new mysqli($servername, $username, $password,$dbname);
header("content-type:text/html;charset=utf-8"); //设置编码
// 检测连接
if(!$conn )
{
die('连接失败: ' . mysqli_error($conn));
}
echo '连接成功
';
// 设置编码,防止中文乱码
mysqli_query($conn , "set names utf8");
/*向数据库插入数据**/
$sql = "insert into users(username,age,gender,phone,address)".
"value('周发','38','男','12433524556','你的')";
// 执行数据插入
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
die('无法插入数据: ' . mysqli_error($conn));
}
echo "数据插入成功\n";
mysqli_close($conn);
/*查询数据*/
$sql = "SELECT id,age,gender FROM users";
$result = mysqli_query( $conn, $sql );
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["age"]. " " . $row["gender"]. "
";
}
echo "数据查询成功";
} else {
echo "0 结果";
}
mysqli_close($conn);
/*更新数据*/
$sql = "UPDATE users SET Age=36,username='周驰' WHERE id=8";
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
die('无法更新数据: ' . mysqli_error($conn));
}
echo "数据更新成功\n";
mysqli_close($conn);
?>