Home > Backend Development > PHP Problem > How to query the database in php

How to query the database in php

silencement
Release: 2023-02-25 06:02:01
Original
5724 people have browsed it

How to query the database in php

Before PHP queries the database, you must first connect to the database. Next, use PDO to connect to the database.

pdo is a newly added database abstraction layer in php5, in order to solve the problem of accessing a unified interface for different databases. It is similar to the operation of PEAR::DB class and ADODB class, but it is directly encapsulated and then used in php extension, so you can choose to use it freely.

PDO constructor to connect to the database

In PDO, to establish a database connection, you need to instantiate the PDO constructor. The syntax format of the PDO constructor is as follows:

_construct(string $dsn[,string $username[,string $password[,array $driver_options]]])
Copy after login

Construction The parameter description of the function is as follows:

dsn:数据源名称,包括主机名端口号和数据库名称。
username:连接数据库的用户名。
password:连接数据库的密码。
driver_options:连接数据库的其它选项。
Copy after login

Then we will use an example to explain directly, connecting to the MySQL database through PDO, the specific code is as follows:

<?php
header("Content-Type:text/html; charset=utf-8");    //设置页面的编码格式
$dbms = "mysql";                                  // 数据库的类型
$dbName ="php_cn";                                //使用的数据库名称
$user = "root";                                   //使用的数据库用户名
$pwd = "root";                                    //使用的数据库密码
$host = "localhost";                              //使用的主机名称
$dsn  = "$dbms:host=$host;dbName=$dbName ";       
try{                                             //捕获异常
    $pdo = new PDO($dsn,$user,$pwd);             //实例化对象
    echo  "PDO连接数据库成功";
}catch (Exception $e){
    echo $e->getMessage()."<br>";
}
Copy after login

Query database


The SELECT statement is used to select data from the database.

The syntax is

SELECT column_name(s) FROM table_name
Copy after login

Note: SQL statements are not case-sensitive. SELECT is equivalent to select.

In order for PHP to execute the above statement, we must use the mysql_query() function. This function is used to send queries or commands to MySQL.

The above is the detailed content of How to query the database in 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