Home > Backend Development > PHP Tutorial > 3 ways to connect to the database with PHP

3 ways to connect to the database with PHP

不言
Release: 2023-03-25 06:46:02
Original
9775 people have browsed it

This article mainly introduces the 3 ways to connect to the database in PHP, which has certain reference value. Now I share it with you. Friends in need can refer to it

1. Ordinary connection

$mysql_server='localhost';
$mysql_username='用户名';
$mysql_password='用户密码';
$mysql_database='数据库名';//建立数据库连接
$conn=mysql_connect($mysql_server,$mysql_username,$mysql_password) or die('数据库连接失败!');//选择某个数据库
mysql_select_db($database,$conn);
mysql_query("set names 'utf8'");//执行sql语句
$result=mysql_query(select * from database where id=1);//提取数据
$row=mysql_fetch_row($result);
Copy after login


When extracting data, we use mysql_fetch_row, and we can also use mysql_fetch_assoc and mysql_fetch_array

2. Object-oriented method mysqli connection

$db=new mysqli($dbhost,$username,$password,$database);
if(mysqli_connect_error()){  
  echo '连接错误';    
  exit;
}$result=$db->query("select * from database where id=1");
$row=$result->fetch_array();
Copy after login

3. PDO method connection

    $db=new pdo('mysql:dbname=cms;host=127.0.0.1','php','password');
        $result=$db->query("select * from database where id=1");
            $row=$result->fetchAll();
Copy after login

The above are three commonly used PHP methods to connect to MYSQL database. We can try to use them. Generally, we use the One method is more common, and the third method is the most secure.

Related recommendations:

php connects to the database to query data


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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template