How can PHP beginners effectively work with databases like MySQL for storing and retrieving data?
To effectively work with databases like MySQL for storing and retrieving data in PHP, beginners can use the mysqli extension or PDO (PHP Data Objects) to interact with the database. They should establish a connection to the database, execute queries to insert, update, delete, or retrieve data, and handle errors properly.
// Establishing a connection to MySQL database using mysqli
$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();