3

This gives a syntax error:

read -p "entry: " entry
sql="select concat('entry ', id) from mytbl where id = ?";
$mysql_conn "prepare stmnt from '${sql}'; set @id='${entry}';
 execute stmnt using @id;deallocate prepare stmnt";

It works if used directly in mysql, but not through a bash script. If only id is selected it works. But concat() throws it off. It will also work if a direct query is made without a prepared statement. What gives?

Also tried:

select concat('entry ',?)

and pass @id but it failed too.

1 Answer 1

3

The issue is quote nesting conflict. When you write:

$mysql_conn "prepare stmnt from '${sql}'..."

And ${sql} contains 'entry ', the single quotes inside clash with the outer statement's quotes.

Best solutions:

  1. Use double quotes in the PREPARE statement (Solution 1):

    $mysql_conn "prepare stmnt from \"${sql}\"; ..."
    
  2. Use a heredoc (Solution 2) - cleanest approach:

$mysql_conn <<EOF
prepare stmnt from "select concat('entry ', id) from mytbl where id = ?";
set @id='${entry}';
execute stmnt using @id;
deallocate prepare stmnt;
EOF
  1. Escape the inner single quotes (Solution 3):

    sql="select concat(\'entry \', id) from mytbl where id = ?"
    
Sign up to request clarification or add additional context in comments.

6 Comments

This answer feels as though it were generated by AI.
A fun fact : those who say AI shouldn't be used also shouldn't use documentation, like JavaScript, PHP, or any other language docs (unless the person using it has no idea what they want or what they're doing).
Not at all...the fidelity of most official docs is way higher than output from LLMs, which, as of 2025, can hallucinate and say things which aren't true.
makes perfect sense. thank you. i went with the escaped double quotes
Sure no problem =)
You still need to safe quote $entry bash side before inserting it into the SQL statement. Even with prepared statement, this is still unsafe in that it might still break the SQL syntax. I really still don't understand why the mysql shell command still is unable to transfer shell arguments to SQL variables. This would save so much headache sending SQL request fro the shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.