What is the correct syntax for selecting all records from a table in PHP using a SELECT statement?
To select all records from a table in PHP using a SELECT statement, you need to establish a connection to your database, prepare and execute the SQL query, and fetch the results. The SQL query should be in the format "SELECT * FROM table_name". This will retrieve all columns and rows from the specified table.
// Establish a connection to the database
$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);
}
// Select all records from a table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Fetch and display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();