PHP 学习笔记:操作数据库

under PHP  tag     Published on November 21st , 2020 at 09:36 am

连接数据库。通常有3种写法。

<?php
$host = "123.1.2.3";//MySQL服务器地址
$username = "root";//MySQL服务器用户名
$password = "123123";//MySQL服务器用户密码
$dbname = "databasename";//数据库名
$mysql = mysqli_connect($host, $username, $password, $dbname);//1
$mysql = new mysqli($host, $username, $password, $dbname);//2,快速写法
$mysql = new mysqli();//3,对象写法
$sql = $mysql->connent($host, $username, $password, $dbname);

这样就连接上数据库了,示例中函数参数有四个,这是最常用的四个参数,还有 port、socket,这两个参数很少用到,稍微了解一下。

post:MySQL服务器端口号,默认是3306;
socket:使用设置的socket或pipe。

关闭数据库。使用完成后要关闭连接,及时释放有关 mysql 对象。

<?php
$mysql = mysqli_connect($host, $username, $password, $dbname);
mysqli_close($mysql);

$mysql = new mysqli($host, $username, $password, $dbname);
$mysql->close();
?>

执行 SQL 语句

<?php
$host = "123.1.2.3";//MySQL服务器地址
$username = "root";//MySQL服务器用户名
$password = "123123";//MySQL服务器用户密码
$dbname = "databasename";//数据库名
$mysql = new mysqli($host, $username, $password, $dbname);//连接数据库
//增
$insert = "INSERT INTO users (username, password) VALUES ('user1','123123')";
$result = $mysql->query($insert);
if($result){
    echo "插入数据成功";
}else{
    die("插入失败");
}
//删
$delete = "DELECT FROM users WHERE username='user2'";
$result = $mysql->query($delete);
//改
$update = "UPDATE users SET password='admin' WHERE username='admin'";
$result = $mysql->query($update);
//查
$select = "SELECT * FROM users";
$result = $mysql->query($select);
$mysql->close();
?>

解析结果集(面向对象、面向过程)

fetch_row()、mysqli_fetch_row()

<?php
$arr = $result->fetch_row();
print_r($arr);
$arr = mysqli_fetch_row($result);
print_r($arr);

输出结果:

Array
(
    [0] => user1
    [1] => 11111
    [2] => 1605858622
)

fetch_assoc()、mysqli_fetch_assoc()

$arr = $result->fetch_assoc();
print_r($arr);
$arr = mysqli_fetch_assoc($result);
print_r($arr);

输出结果:

Array
(
    [username] => user1
    [password] => 11111
    [time] => 1605858622
)

fetch_array()、mysqli_fetch_array()

<?php
$arr = $result->fetch_array();
print_r($arr);
$arr = mysqli_fetch_array($result);
print_r($arr);

输出结果:

Array
(
    [0] => user1
    [username] => user1
    [1] => 11111
    [password] => 11111
    [2] => 1605858622
    [time] => 1605858622
)

num_rows、mysqli_num_rows()

<?php
$num = $result->num_rows;
var_dump($num);
$num = mysqli_num_rows($result);
var_dump($num);

输出结果:

int(1);

本文由 surface 创作,采用 知识共享署名4.0 国际许可协议进行许可,转载前请务必署名
  文章最后更新时间为:November 21st , 2020 at 10:43 am
分享到:Twitter  Weibo  Facebook