首页 > 开发 > PHP > 正文

PHP Mysqli 常用代码集合

2024-05-04 22:51:09
字体:
来源:转载
供稿:网友

PHP5.0开始,不仅可以使用早期的mysql数据库扩展函数,还能使用新扩展的mysqli技术实现与mysql数据库的信息交流,PHP的mysqli扩展被封装在在一个类中,它是一种面向对象技术,只能在PHP5和MYSQL4,1或更高的版本才能使用,(i)表示该进,使用mysqli,执行速度更快,更方便,更高效,也可以使数据库访问更安全(因为用类模式)

使用mysqli 简单流程

设置PHP.ini 配置文件
extension=php_mysqli.dll

//创建连接

$conn = new mysqli($servername, $username, $password, $dbname); 

//检测连接

if ($conn->connect_error)  {   die("Connection failed: " . $conn->connect_error); } 

//获取数据库返回值

if($stmt=$con->prepare("SELECT username,password FROM member WHERE username=? AND password=?")) {   $stmt->bind_param("ss",$username,$password);   $stmt->execute();   $stmt->bind_result($U,$P);   $HasData=false;   while($stmt->fetch())   {     $HasData=true;     echo "username->".$U." password->".$P."<br>";   } }

//关闭连接

$conn->close(); 

//常用语法
INSERT INTO [表名] ([字段1],[字段2]) VALUES ([值1],[值2]);
SELECT * FROM [表名] WHERE [表达式] ORDER BY [字段1],[ASC/DESC 升/降] [字段2],[ASC/DESC 升/降];
DELETE FROM [表名] WHERE [表达式];
UPDATE [表名] SET [字段1]=[值1],[字段2]=[值2] WHERE [表达式];
获取总行数:SELECT COUNT(*) FROM [表]

//中文乱码

//针对页面 header("Content-Type:text/html;charset=utf-8"); //针对数据库 mysqli->query("SET CHARACTER SET 'utf8'");//读库  mysqli->query("SET NAMES 'utf8'");//写库  

以下是一些实例

连接mysqli

建立MYSQL配置文件 config.ini.php

config.ini.php 内容如下:

<?php  $dbhost ="locallhost"; $dbuser = "hehehe"; $dbpwd = "123456"; $dbname = "Student"; $charName = "gbk2312"; 设置查询字符集gbk,gbk2312,utf-8?>

(用mysqli链接MYSQL数据库)

requery_once("config.ini.php");$mysqliObj = new mysqli($dbhost,$dbuser,$dbpwd,$dbname);if(mysqli_connect_errno()){ echo "连接失败".mysqli_connect_error(); exit();}$mysqliObj->query("set name $charName");

(其他操作)

查询

(单条查询)$sql = "drop table if exists user;";$mysqliObj->query($sql); (多条查询)$musqliObj->multip_query($sql) 返回执行$sql受影响的行数() if($mysqliObj->query($sql))echo $mysqliObj->affected_rows; insert 插入时,返回插入的id (很有用)  $num = $mysqliObj->insert_id;

三种处理查询结果

$sql = "select * from user"; $result = $mysqli->query($sql); (1)fetch_row()  返回索引数组fetch_row()while(list($id,$name,$pwd)=$result->fetch_row()){echo "id: ".$id." name:".$name." pwd:".$pwd."<br>"; }(2)fetch_assoc() 返回关联数组fetch_assoc()while ($row = $result->fetch_assoc()){ echo "id:".$row["userId"]." name:".$row["userName"]." pwd:".$row["password"]."<br>";} (3)fetch_object()返回对象while($row = $result->fetch_object()){echo "id:".$row->userId." name:".$row->uerName." pwd:".$row->password."<br>"; }            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表