How to assign the result of a MySQL query into a variable?

MySQLMySQLi Database

Use @anyVariableName to assign the result of a query into a variable. Let us first create a table −

mysql> create table DemoTable1864
     (
     Id int,
     FirstName varchar(20),
     LastName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1864 values(101,'Chris','Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1864 values(102,'David','Miller');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1864 values(103,'Adam','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1864 values(104,'John','Doe');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from  DemoTable1864;

This will produce the following output −

+------+-----------+----------+
| Id   | FirstName | LastName |
+------+-----------+----------+
|  101 | Chris     |    Brown |
|  102 | David     |   Miller |
|  103 | Adam      |    Smith |
|  104 | John      |      Doe |
+------+-----------+----------+
4 rows in set (0.00 sec)

Here is the query to assign the result of a query into a variable −

mysql> select @fName:=FirstName,@lName:=LastName
     from DemoTable1864
     where Id=103;

This will produce the following output −

+-------------------+------------------+
| @fName:=FirstName | @lName:=LastName |
+-------------------+------------------+
| Adam              |            Smith |
+-------------------+------------------+
1 row in set (0.00 sec)
raja
Published on 26-Dec-2019 07:16:28
Advertisements