PHP is a server-side programming language that has a wide range of applications, one of which is querying data through PHP. In this article, we will discuss how to query all the data of a data table using PHP.
Before you begin, assume that you already have a database, which contains a table named "users". There are multiple fields in the table, including "id", "name", and "email" , "phone", etc. We will use this table to implement the function of querying all data.
The first step is to establish a connection to the database. Use the mysqli_connect() function in PHP, pass in the host name, user name, password and database name, and return a connection object. For example:
$host = "localhost"; $user = "root"; $password = "password"; $dbname = "test"; $conn = mysqli_connect($host, $user, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
Next, we can use the SELECT statement to retrieve all data in the "users" table. The SELECT statement is the core part of the SQL language and can query data in the table. For example:
$sql = "SELECT * FROM users"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. " - Phone: " . $row["phone"]. "<br>"; } } else { echo "0 results"; }
In this example, we use SELECT * to retrieve all data in the table. The results are stored in the $result variable, and the mysqli_fetch_assoc() function is used to obtain each piece of data in the result set row by row. It returns an associative array of data for each row, where the column names are the keys of the array. We output them to the screen for viewing.
After executing the query, the final step is to close the database connection. Use the mysqli_close() function to do this. For example:
mysqli_close($conn);
After the above code is executed, you will see all the data in the "users" table, one row for each piece of data. By modifying the conditions in the SELECT statement, you can retrieve different data.
Summary: Using PHP to query data is one of the basic skills for using PHP and SQL languages. After establishing a connection to the database, use the SELECT statement to query the data. By specifying criteria, you can retrieve different data. Finally, don't forget to close the database connection.
The above is the detailed content of How to query all the data in the data table in php. For more information, please follow other related articles on the PHP Chinese website!