In the current Internet era, interfaces are one of the main ways of data communication between various web applications. In PHP, using interfaces to query databases is a common task. Let's briefly introduce how to use PHP to write interfaces and query databases.
1. Preparation
Before we start, we need to make some preparations. First, we need to install a web server software, such as Apache or Nginx. Secondly, we need to install the PHP environment. It is recommended to use PHP7 and above. Finally, we need to set up and configure the database used. Here we take MySQL as an example.
2. Design the database
Before conducting interface query, we need to design the database structure first. Here we take a user table as an example. The table structure is as follows:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `age` int(3) NOT NULL, `phone` varchar(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Brief description of the table structure:
3. Write php code
Before writing the php code for interface query, we need to install a php extension: mysqli, which is used to operate the mysql database. The installation instructions are:
sudo apt-get install php-mysql
Next we can start writing PHP code. First, use the mysqli_connect() method to connect to the MySQL database, and then use the mysqli_query() method to query the data. The code is as follows:
<?php $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "dbname"; //连接MySQL数据库 $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } //查询users表中所有数据 $sql = "SELECT * FROM users"; $result = mysqli_query($conn, $sql); //将数据以json格式返回 if (mysqli_num_rows($result) > 0) { //输出数据 while($row = mysqli_fetch_assoc($result)) { $json_arr[] = $row; } echo json_encode($json_arr); } else { echo "0 结果"; } mysqli_close($conn); ?>
4. Test the interface
Next, we need to test the interface. Enter the following code in the terminal:
php -S localhost:8000
This will start a simple php web server, and then we enter the url in the browser: http://localhost:8000/query.php to test the interface query data function.
Summary:
This article introduces the method of using PHP to write an interface to query the database, and briefly configures and explains the MySQL database. I hope readers can understand the basic PHP interface query function through this article and apply this technology in actual development.
The above is the detailed content of How to use php to write an interface and query the database. For more information, please follow other related articles on the PHP Chinese website!