How can PHP beginners learn to effectively use MySQL for database operations in their scripts?
PHP beginners can effectively learn to use MySQL for database operations by studying the basics of SQL queries, understanding how to connect to a MySQL database using PHP, and learning about functions like mysqli_query() for executing queries. They can also benefit from using prepared statements to prevent SQL injection attacks. Practice and experimentation with sample databases can help solidify their understanding.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Example SQL query
$sql = "SELECT * FROM users";
$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();
?>