Home  >  Article  >  类库下载  >  PHP uses mysqli extension to connect to MySQL database

PHP uses mysqli extension to connect to MySQL database

高洛峰
高洛峰Original
2016-10-09 13:06:141343browse

This article mainly introduces PHP to use the mysqli extension to connect to the MySQL database. Friends who need it can refer to it

1. Object-oriented usage

$db = new mysqli('localhost', 'root', '123456', 'dbname');

If the database is not specified when establishing the connection, select the database to use and switch to use Database

$db->select_db('dbname');
  
$query = "SELECT * FROM user WHERE uid=4";
  
$result = $db->query($query);
  
$result_num = $result->num_rows;
  
$row = $result->fetch_assoc();  //返回一个关联数组,可以通过$row['uid']的方式取得值
  
$row = $result->fetch_row();  //返回一个列举数组,可以通过$row[0]的方式取得值
  
$row = $result->fetch_array();  //返回一个混合数组,可以通过$row['uid']和$row[0]两种方式取得值
  
$row = $result->fetch_object();  //返回一个对象,可以通过$row->uid的方式取得值
  
$result->free();  //释放结果集
  
$db->close();  //关闭一个数据库连接,这不是必要的,因为脚本执行完毕时会自动关闭连接

When performing INSERT, UPDATE, and DELETE operations, use $db->affected_rows to view the number of affected rows

2. Process-oriented usage

$db = mysqli_connect('localhost', 'root', '123456', 'dbname');

If the database is not specified when establishing a connection, the database will be selected. Database, switch the database used

mysqli_select_db($db, 'dbname');

Query the database

$query = "SELECT * FROM user WHERE uid=4";
  
$result = mysqli_query($db, $query);
  
$result_num = mysqli_num_rows($result);

Return one row of results

$row = mysqli_fetch_assoc($result);  //返回一个关联数组,可以通过$row['uid']的方式取得值
  
$row = mysqli_fetch_row($result);  //返回一个列举数组,可以通过$row[0]的方式取得值
  
$row = mysqli_fetch_array($result);  //返回一个混合数组,可以通过$row['uid']和$row[0]两种方式取得值
  
$row = mysqli_fetch_object($result);  //返回一个对象,可以通过$row->uid的方式取得值

Disconnect the database

mysqli_free_result($result);  //释放结果集
  
mysqli_close($db);  //关闭一个数据库连接,这不是必要的,因为脚本执行完毕时会自动关闭连接

When performing INSERT, UPDATE, DELETE operations, use mysqli_affected_rows() to view the number of affected rows

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more