Home >Backend Development >PHP Tutorial >3 ways to connect to the database with PHP
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
$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);
When extracting data, we use mysql_fetch_row, and we can also use mysql_fetch_assoc and mysql_fetch_array
$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();
$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();
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!