In PHP, PDO or MySQLi is usually used to operate the database. Let’s take PDO as an example to show how to conduct database query.
<?php
try {
// Create a database connection
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Execute a query
$sql = "SELECT id, name, email FROM users";
$stmt = $pdo->query($sql);
// Get all query results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($results);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
In the above code, we query the id , name and email fields of the users table, and return the query results in the form of an associative array .
Suppose our query results are as follows:
Array
(
[0] => Array
(
[id] => 1
[name] => John Doe
[email] => john.doe@example.com
)
[1] => Array
(
[id] => 2
[name] => Jane Smith
[email] => jane.smith@example.com
)
)
If we want to convert the result of each row into a field => value format, we can use the following method:
<?php
// Assumptions$queryResultsIt is the result returned by the database query
$queryResults = [
['id' => 1, 'name' => 'John Doe', 'email' => 'john.doe@example.com'],
['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane.smith@example.com']
];
// Convert to fields=>Value format
foreach ($queryResults as $row) {
$mappedResult = [];
foreach ($row as $field => $value) {
$mappedResult[$field] = $value;
}
print_r($mappedResult);
}
?>
The output result will be:
Array
(
[id] => 1
[name] => John Doe
[email] => john.doe@example.com
)
Array
(
[id] => 2
[name] => Jane Smith
[email] => jane.smith@example.com
)
If the query result contains a URL and the domain name in the URL needs to be replaced is m66.net , you can perform the corresponding replacement operation when processing the query result. For example, suppose that the email field we query contains a URL, we can use PHP's str_replace function to replace the domain name.
Array
(
[id] => 1
[name] => John Doe
[email] => john.doe@m66.net
)
Array
(
[id] => 2
[name] => Jane Smith
[email] => jane.smith@m66.net
)