简体   繁体   中英

While loop displaying result 3 times

Basicly I'm trying to make a simple news feed but I'm stuck at the moment as my while loop display the result 3 times, why is this? :/

<?php 
$sql ="SELECT
            *
        FROM
            news,
            admins";
$result = mysql_query($sql);

if(!$result)
{
    echo 'Error while selecting from database. Please contact the administration team';
} else {
    while($row = mysql_fetch_assoc($result))
    {
        echo '
        <div class="content_news">
            <h1>' . $row['news_name'] . '</h1>
            <p style="font-size:12px;">Posted by <b>' . $row['admin_name'] . '</b> on ' . $row['news_date'] . '
            <p>' . $row['news_description'] . '</p>
            <a href="' . $row['news_link'] . '">read more</a>
        </div>
        ';
    }
}

?>

If you'd like to see what I am talking about: http://freewallpaperblog.com/freshrp/

Ignore the last 2(those are static html not php)

You either have 3 admins or 3 rows of news. Your query makes a direct multiplication between tables. Try "left join" instead...

your query selects data from 2 tables ( news , admins ) so it joins every row of 1st table with every row of 2nd table

SELECT * FROM news, admins

i recommend you to use following query

SELECT news.*, admins.admin_name FROM news
INNER JOIN admins ON news.admin_id = admins.id

where admin_id is your correct column name

SELECT * FROM news
INNER JOIN admins ON admins.id = news.adminid

Or whatever adminid is in the news table.

Try the following query:

 SELECT
                *
            FROM
                news
    Inner join admins on news.admin_id = admins.id

You made no JOIN statement in your SQL, as someone else has already commented on in your question. It would help if you posted the associated fields you're grabbing, but based on your $row keys, my best guess is the following should work for you (but I can't promise it will without knowing how your database is designed, I can only infer from the variable names):

$sql = "SELECT news.name, news.date, news.description, news.link, admins.name"
. "FROM news"
. "INNER JOIN admins"
. "ON news.name=admins.name"

References:

http://www.w3schools.com/sql/sql_join_inner.asp

http://www.w3schools.com/sql/sql_join_left.asp

http://dev.mysql.com/doc/refman/5.0/en/join.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM