How can a beginner effectively retrieve and manipulate data from a MySQL database using PHP?
To retrieve and manipulate data from a MySQL database using PHP, a beginner can use the mysqli extension in PHP. This extension allows for connecting to a MySQL database, executing queries, fetching results, and manipulating data as needed. By using functions such as mysqli_connect, mysqli_query, mysqli_fetch_assoc, and mysqli_close, beginners can effectively interact with a MySQL database in their PHP scripts.
// Connect to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database_name");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Example query to retrieve data
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Fetch and manipulate data
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
// Manipulate data here
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "No results found";
}
// Close the connection
mysqli_close($connection);