Data exchange between tables in the database

When the user id from the ‘members’ table is entered into the ‘messages’ table, how to make this id mean the first name (name) or last name (username) of the user.


Answer 1, authority 100%

You’re phrasing your question in a strange way. I would venture to suggest that when displaying a message, you do not want to show the user ID, but his first name (last name). Then this is done with a query like this:

select messages.msgtext, members.name from messages inner join members on members.userid=messages.userid;

Regards

to call from php:

mysql_query("select messages.msgtext, members.name from messages inner join members on members.userid=messages.userid");

explanations:

  1. In SQL, table and field names do not need to be enclosed in internal quotes. Required – only if the table/field name matches a reserved (service) SQL word. Therefore, I wrote without …

  2. messages – table with messages. msgtext – this is how I named the field in the messages table that contains the message text (I just don’t know your name). messages.msgtext is a direct reference to a field by name of both the field and the table. This format is used, in particular, when several tables are combined that have the same field names. Otherwise, mysql cannot determine which table field you “mean”…

  3. inner join – joining tables according to the condition specified further after on. on members.userid=messages.userid – the condition by which the merging occurs (i.e. records corresponding to each other are searched). In this case, the userid field value from the members table must match the userid value from the messages table.

I advise you to read something about SQL/MySQL…