3

I have two tables: users and threads. When a thread is created, it will store the user_id in the table as author_id. I want to display the thread name and the username of its author with the same query. I am currently using two querys as shown:

$query2 = mysql_query("SELECT author_id FROM threads WHERE id = $threadId") or die(mysql_error());
$result2 = mysql_fetch_array($query2);
$author_id = $result2['author_id'];
$query3 = mysql_query("SELECT username FROM users WHERE id = $author_id") or die(mysql_error());
$result3 = mysql_fetch_array($query3);
$author_name = $result3['username'];
1
  • 2
    Follow a SQL tutorial. It will cover basic RA constructs such as joins (which must already be known about, as it was a added as a tag..). Commented Dec 16, 2015 at 3:19

2 Answers 2

4
<?php
$sql = '
    SELECT t.name, u.username
    FROM threads t
    JOIN users u ON t.author_id = u.id
    WHERE t.id = ' . (int)$threadId . '
';
list($thread_name, $author_name) = mysql_fetch_row(mysql_query($sql));

P.S. Mysql php extension is deprecated.

Sign up to request clarification or add additional context in comments.

3 Comments

(int) before variable casts it to the integer type. It prevents sql-injection attacks.
ah ok thanks! So anytime I have a GET I should use a variable casts on it when receiving it?
If u expect int or float, you may use type casting. if string - use mysql_real_escape_string (php.net/manual/en/function.mysql-real-escape-string.php). Alternative is not to compose sql directly via string concat, but use prepared statements (for example with mysqli extension: php.net/manual/en/mysqli.quickstart.prepared-statements.php).
1

Try this query:

SELECT username 
FROM users 
WHERE id = (SELECT author_id 
            FROM threads 
            WHERE id = $threadId 
            LIMIT 1)

Note: Limit 1 is not mandatory as id is unique.

Comments

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.