What are the potential pitfalls of using the outdated mysql_* functions in PHP, and what alternative should be considered?
Using the outdated mysql_* functions in PHP poses security risks as they are vulnerable to SQL injection attacks and lack support for modern MySQL features. It is recommended to use MySQLi (MySQL Improved) or PDO (PHP Data Objects) extensions, which provide prepared statements to prevent SQL injection and support for newer MySQL features.
// Using MySQLi extension to connect to a MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform SQL query using prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "example_user";
$stmt->execute();
$result = $stmt->get_result();
// Fetch results
while ($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"] . "<br>";
}
// Close connection
$stmt->close();
$conn->close();
Related Questions
- Are there recommended resources, such as books or YouTube channels, for learning PDO in PHP with practical examples?
- How can the background color of cells be changed in FPDF using an array->row output?
- How can PHP be used to determine the frequency of specific courses on a daily, weekly, or monthly basis in a scheduling system?