In the context of PHP development, what are the best practices for connecting to databases and querying data, considering the deprecation of mysql_* functions?
With the deprecation of mysql_* functions in PHP, it is recommended to use either MySQLi (MySQL Improved) or PDO (PHP Data Objects) for connecting to databases and querying data. These extensions provide more secure and efficient ways to interact with databases, preventing SQL injection attacks and offering better performance.
// Using MySQLi for connecting to a database and querying data
$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);
}
// Query data
$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
- What are the best practices for extracting and manipulating year values from dates in PHP to avoid discrepancies like the one mentioned in the forum thread?
- What are the best practices for handling user input from a form in PHP?
- How can PHP developers ensure that only specific images are updated when editing an entry with multiple images in a database?