21

I get the following error listed below and was wondering how do I fix this problem.

Not unique table/alias: 'grades'

Here is the code I think is giving me the problem.

function getRating(){
$dbc = mysqli_connect ("localhost", "root", "", "sitename");

$page = '3';

$sql1 = "SELECT COUNT(*) 
         FROM articles_grades 
         WHERE users_articles_id = '$page'";

$result = mysqli_query($dbc,$sql1);

if (!mysqli_query($dbc, $sql1)) {
        print mysqli_error($dbc);
        return;
}

$total_ratings = mysqli_fetch_array($result);

$sql2 = "SELECT COUNT(*) 
         FROM grades 
         JOIN grades ON grades.id = articles_grades.grade_id
         WHERE articles_grades.users_articles_id = '$page'";

$result = mysqli_query($dbc,$sql2);

if (!mysqli_query($dbc, $sql2)) {
        print mysqli_error($dbc);
        return;
}

$total_rating_points = mysqli_fetch_array($result);
if(!empty($total_rating_points) && !empty($total_ratings)){
// set the width of star for the star rating
$rating = (round($total_rating_points / $total_ratings,1)) * 10; 
echo $rating;
} else {
    $rating = 100; 
    echo $rating;
}
}
tEcHnUt
  • 393
  • 3
  • 4
  • 7

4 Answers4

33

The problem seems to be here:

SELECT COUNT(*) 
FROM grades 
JOIN grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'"

You are trying to join the table grades to itself. You probably meant to join with articles_grades.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
7

You need to use an alias if you're using the same name twice:

SELECT FROM grades g1 ... 
JOIN grades g2 ON g1.id = g2.grade_id ...

Be sure that you intended to use the same name twice, and didn't mistakenly enter the same name twice.

Sampson
  • 265,109
  • 74
  • 539
  • 565
2

it's saying that because you have table name grades in the query twice

sathish
  • 6,705
  • 3
  • 30
  • 35
0

I thin that in the $sql2 query the second table isn't grades but article_grades. so it will be:

"SELECT COUNT(*) 
         FROM grades 
         JOIN articles_grades ON grades.id = articles_grades.grade_id
         WHERE articles_grades.users_articles_id = '$page'"
mck89
  • 18,918
  • 16
  • 89
  • 106