With the rapid development of the Internet, data analysis and visualization have become essential means for companies and individuals to analyze data on websites and applications. As a popular server-side scripting language, PHP has become the first choice of many web developers. In this article, we will discuss how to read data from a database and generate a chart display using PHP.
1. PHP connection to the database
Before generating the chart, we need to connect to the database and obtain the required data. PHP supports a variety of databases, including MySQL, PostgreSQL, SQLite, etc. In this example, we will use the MySQL database.
First, we need to use the mysqli connection function in the PHP code to connect to the MySQL database. The connection function accepts four parameters: host address, username, password and database name.
$conn = mysqli_connect("localhost", "username", "password", "database_name");
If the connection is successful, you can execute the SQL query and obtain the required data. The following is an example of using the mysqli function to execute a SELECT query and obtain the results:
$sql = "SELECT * FROM table_name";
$result = mysqli_query($conn, $sql);
$ data = mysqli_fetch_all($result, MYSQLI_ASSOC);
This example queries the table named "table_name" and stores the results in the $data array.
2. PHP generates charts
There are many popular chart libraries available for PHP, such as Google Charts, Chart.js and Highcharts. In this example, we will use Google Charts to generate the chart.
Google Charts is a popular JavaScript library that can be used to generate a variety of interactive charts, including line charts, bar charts, pie charts, scatter charts, and more. Before using Google Charts, we need to add a reference to the following JavaScript library in the HTML file: