The select()
function in PHP is used to retrieve data from a database table. It is part of the PHP Data Objects (PDO) extension, which provides a consistent interface for accessing databases.
Here is an example of how to use the select()
function in PHP:
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare the SQL statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE age > :age');
// Bind the parameter value
$stmt->bindParam(':age', 18, PDO::PARAM_INT);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results
foreach ($results as $row) {
echo $row['name'] . ' - ' . $row['email'] . '<br>';
}
In this example, we first establish a database connection using the PDO constructor. Then, we prepare an SQL statement using the prepare()
method, which includes a placeholder :age
for a parameter value. We bind the parameter value using the bindParam()
method, specifying the data type as PDO::PARAM_INT
to ensure it is treated as an integer.
Next, we execute the query using the execute()
method. The results are fetched using the fetchAll()
method, which returns an array of associative arrays representing the rows returned by the query.
Finally, we loop through the results and echo out the values of the name
and email
columns for each row.
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站