What are common ways to interact with a MySQL database using PHP?

One common way to interact with a MySQL database using PHP is to use the MySQLi (MySQL Improved) extension. This extension provides a procedural and object-oriented interface for interacting with MySQL databases in PHP. By establishing a connection to the database, executing queries, and fetching results, you can easily retrieve, insert, update, and delete data in your MySQL database.

// Establishing a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

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

// Example query to retrieve data from a table
$sql = "SELECT * FROM table_name";
$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";
}

// Close the connection
$conn->close();