php操作数据库

<?php

session_start();

#面向过程

function create_connection(){

$conn = mysqli_connect('127.0.0.1','root','123456','learn_2') or die("数据库连接失败");

mysqli_query($conn,"set names utf8");

return $conn;

}

#面向对象

function create_connection_opp(){

$conn = new mysqli('127.0.0.1','root','123456','learn_2') or die("数据库连接失败");

$conn->query("set names utf8");

#$conn->set_charset('utf8');

return $conn;

}

function test_mysqli_opp(){

$conn = create_connection_opp();

$sql = "select * from user";

result = conn->query($sql);

//获取结果集行数

#echo $result->num_rows;

rows = result->fetch_all();

var_dump($rows);

#关联数组的方式

rows = result->fetch_all(MYSQLI_ASSOC);

var_dump($rows);

foreach (rows as row){

echo $row['username']."<br>" ;

echo $row['password'];

}

}

//mysql预处理功能

function mysqli_prepare_stmt(){

$conn =create_connection_opp();

$sql = "select * from user where username = ?";

//实例化prepared statement预处理对象

stmt = conn->prepare($sql);

#实例化需要将参数进行绑定 "s"代表字符串 "i"整数 "d"小数 "b"二进制

stmt-\>bind_param("s",username);

$username = 'zs';

#要获取查询结果,还需要绑定结果参数。不需要返回结果无需此操作

stmt-\>bind_result(username,$password);

#返回值bool ture执行成功 false执行失败

$stmt->execute();

#调佣结果并进行处理

$stmt->store_result();

while($stmt->fetch()){

echo username,password,'<br>';

}

#输出行数

echo $stmt->num_rows.'<br>';

echo $stmt->affected_rows;

/**

* $sql = "select * from user where username = ? and password = ?";

* stmt-\>bind_param("ss",username,$password);

*/

}

mysqli_prepare_stmt()

?>

相关推荐
BingoGo17 小时前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack17 小时前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
cipher1 天前
ERC-4626 通胀攻击:DeFi 金库的"捐款陷阱"
前端·后端·安全
BingoGo2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
Jony_2 天前
高可用移动网络连接
网络协议
chilix3 天前
Linux 跨网段路由转发配置
网络协议
JaguarJack3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack4 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel