What are the benefits of switching from mysql to mysqli for PHP scripts?

Switching from mysql to mysqli in PHP scripts is beneficial because mysqli is an improved version of the mysql extension that provides better security, performance, and functionality. Mysqli supports prepared statements, which help prevent SQL injection attacks. Additionally, mysqli offers support for transactions, stored procedures, and multiple statements in a single query, making it a more robust option for interacting with MySQL databases.

// Connect to MySQL using mysqli
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Perform a query using mysqli
$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();