Languages
[Edit]
EN

PHP - how to make MySQL select query with PDO?

3 points
Created by:
Marcin
15710

In PHP it is possible to make SQL SELECT query with PDO in following way.

1. SELECT query with PDO example

<?php

	if(isset($_GET['role']))
	{
		$role = $_GET['role'];

		$db_name = 'test';
		$db_host = '127.0.0.1'; // 'localhost'
		$db_username = 'root';
		$db_password = 'root';

		$dsn = 'mysql:dbname=' . $db_name . ';host=' . $db_host . ';charset=utf8';
		$pdo = new PDO($dsn, $db_username, $db_password);
		
		$statement = $pdo->prepare('SELECT * FROM `users` WHERE `role` = :role');

		if($statement === FALSE)
			die('Query preparation error!');

		$parameters = array(
			'role' => $role
		);

		if($statement->execute($parameters))
		{
			echo '<pre>';
			echo "[ID]\t[name]\t[role]<br />";

			while ($row = $statement->fetch(PDO::FETCH_OBJ))
			{
				//echo print_r($row, true);
				
				echo $row->id . "\t" . $row->name . "\t" . $row->role . '<br />';
			}
		
			echo '</pre>';
		}
		else
			echo 'Query execution error!';
	}

?>

Result:

SQL Injection prevention with PDO class - PHP / MySQL.
SQL SELECT query with PDO class - PHP / MySQL.

2. Database preparation

create_tables.sql file:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(100) NOT NULL,
	`role` VARCHAR(15) NOT NULL,
	PRIMARY KEY (`id`)
)
ENGINE=InnoDB;

insert_data.sql file:

INSERT INTO `users`
	(`name`, `role`)
VALUES
	('John', 'admin'),
	('Chris', 'moderator'),
	('Kate', 'user'),
	('Denis', 'moderator');

See also

  1. PHP - how to prevent SQL injection?
  2. PHP - how to make MySQL insert query with PDO?
  3. PHP - how to make MySQL update query with PDO?
  4. PHP - how to make MySQL delete query with PDO?
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join