PHP MySQL Select Data
To select data from a MySQL database using PHP, you can use either the MySQLi extension or PDO
Here's how you can use prepared statements with MySQLi and PDO:
Using MySQLi:
<?php // MySQLi Configuration $servername = "localhost"; // Change this to your MySQL server address $username = "username"; // Change this to your MySQL username $password = "password"; // Change this to your MySQL password $database = "dbname"; // Change this to your MySQL database name // Create connection $conn = new mysqli($servername, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // SQL statement $sql = "SELECT * FROM users"; // Execute the query $result = $conn->query($sql); // Check if there are any rows returned if ($result->num_rows > 0) { // Output data of each row while ($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "You can click on above box to edit the code and run again.
"; } } else { echo "0 results"; } // Close connection $conn->close(); ?>
Output
Using PDO :
<?php // PDO Configuration $servername = "localhost"; // Change this to your MySQL server address $username = "username"; // Change this to your MySQL username $password = "password"; // Change this to your MySQL password $database = "dbname"; // Change this to your MySQL database name try { // Connect to MySQL using PDO $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); // Set PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // SQL statement $sql = "SELECT * FROM users"; // Prepare the statement $stmt = $conn->prepare($sql); // Execute the statement $stmt->execute(); // Fetch all rows as associative array $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Output data of each row foreach ($rows as $row) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "You can click on above box to edit the code and run again.
"; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } // Close connection $conn = null; ?>