Home >Backend Development >PHP Problem >How to connect to the database in php7

How to connect to the database in php7

(*-*)浩
(*-*)浩Original
2019-10-12 09:09:293149browse

The methods to use native PHP to connect to MySQL include the MySQL library, MySQLi library and PDO. Since PHP 7 has abolished the MySQL library, it is recommended to use MySQLi and PDO.

How to connect to the database in php7

There are two styles for connecting to MySQLi:

Object-oriented style ( Recommended) (Recommended learning: PHP video tutorial)

<?php
$serve = &#39;localhost:3306&#39;;
$username = &#39;root&#39;;
$password = &#39;admin123&#39;;
$dbname = &#39;examples&#39;;
$mysqli = new Mysqli($serve,$username,$password,$dbname);
if($mysqli->connect_error){
	die(&#39;connect error:&#39;.$mysqli->connect_errno);
}
$mysqli->set_charset(&#39;UTF-8&#39;); // 设置数据库字符集

$result = $mysqli->query(&#39;select * from customers&#39;);
$data = $result->fetch_all(); // 从结果集中获取所有数据
print_r($data);

 ?>

Procedural style

<?php
$serve = &#39;localhost:3306&#39;;
$username = &#39;root&#39;;
$password = &#39;admin123&#39;;
$dbname = &#39;examples&#39;;
$link = mysqli_connect($serve,$username,$password,$dbname);
mysqli_set_charset($link,&#39;UTF-8&#39;); // 设置数据库字符集
$result = mysqli_query($link,&#39;select * from customers&#39;);
$data = mysqli_fetch_all($result); // 从结果集中获取所有数据
print_r($data);

 ?>

PDO connection database

<?php
$serve = &#39;mysql:host=localhost:3306;dbname=examples;charset=utf8&#39;;
$username = &#39;root&#39;;
$password = &#39;admin123&#39;;

try{ // PDO连接数据库若错误则会抛出一个PDOException异常
	$PDO = new PDO($serve,$username,$password);
	$result = $PDO->query(&#39;select * from customers&#39;);
	$data = $result->fetchAll(PDO::FETCH_ASSOC); // PDO::FETCH_ASSOC表示将对应结果集中的每一行作为一个由列名索引的数组返回
	print_r($data);
} catch (PDOException $error){
	echo &#39;connect failed:&#39;.$error->getMessage();
}

 ?>

The above is the detailed content of How to connect to the database in php7. For more information, please follow other related articles on the PHP Chinese website!

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
Previous article:Is php safe?Next article:Is php safe?