Home >Backend Development >PHP Problem >How to get query data using PHP
PHP is a commonly used server-side programming language that is widely used in the field of web development. In PHP, obtaining query data is a frequently used operation and can be achieved through various methods. This article will introduce how to use PHP to obtain query data.
MySQLi is the official extension of PHP and provides interactive functions with MySQL. Query data can be easily obtained through the MySQLi extension. The following is an example of using the MySQLi extension to obtain query data:
<?php //建立连接 $mysqli = new mysqli("localhost", "root", "password", "database"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); } //执行查询语句 $result = $mysqli->query("SELECT * FROM users"); //检查查询结果 if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>"; } } else { echo "0 results"; } //关闭连接 $mysqli->close(); ?>
PDO (PHP Data Object) provides a universal access to multiple kind of database. Compared to MySQLi, PDO is more flexible. The following is an example of using PDO extension to obtain query data:
<?php //建立连接 try { $pdo = new PDO("mysql:host=localhost;dbname=database", "root", "password"); } catch (PDOException $e) { echo "Error: " . $e->getMessage(); die(); } //执行查询语句 $stmt = $pdo->query("SELECT * FROM users"); //检查查询结果 if ($stmt->rowCount() > 0) { // 输出每行数据 while($row = $stmt->fetch()) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>"; } } else { echo "0 results"; } //关闭连接 $pdo = null; ?>
Using PDO preprocessing statements can improve query efficiency and security . The following is an example of using PDO prepared statements to obtain query data:
<?php //建立连接 try { $pdo = new PDO("mysql:host=localhost;dbname=database", "root", "password"); } catch (PDOException $e) { echo "Error: " . $e->getMessage(); die(); } //准备预处理语句 $stmt = $pdo->prepare("SELECT * FROM users WHERE name=?"); //绑定参数 $stmt->bindParam(1, $name); //设置参数 $name = "John"; //执行查询 $stmt->execute(); //检查查询结果 if ($stmt->rowCount() > 0) { // 输出每行数据 while($row = $stmt->fetch()) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>"; } } else { echo "0 results"; } //关闭连接 $pdo = null; ?>
This article introduces three methods of obtaining query data, namely using MySQLi extension, using PDO extension, and using PDO prepared statements. These methods can all meet different needs well, and programmers can choose the most appropriate method according to the specific situation. By mastering these methods, you can process query data more conveniently and improve programming efficiency.
The above is the detailed content of How to get query data using PHP. For more information, please follow other related articles on the PHP Chinese website!