<?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()
?>