Languages
[Edit]
EN

PHP - how to make MySQL select query with MySQL?

8 points
Created by:
martineau
1140

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

1. SELECT query with MySQLi 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';

		$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
		
		if($mysqli->connect_error)
			die('Database connection error!');
		
		if($statement = $mysqli->prepare('SELECT * FROM `users` WHERE `role` = ?'))
		{
			$statement->bind_param('s', $role); // string parameter
			
			if($statement->execute())
			{
				$statement->bind_result($row_id, $row_name, $row_role);
				
				echo '<pre>';
				echo "[ID]\t[name]\t[role]<br />";

				while ($statement->fetch())
					echo $row_id . "\t" . $row_name . "\t" . $row_role . '<br />';
				
				echo '</pre>';
			}
			else
				echo 'Query execution error!';
			
			$statement->close();
		}
		else
			echo 'Query preparation error!';
		
		$mysqli->close();
	}

?>

Result:

SQL SELECT query with mysqli class - PHP / MySQL.
SQL SELECT query with mysqli 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?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

PHP - MySQL

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join