MySQL INSERT ... SET

MySQL supports an INSERT ... SET form for inserting one row by assigning values directly to column names. It is a MySQL-specific alternative to the standard INSERT ... VALUES syntax and can be convenient when a row has many columns.

INSERT INTO library SET book_name = 'Learning MySQL', author = 'plus2net group';

Columns that have an AUTO_INCREMENT value or a suitable DEFAULT can be omitted.

Insert into the student table

INSERT INTO student SET name = 'my_name', class = 'my_class', mark = 80, gender = 'Male';

PDO prepared statement

Use parameters for values coming from a form or another external source.

<?php
require 'config.php'; // Database connection

$name = 'Alex R';
$class = 'Five';
$mark = 70;
$gender = 'Female';

$query = 'INSERT INTO student SET name = :name, class = :class, mark = :mark, gender = :gender';
$stmt = $dbo->prepare($query);
$stmt->execute([
    ':name' => $name,
    ':class' => $class,
    ':mark' => $mark,
    ':gender' => $gender
]);

$member_id = $dbo->lastInsertId();
echo 'Thanks. Your membership id = ' . $member_id;
?>

This also corrects an error in the older sample where the mark placeholder was accidentally bound to the name variable.

MySQLi prepared statement

<?php
require 'config.php'; // MySQLi connection in $connection

$name = 'my_name';
$class = 'Three';
$mark = 70;
$gender = 'Male';

$query = 'INSERT INTO student SET name = ?, class = ?, mark = ?, gender = ?';
$stmt = $connection->prepare($query);
$stmt->bind_param('ssis', $name, $class, $mark, $gender);
$stmt->execute();

echo 'No. of records inserted: ' . $stmt->affected_rows;
echo ' Insert ID: ' . $connection->insert_id;
?>
No. of records inserted: 1
Insert ID: 52

PDO tutorial | MySQLi tutorial | MySQLi connection

Student table SQL dump




Subscribe to our YouTube Channel here



plus2net.com
anjali vaswani

18-01-2011

can set command be also used for checking a value in the field of one column and entering value in other column. example: if we want to enter value of y corresponding to its value o x in table t1 where x and y are columns of table t1 and x value is already entered in the database




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer