What are common methods for retrieving data from a MySQL database using PHP?
To retrieve data from a MySQL database using PHP, you can use the MySQLi or PDO extension. Both extensions provide methods for connecting to a MySQL database, executing queries, and fetching results. You can use SELECT queries to retrieve data from specific tables in the database and then process the results in your PHP code.
// Using MySQLi extension to retrieve data from a MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM table_name";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$mysqli->close();
Keywords
Related Questions
- What are some alternative methods for finding information on date differences in PHP if the search function is not working?
- What are the advantages of using prepared statements or mysqli_real_escape_string() when dealing with user input in PHP?
- How can a PHP beginner ensure that new users automatically appear on a member list without having to manually edit the PHP file each time?