Vinayak Garg
Vinayak Garg

Reputation: 6616

How to get user input in MySQL?

Consider this simple Relation MyRel(A, B)
I wanted to display A based on value of B.
Here I would ask value of B from user. Is it possible in MySQL? How can I do it?

My query would be something like this SELECT A FROM MyRel WHERE B = [user_input].

Also Note that I am not using PHP or any other language with MySQL. I will execute this on Linux terminal.

Upvotes: 1

Views: 7636

Answers (2)

F.P
F.P

Reputation: 17831

If you are on the terminal anyway, why not write a little script around your functions and get the user input there, store it in variables and then send the mysql queries?

AFAIK there is no native method in MySQL that allows something like this, because SQL is there to query the data, not the user.

Small example:

echo "Please specify 'b'"
read b
mysql -u username -ppassword -D dbname -e "SELECT A, B FROM MyRel WHERE B = '$b'"

Upvotes: 3

Stéphane
Stéphane

Reputation: 1546

You could use this command:

echo "SELECT A FROM MyRel WHERE B = [user_input]" | mysql -u login -ppassword db_name

Then you get the result on standard output. You can redirect it in a file or get it in a variable if you're in a bash script.

Upvotes: 2

Related Questions