PHP how Mysql database connection

PHP is a PHP database connection mysql novice who must master a skill, as long as the master of PHP database CRUD and other operations, can write some simple and common procedures. Such as leaving a message, such as news pages. This article is mainly to introduce two common methods PHP Mysql database connection details.
We adopted the following specific code examples to tell you two methods PHP mysql database connection details.

mysqli connect to the database and the database, there are two methods pdo connection.

The first method: using mysqli database connection mysql

Code examples are as follows:

<?php
$host='127.0.0.1';
$user='root';
$password='root';
$dbName='php';
$link=new mysqli($host,$user,$password,$dbName);
if ($link->connect_error){
    die("连接失败:".$link->connect_error);
}
    $sql="select * from admins";
    $res=$link->query($sql);
    $data=$res->fetch_all();
    var_dump($data);

In the above code, we must first create some variables need to use, such as a database user name, database name, password and so on. Then we use the object-oriented database connection named php. By then if condition, connect-error method for determining whether the database connection PHP success.

After a series of connected operations, we'll create a sql statement to query data tables where test.

Here, we first look at whether there is a sign in phpmyadmin php database, from the figure may be known to be present in this php database.
PHP how Mysql database connection
Last accessed through a browser, the results as shown below:
PHP how Mysql database connection
can be seen from the figure, we have successfully connected php database, and can query the data table information.

The second method: using PDO database connection

Code examples are as follows:

<?php
$host='127.0.0.1';
$user='root';
$password='root';
$dbName='php';
$pdo=new PDO("mysql:host=$host;dbname=$dbName",$user,$password);
$sql="select * from admins";
$data=$pdo->query($sql)->fetch();
var_dump($data);

Accessed through a browser, the results shown:
PHP how Mysql database connection
These are two common ways to connect on PHP database query data Detailed

Guess you like

Origin blog.51cto.com/14646124/2461289