How can a beginner effectively incorporate a database into their PHP script?

To incorporate a database into a PHP script, a beginner can start by establishing a connection to the database using PHP's built-in functions like mysqli or PDO. They can then execute SQL queries to interact with the database, such as inserting, updating, or retrieving data. It's important to properly handle errors and sanitize user input to prevent SQL injection attacks.

// Establish a connection to the 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";
}

$conn->close();