What are common errors encountered when using PHP scripts with MySQL databases?

Common errors encountered when using PHP scripts with MySQL databases include syntax errors in SQL queries, connection errors, and data type mismatches. To solve these issues, ensure that SQL queries are written correctly, check the connection to the database, and make sure that data types in PHP variables match the corresponding database columns.

// Example code snippet to connect to a MySQL database and execute a query

// Database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

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

// SQL query
$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";
}

$conn->close();