What are the recommended steps for connecting to a MySQL database and executing queries in PHP?
To connect to a MySQL database and execute queries in PHP, you need to first establish a connection to the database using the mysqli_connect() function. After connecting, you can use mysqli_query() to execute SQL queries on the database. Make sure to handle any errors that may occur during the connection or query execution.
// Step 1: Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Step 2: Execute a query on the database
$sql = "SELECT * FROM table_name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Step 3: Close the connection
mysqli_close($conn);
Related Questions
- What is the correct way to clear cookies in PHP to prevent users from accessing a page using the back button or copied URLs?
- What are the potential drawbacks of implementing mail sending in the Model in PHP?
- How can JavaScript or meta tags be used for page redirection in PHP as an alternative to the header() function?