📜  php forech pdo - PHP (1)

📅  最后修改于: 2023-12-03 15:33:29.232000             🧑  作者: Mango

PHP foreach PDO

Introduction

If you are a PHP developer, you might have used the foreach loop to iterate through an array for various purposes. Similarly, if you have worked with databases in PHP, you might be familiar with the PDO library, which provides a consistent interface for accessing different types of relational databases.

In this article, we'll explore how to use the foreach loop with PDO to fetch data from a database and display it in an HTML table.

Setting up the Database

Before we get started, we need to set up a simple database table and add some test data. Let's create a table called "users" that has three columns: "id", "name", and "email".

CREATE TABLE users (
  id INT(11) NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(50) NOT NULL,
  PRIMARY KEY (id)
);

INSERT INTO users (name, email) VALUES
('John Doe', 'john.doe@example.com'),
('Jane Smith', 'jane.smith@example.com'),
('Bob Johnson', 'bob.johnson@example.com');
Connecting to the Database

We'll use PDO to connect to the database and retrieve data from the "users" table. Here's how we can do that:

$dsn = 'mysql:host=localhost;dbname=mydatabase;charset=utf8';
$username = 'myusername';
$password = 'mypassword';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    exit;
}

In the above code, we first create a DSN (Data Source Name) that specifies the host, database name, and character set we want to use. We then create a PDO instance by passing in the DSN, username, and password.

We also set the ATTR_ERRMODE attribute to ERRMODE_EXCEPTION, which tells PDO to throw exceptions if there are any errors.

Fetching Data with foreach and PDO

Now that we have a PDO instance, we can use it to fetch data from the "users" table and display it in an HTML table using foreach. Here's how we can do that:

$stmt = $pdo->query('SELECT * FROM users');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (count($users) > 0) {
	echo '<table>';
	echo '<tr><th>ID</th><th>Name</th><th>Email</th></tr>';
	foreach ($users as $user) {
		echo '<tr>';
		echo '<td>' . $user['id'] . '</td>';
		echo '<td>' . $user['name'] . '</td>';
		echo '<td>' . $user['email'] . '</td>';
		echo '</tr>';
	}
	echo '</table>';
} else {
	echo 'No users found.';
}

In the above code, we first execute a SQL query to select all columns from the "users" table. We then fetch all rows using fetchAll and store them in the $users array.

If $users contains any rows, we display them in an HTML table using foreach. For each row, we output the "id", "name", and "email" columns in separate table cells.

Conclusion

Using foreach with PDO is a powerful and convenient way to fetch data from a database and display it in a user-friendly format. With a few lines of code, we can get our data from the database, loop through it using foreach, and output it in an HTML table.