Home  >  Article  >  Backend Development  >  How to connect the database to the front-end written in php

How to connect the database to the front-end written in php

(*-*)浩
(*-*)浩Original
2019-05-18 09:29:424232browse

Of course, use PHP code to write the connection method to connect to the database, so that the data in the database can be called to the front end.

How to connect the database to the front-end written in php

Connect to the database (traditional method)

mysql_connect("lcoalhost","root","");   //连接本机数据库,连接外机localhost可以改成制定ip地址
mysql_select_db("txst",$db);            //选择要操作的数据库
$sql="select * from info";              //书写MySQL语句
$result=mysql_query($sql);              //执行MySQL语句
var_dump(mysql_fetch_row($result));     //每执行一次,返回一行数据,可利用循环读取全部,这时就可以读取的数据给前端

Connect to the database (current method)

$db=new MySQLi("localhost","root","","test");   //连接本机的数据库,并指定到具体的库赋值给$db

!mysqli_connect_error() or die("连接失败");      //检测连接数据库是否成功,失败返回“连接失败”,并退出程序 

if(mysqli_connect_error())                     //检测连接数据库是否成功,成功返回false
{
    exit();              //退出程序
}

$sql="select * from info";                     //书写sql语句
$result=$db->query($sql);                      //执行sql语句,成功返回结果集对象,失败返回false

if($result)    //判断是否执行成功
{
    var_dump($row=$result->fetch_row());           //返回索引数组,每执行一次返回一行,加上循环可读取多有数据
    var_dump($result->fetch_assoc());              //返回关联数组,每执行一次返回一行
    var_dump($result->fetch_object());             //返回一个对象,每执行一次返回一次 
    var_dump($result->fetch_all());                //返回索引二维数组,读取全部信息           
}

The above is the detailed content of How to connect the database to the front-end written in php. For more information, please follow other related articles on 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
Previous article:why choose phpNext article:why choose php