Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

PHP - how to make MySQL insert query with PDO?

0 contributions
8 points

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

1. INSERT query with PDO example

<?php

	if(isset($_GET['name']) && isset($_GET['role']))
	{
		$name = $_GET['name'];
		$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);

		$query = 'INSERT INTO `users` (`name`, `role`) VALUES (:name, :role)';
		$statement = $pdo->prepare($query);

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

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

		if($statement->execute($parameters))
		{
			$count = $statement->rowCount();

			if($count > 0)
			{
				$id = $pdo->lastInsertId('id');
				
				echo 'Last added user has id ' . $id . '.';
			}
			else
				echo 'Add user operation error!';
		}
		else
			echo 'Query execution error!';
	}

?>

Running:

http://localhost/add-user.php?name=Matt&role=moderator

Result:

SQL INSERT query with PDO class - PHP / MySQL.
SQL INSERT query with PDO class - PHP / MySQL.

Database:

Database state after SQL INSERT query with PDO class - HeidiSQL.
Database state after SQL INSERT query with PDO class - HeidiSQL.

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 select query with PDO?
  3. PHP - how to make MySQL update query with PDO?
  4. PHP - how to make MySQL delete query with PDO?
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more