Home >Backend Development >PHP Tutorial >How to connect MYSQL database with PHP

How to connect MYSQL database with PHP

高洛峰
高洛峰Original
2017-03-01 16:31:554507browse

For entry-level PHP users, as long as we master basic database operations such as writing, reading, editing, and deleting, we can even get started. We can also write simple programs, such as guest books, news article systems, etc. . In the whole process, the connection to the MySQL database is also very important. You can use a variety of methods to connect. For novices, we don’t need to analyze which method optimizes system resources. We just need to be able to connect first.

Here, we summarize several commonly used methods of connecting PHP to MYSQL database.

First, Commonly used common methods

##

$mysql_server="localhost";
$mysql_username="数据库用户名";
$mysql_password="数据库密码";
$mysql_database="数据库名";
//建立数据库链接
$conn = mysql_connect($mysql_server,$mysql_username,$mysql_password) or die("数据库链接错误");
//选择某个数据库
mysql_select_db($mysql_database,$conn);
mysql_query("set names 'utf8'");
//执行MySQL语句
$result=mysql_query("SELECT id,name FROM 数据库表");
//提取数据
$row=mysql_fetch_row($result);

In When extracting data, we use mysql_fetch_row, and we can also use mysql_fetch_assoc and mysql_fetch_array. For details, we refer to the manual.

Second, Object-oriented method

$db=new mysqli($dbhost,$username,$userpass,$dbdatabase);
if(mysqli_connect_error()){
echo 'Could not connect to database.';
exit;
}

$result=$db->query("SELECT id,name FROM user");
$row=$result->fetch_row();

Third, PDO method

##
$dsn='mysql:host='.$dbhost.';dbname='.$dbdatabase.';'
$dbh=new PDO($dsn,$username,$userpass);

$stmt=$dbh->query('SELECT id,name FROM user');
$row=$stmt->fetch();

The above are the three commonly used PHP connections to MYSQL We can try to use the database method. Generally, we use the first method more often.

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to how PHP connects to MYSQL database, please pay attention to 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