tags:

views:

62

answers:

3
+1  Q: 

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

A: 
$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.

Deniss Kozlovs
+1  A: 

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

Ben
Looks good but it looks like you forgot an "s" on user.id should be users.id.
Brian Fisher
Oops! Well spotted. Thanks! Have fixed it now.
Ben
i get this :/Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in c/krukow/news.php on line 5$query = mysql_query("SELECT username from news, users WHERE news.user_id = user.id and news.id = ".$_GET['newsID'].");");$news = mysql_fetch_assoc($query);
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
this outputs$query = mysql_query("SELECT * FROM news, users WHERE news.user_id = users.id AND news.id = ".$_GET['newsID']."");$news = mysql_fetch_assoc($query);everything but the row "text" with is the news...it is text in it so i dont understand
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 <?php and ?> tags, right? It sounds like you changed something other than just the contents of the query, if it was not doing this before...
Ben
man this is what i got$query = mysql_query("SELECT * FROM news, users WHERE news.user_id = users.id AND news.id = ".$_GET['newsID']."");$news = mysql_fetch_assoc($query);?>it write everything out exept textecho $news["user_id"]; echo $news["username"];but notecho $news['text'];
ops i had a coluimn called text in users too...i thought i had changed that..jaja it works now thx ben
Cool! :-) (btw: if you want to accept this answer, click on the "tick" symbol under the number of votes...)
Ben
A: 

wow that was fast. nice site this is. thanks guys thats great. im new working with sql databses

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