php method to get data and convert it to json data format: first connect to the database; then execute "mysql_query($sql);"; finally convert the data into json data format through "json_encode($arr);" .
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
How to obtain data in php and convert it to json data format ?
php obtains data and converts it into json format
<?php header("content-type:text/html;charset=utf-8"); $con=mysql_connect("localhost","root","123456"); mysql_select_db("style"); mysql_query("set names utf8"); $sql="select * from test"; $r=mysql_query($sql); $arr=array();//开始转换 while ($row = mysql_fetch_assoc($r)) { $arr[] = $row; } echo json_encode($arr); mysql_close($con); ?>
1. Concepts related to mysql and mysqli
1. Mysql and mysqli are both function sets in PHP. It has little to do with the mysql database.
2. Before the php5 version, the mysql function of php was generally used to drive the mysql database. For example, the mysql_query() function is process-oriented. 3. After the php5 version, the mysqli function has been added. In a sense, it is an enhanced version of the mysql system function, which is more stable, efficient and secure. Corresponding to mysql_query() is mysqli_query(), which is object-oriented and uses objects to operate and drive the mysql database
2. The difference between mysql and mysqli
1. Mysql is a non-persistent connection function. Mysql will open a connection process every time it is connected.
2. Mysqli is a permanent connection function. Running mysqli multiple times will use the same connection process, thus reducing server overhead. mysqli encapsulates some advanced operations such as transactions, and also encapsulates many available methods in the DB operation process.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to get data in php and convert it to json data format. For more information, please follow other related articles on the PHP Chinese website!