How can a beginner effectively assign values from specific columns in a MySQL database to variables in PHP?

To assign values from specific columns in a MySQL database to variables in PHP, you can use a SELECT query to retrieve the data and then fetch the results into variables using the mysqli_fetch_assoc() function. Make sure to establish a connection to the database before executing the query.

// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Select specific columns from a table
$query = "SELECT column1, column2 FROM table_name";
$result = mysqli_query($connection, $query);

// Fetch the results into variables
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $variable1 = $row['column1'];
        $variable2 = $row['column2'];
        
        // Do something with the variables
        echo $variable1 . " " . $variable2 . "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
mysqli_close($connection);