Home  >  Article  >  Backend Development  >  Does php query data return an array?

Does php query data return an array?

王林
王林Original
2023-05-11 11:28:06429browse

Yes, PHP query data can return arrays. By using a relational database, such as MySQL, we can use PHP's MySQLi or PDO extension to connect to the database and perform query operations. When we execute a SELECT query, the database returns one or more rows, which we can then convert into an array using PHP.

The following is an example using PHP to return an array queried from a database:

// 连接到数据库
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'myusername', 'mypassword');

// 执行查询操作
$sql = "SELECT id, name, email FROM users WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => 1]);

// 获取结果数组
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// 输出结果
print_r($row);

The above code first connects to the database named "mydatabase" and queries the table named "users" , to get the name and email address of user with ID 1. It uses PDO prepared statements to execute queries that have named placeholders to prevent SQL injection attacks.

Next, the code uses PDO's fetch() method to get a row from the query results and returns the row as an associative array. Finally, the code uses the print_r() function to output the resulting array to the screen.

Here is a sample output:

Array
(
    [id] => 1
    [name] => John Smith
    [email] => john@example.com
)

As you can see, PHP query data can indeed return arrays. Using relational database and PHP extensions, we can easily connect to the database and perform various query operations such as INSERT, UPDATE, DELETE and SELECT. We can then use PHP functions to convert the results into an array and perform further processing and analysis on them.

The above is the detailed content of Does php query data return an array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn