Php pdo insert примеры

PHP MySQL Insert Data

After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

  • The SQL query must be quoted in PHP
  • String values inside the SQL query must be quoted
  • Numeric values must not be quoted
  • The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

To learn more about SQL, please visit our SQL tutorial.

In the previous chapter we created an empty table named «MyGuests» with five columns: «id», «firstname», «lastname», «email» and «reg_date». Now, let us fill the table with data.

Note: If a column is AUTO_INCREMENT (like the «id» column) or TIMESTAMP with default update of current_timesamp (like the «reg_date» column), it is no need to be specified in the SQL query; MySQL will automatically add the value.

The following examples add a new record to the «MyGuests» table:

Example (MySQLi Object-oriented)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if ($conn->query($sql) === TRUE) echo «New record created successfully»;
> else echo «Error: » . $sql . «
» . $conn->error;
>

Example (MySQLi Procedural)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if (mysqli_query($conn, $sql)) echo «New record created successfully»;
> else echo «Error: » . $sql . «
» . mysqli_error($conn);
>

Example (PDO)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDBPDO»;

try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;
// use exec() because no results are returned
$conn->exec($sql);
echo «New record created successfully»;
> catch(PDOException $e) echo $sql . «
» . $e->getMessage();
>

Источник

PDO: Insert example.

This is a beginners tutorial on how to insert rows into a MySQL database using PHP’s PDO object. Note that I have also written a tutorial on how to do a multi-insert with PDO. For this tutorial, however, I will be sticking to the basics.

CREATE TABLE IF NOT EXISTS `cars` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `make` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `model` varchar(100) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

For the purpose of this example, I have created a simple table called cars. Be sure to import the SQL above into your own database if you plan on playing around with the PDO extension.

PDO Insert example.

//MySQL connection details. $host = 'localhost'; $user = 'root'; $pass = ''; $database = 'test'; //Custom PDO options. $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false ); //Connect to MySQL and instantiate our PDO object. $pdo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options);

Once we have connected to MySQL and selected our database, we can execute a prepared insert statement:

//Create our INSERT SQL query. $sql = "INSERT INTO `cars` (`make`, `model`) VALUES (:make, :model)"; //Prepare our statement. $statement = $pdo->prepare($sql); //Bind our values to our parameters (we called them :make and :model). $statement->bindValue(':make', 'Nissan'); $statement->bindValue(':model', 'Primera'); //Execute the statement and insert our values. $inserted = $statement->execute(); //Because PDOStatement::execute returns a TRUE or FALSE value, //we can easily check to see if our insert was successful. if($inserted)< echo 'Row inserted!
'; >

The process of inserting a row into MySQL with the PDO object is actually pretty simple:

  1. We created our INSERT SQL statement. Note how we created “placeholders” such as :make and :model. Later on, these placeholders will allow us to “bind” our data to the statement. Remember that in a prepared statement, there are two rounds of communication with the MySQL server. First, we tell the MySQL about the structure of our statement by “preparing it”. Then, we send the data through by “binding” our data and executing the statement.
  2. We prepared our statement.
  3. We binded the data that we want to insert into our statement.
  4. After that, we executed the statement (thereby executing the SQL query).
  5. Finally, we checked to see if the result of PDOStatement::execute was a boolean TRUE value. If it is TRUE, then it means that the new row was inserted successfully. If it FALSE, then it means that MySQL could not insert the row. In cases like this, you will most likely encounter a PDOException error.

Inserting multiple rows with PDO.

Note that you can re-use the same statement to insert multiple rows:

//Create our SQL query. $sql = "INSERT INTO `cars` (`make`, `model`) VALUES (:make, :model)"; //Prepare our statement using the SQL query. $statement = $pdo->prepare($sql); //Bind our values to our parameters (we called them :make and :model). $statement->bindValue(':make', 'Nissan'); $statement->bindValue(':model', 'Primera'); //Execute the statement and insert our values. $inserted = $statement->execute(); //Because PDOStatement::execute returns a TRUE or FALSE value, //we can easily check to see if our insert was successful. if($inserted)< echo 'Row inserted!
'; > //For our next row, we're going to insert a Honda Civic. //We will re-use the statement that we already prepared. $statement->bindValue(':make', 'Honda'); $statement->bindValue(':model', 'Civic'); //Execute the statement and insert our values. $statement->execute();

Note how we executed the same statement twice, without having to prepare a new one for each insert.

Shorthand / Quick insert with PDO.

There is also a shorthand version.

//Create our SQL query. $sql = "INSERT INTO `cars` (`make`, `model`) VALUES (?, ?)"; //Prepare the statement. $statement = $pdo->prepare($sql); //Execute it $statement->execute(array('Honda', 'Civic'));

As you can see, this method is a lot quicker.

Related reading for PDO beginners:

Источник

Примеры использования PDO MySQL

Ниже приведены основные примеры работы с расширением PHP PDO. Такие как подключение к БД, получение, изменение и удаление данных. Подробнее о методах PDO можно узнать на php.net.

Для примеров используется таблица `category` с полями `id` , `name` и `parent` .

Подключение к серверу MySQL

$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');

Четвертым параметром конструктора PDO можно указать параметры подключения, например SQL запрос который будет выполнен сразу после подключения:

$dbh = new PDO(' mysql:dbname=db_name;host=localhost', 'логин', 'пароль', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'") );

Чтобы отследить ошибку подключения к БД используется исключение:

try < $dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль'); >catch (PDOException $e) < die($e->getMessage()); >
SQLSTATE[HY000] [1045] Access denied for user 'логин'@'localhost' (using password: YES)

Выборка из БД

Выборка одной записи

PDO позволяет использовать в запросах псевдопеременные чтобы исключить SQL инъекции. В самом запросе в место данных указывается ? или :id , а в методе execute() указываются реальные значения этих переменных.

$sth = $dbh->prepare("SELECT * FROM `category` WHERE `id` = ?"); $sth->execute(array('21')); $array = $sth->fetch(PDO::FETCH_ASSOC); print_r($array);
$sth = $dbh->prepare("SELECT * FROM `category` WHERE `id` = :id"); $sth->execute(array('id' => '21')); $array = $sth->fetch(PDO::FETCH_ASSOC); print_r($array);
Array ( [id] => 21 [parent] => 3 [name] => Хурма ) 

Выборка всех записей таблицы

Данный пример получает всю таблицу в виде ассоциативного массива:

$sth = $dbh->prepare("SELECT * FROM `category` ORDER BY `name`"); $sth->execute(); $array = $sth->fetchAll(PDO::FETCH_ASSOC); print_r($array);
Array ( [0] => Array ( [id] => 16 [parent] => 3 [name] => Абрикос ) [1] => Array ( [id] => 28 [parent] => 3 [name] => Авокадо ) . )

Получить значение поля одной записи

$sth = $dbh->prepare("SELECT `name` FROM `category` WHERE `id` = ?"); $sth->execute(array('21')); $value = $sth->fetch(PDO::FETCH_COLUMN); echo $value; // Выведет "Хурма"

Получение всех значений одного столбца таблицы

Пример получает все значения поля `name` из таблицы `category` .

$sth = $dbh->prepare("SELECT `name` FROM `category`"); $sth->execute(); $array = $sth->fetchAll(PDO::FETCH_COLUMN); print_r($array);
Array ( [0] => Мороженое [1] => Овощи [2] => Фрукты [3] => Ягоды [4] => Грибы [5] => Морепродукты [6] => Смеси . )

Получение структуры таблицы

$sth = $dbh->prepare("SHOW COLUMNS FROM `category`"); $sth->execute(); $array = $sth->fetchAll(PDO::FETCH_ASSOC); print_r($array);
Array ( [0] => Array ( [Field] => id [Type] => int(10) unsigned [Null] => NO Php pdo insert примеры => PRI [Default] => [Extra] => auto_increment ) [1] => Array ( [Field] => parent [Type] => int(11) unsigned [Null] => NO Php pdo insert примеры => [Default] => 0 [Extra] => ) [2] => Array ( [Field] => name [Type] => varchar(255) [Null] => NO Php pdo insert примеры => [Default] => [Extra] => ) )

Добавление записей в БД

$sth = $dbh->prepare("INSERT INTO `category` SET `parent` = :parent, `name` = :name"); $sth->execute(array('parent' => 1, 'name' => 'Виноград')); // Получаем id вставленной записи $insert_id = $dbh->lastInsertId();

Изменение записей

$sth = $dbh->prepare("UPDATE `category` SET `name` = :name WHERE `id` = :id"); $sth->execute(array('name' => 'Виноград', 'id' => 22));

Удаление из БД

$count = $dbh->exec("DELETE FROM `category` WHERE `parent` = 1"); echo 'Удалено ' . $count . ' строк.';

Или метод c псевдопеременными:

$sth = $dbh->prepare("DELETE FROM `category` WHERE `parent` = :parent"); $sth->execute(array('parent' => 1));

Обработка ошибок

В PDO есть метод errorInfo() который возвращает сведенья об ошибке последнего запроса.

// Таблицы `category_new` нет в БД. $sth = $dbh->prepare("INSERT INTO `category_new` SET `parent` = :parent, `name` = :name"); $sth->execute(array('parent' => 1, 'name' => 'Виноград')); $info = $sth->errorInfo(); print_r($info);
Array ( [0] => 42S02 [1] => 1146 [2] => Table 'database.category_new' doesn't exist )

Комментарии 1

О

Функция debugDumpParams объекта PDOStatement используется для вывода параметров подготовленного оператора. Это может быть полезно для отладки и устранения неполадок, поскольку позволяет увидеть точный SQL-запрос, который будет выполнен, а также значения любых установленных заполнителей.
Например, рассмотрим следующий код:

$sth = $dbh->prepare(‘SELECT * FROM users WHERE name = :name AND age = :age’);
$sth->bindParam(‘:name’, $name);
$sth->bindParam(‘:age’, $age);
$name = ‘John’;
$age = 35;
$sth->debugDumpParams();

SQL: [114] SELECT * FROM users WHERE name = :name AND age = :age
Params: 2
Key: Name: [5] :name
paramno=-1
name=[5] «:name»
is_param=1
param_type=2
Key: Name: [4] :age
paramno=-1
name=[4] «:age»
is_param=1
param_type=2

Вывод показывает SQL-запрос с заполнителями и значениями заполнителей (в данном случае :name — «John», а :age — 35). Это может быть полезно для проверки того, что в запросе используются правильные значения, или для выявления проблем с запросом или заполнителями.
Надеюсь, это поможет! Дайте знать, если у вас появятся вопросы.

Авторизуйтесь, чтобы добавить комментарий.

Источник

Читайте также:  How to convert xml to json python
Оцените статью