Get LAST_INSERT_ID in this bash script

194
October 30, 2019, at 03:30 AM

I have a script executing MySQL queries (see below). If it's a INSERT query, I want to return the LAST_INSERT_ID(),

mysql_exec_result=$(
    printf "%s\n" \
      "[client]" \
      "user=${CONFIG_DB_USERNAME}" \
      "password=${CONFIG_DB_PASSWORD}" \
      "host=${CONFIG_DB_HOST}" \
      "port=${CONFIG_DB_PORT}" \
      "database=${CONFIG_DB_DATABASE}" \
      | HOME="/sys" mysql --defaults-file=/dev/stdin ${opts} -e "${query}"
  )

Thank you for the help!

Answer 1

As you are executing the query from outside of MySQL, you are open to use bash commands to execute further commands dependent on the first.

You can store your query in a variable, and then run an if statement like the below example:

query="INSERT.....";
if [[ $query == *"INSERT"* ]]; 
then 
mysql -e "$query; SELECT LAST_INSERT_ID();"
else
mysql -e "$query"
fi

In the above, if the query that you are executing contains any INSERT command, then it will get you the LAST_INSERT_ID after the INSERT is ran.

If the query does not contain an INSERT, then it will action the query without getting the LAST_INSERT_ID following query completion.

The "mysql -e" command can be amended to include your required flags accordingly.

The if statement example provided, can be put on a one line as per the below:

query="INSERT....."; if [[ $query == *"INSERT"* ]]; then mysql -e "$query; SELECT LAST_INSERT_ID();"; else mysql -e "$query"; fi
Rent Charter Buses Company
READ ALSO
How to customize orangeHRM to add more than 10 custom list

How to customize orangeHRM to add more than 10 custom list

How to customize orangeHRM to add more than 10 custom list in Custom List Section, I have tried to add custom11 variable its only saving in Database but when tried to view its showing internal error contact DB admin, is there any any change that need to be done in EmployeeDaophp

92
email send to user using databse information

email send to user using databse information

i m try to add code but it is coming only one user data, i m login to different user and send request then also only one user information mail i m getting please help to solve this issue

102
Mysql - Looping through a date range to perform a select & intert query

Mysql - Looping through a date range to perform a select & intert query

I am trying to loop through a date range in mysql: SET @dadate = '2018-01-01'; SET @enddate = '2019-10-28';

111
How do I create different registration forms using Laravel 6 [on hold]

How do I create different registration forms using Laravel 6 [on hold]

I am new to laravel, i have successfully created 3 new users (admin, company, employee)with different tablesI need help in creating 3 different registration forms which has different input fields

115