How to connect MYSQL database with PHP

高洛峰
Release: 2023-03-06 09:22:02
Original
4472 people have browsed it

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);
Copy after login

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();
Copy after login

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();
Copy after login

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!

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