1

I have 2 table message and answer. where message id = answer id. I want select using message. when message = hi then expected answer hello, hey.

Message Table:
|  id  |  message |
|   1  |    hi    |
|   2  |    hi    |
|   3  |    Hi    |

and answer table:

| id | answer |
| 1  | hello  |
| 2  | hey    |
| 3  | Hello  |

I already tried: $inp = "hi";

SELECT * FROM message JOIN answer ON message.message = answer.answer WHERE message='$inp'"

any suggestions?

Rabib
  • 45
  • 10

2 Answers2

3

Try this code :

"SELECT * FROM message JOIN answer ON message.id= answer.id WHERE message.message='".$inp."'";
Bhoomi Patel
  • 791
  • 10
  • 31
1

use common b/w each table in your case id so query should be..

SELECT * FROM message JOIN answer ON answer.id = message.id WHERE message = 'hi';

rest in php you should use different ways to run query like prepared statements in order to avoid sql injection or concatenate the variables

like

'SELECT * FROM message JOIN answer ON answer.id = message.id WHERE message = "'.$input.'"';

or mysqli_prepare() bind_params()

or learn using PDO which is good to avoid sql injections as well as supports multiple db drivers which make your work more dynamic and flexible.

Akhilesh
  • 748
  • 4
  • 17
  • thank you for your answer. but my expected output single time 2 results hello and hey. how can do this? any suggestions? – Rabib Nov 23 '18 at 08:58
  • 1
    it is giving you two answers for the message 'hi' isn't it ?? so all you need to do is loop through it using php. – Akhilesh Nov 23 '18 at 09:06
  • haha my code is working. but I forgotten to add while loop. thank you again – Rabib Nov 23 '18 at 10:08