Tuesday, March 1, 2011

SQL Join maybe?

$query = mysql_query("SELECT * FROM news WHERE id = '{$_GET['id']}'"); $news = mysql_fetch_assoc($query);

$sql84 = mysql_query("SELECT username FROM users WHERE id = '".$news['user_id']."'") or exit(mysql_error()); $author = mysql_fetch_array($sql84);

is there i better way of doing this? a join maybe? how that look

From stackoverflow
  • $query = mysql_query("SELECT n.*, u.* FROM news n LEFT JOIN users u ON u.id=n.user_id WHERE n.id = ".intval($_GET['id']));
    

    Please don't forget to use intval() if value assumed is numeric.

  • It seems like you want something like this:

    (Edited to add error checking)

    $q = "select username from news, users where news.user_id=users.id and news.id=".$_GET['id'].");";
    $query = mysql_query($q) or die(mysql_error());
    

    Ben

    Brian Fisher : Looks good but it looks like you forgot an "s" on user.id should be users.id.
    Ben : Oops! Well spotted. Thanks! Have fixed it now.
    Ben : Hmmm... Not sure why. I've added error checking into the example above. You might also want to check that $_GET['id]' really contains what you expect it to contain, and perhaps try it with a hard-coded value for news.id.
    Ben : Do you mean that the code gets displayed as the output of your programme? Are you running it from the command-line or in a browser? You do have tags, right? It sounds like you changed something other than just the contents of the query, if it was not doing this before...
    Ben : Cool! :-) (btw: if you want to accept this answer, click on the "tick" symbol under the number of votes...)
  • wow that was fast. nice site this is. thanks guys thats great. im new working with sql databses

    bortzmeyer : If it works for you, Accept the answer (and upvote it) and Edit the original question, do not add an answer.

0 comments:

Post a Comment