What strategies can be implemented to streamline the process of connecting and accessing data from a shared database in PHP applications?
To streamline the process of connecting and accessing data from a shared database in PHP applications, one strategy is to create a separate file for database connection and include it in all relevant PHP files. This way, you can easily make changes to the database connection details in one place. Additionally, using prepared statements can help prevent SQL injection attacks and make querying the database more efficient.
// db_connect.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
```
```php
// index.php
<?php
include 'db_connect.php';
// Query the database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- Are there any best practices for improving the readability of PHP code for prime number search?
- What are the potential pitfalls of not properly closing loops and conditional statements in PHP?
- How can the issue of "mysql_num_rows(): supplied argument is not a valid MySQL result resource" be addressed in PHP?