简体   繁体   中英

Get data from a join table

I am trying to pull data from my database which ahs the following:

x3 tables:

docs
  doc_id - index
cat
  cat_id - index
doc_cat_join
  doc_id - foreign key to docs/doc_id
  cat_id - foreign key to cats/cat_id

I have inserted some data so that I have a row in cats and a rows in docs and in the join table bound a cat_id with a doc_id which all works fine. I am tying to pull that from the tables and show it, here is my approach so far but not getting anything out and am wondering where my failings are as I am getting no errors?

when I visit the cateroy page in my scripts I GET the id from the url:

    $id = $_GET['cat_id'];           

    $q = sprintf("
        SELECT
        docs.doc_id,doc_name
        FROM docs
        INNER JOIN doc_cat_join
        ON cats.cat_id = doc_cat_join.cat_id
        WHERE doc_cat_join.doc_id = '%s'
        ",

        mysqli_real_escape_string($dbc, $id) );

    $r = mysqli_query($dbc,$q)
        or die ("Couldn't execute query: ".mysqli_error($dbc));


    // FETCH AND PRINT ALL THE RECORDS

    echo '<div class="view_body">';

    while ($row = mysqli_fetch_array($r)) {
        echo '<a href="doc_view.php?doc_id='.$row["doc_id"].'"> '.$row["doc_name"]. '</a><br>';

    }
    echo '</div>';           
}

for some bizarre reason I get nothing, if I do a var_dump on $r I get the following:

string(168) " SELECT docs.doc_id,doc_name FROM docs INNER JOIN doc_cat_join ON cats.cat_id = doc_cat_join.cat_id WHERE doc_cat_join.doc_id = '24' "  

So it gets the correct category ID I am in.

I am now getting th following output:

Couldn't execute query: Unknown column 'cats.cat_id' in 'on clause'
$id = $_GET['cat_id']; 

$q = sprintf("
SELECT
*
FROM docs
INNER JOIN doc_cat_join
ON docs.doc_id = doc_cat_join.doc_id
INNER JOIN cat
ON doc_cat_join.cat_id = cat.cat_id
WHERE doc_cat_join.cat_id = '$id'
",

mysqli_real_escape_string($dbc, $id) );

print_r ($q);


// FETCH AND PRINT ALL THE RECORDS

echo '<div class="view_body">';

while ($row = mysqli_fetch_array($r)) {

echo '<a href="doc_view.php?doc_id='.$row["doc_id"].'"> '.$row["doc_name"].        '</a><br>';

}
echo '</div>';           
}

your query is wrong I think.

as per your input and query design, your query should be as per below-

SELECT d.doc_id, d.doc_name 
FROM docs AS d 
INNER JOIN doc_cat_join AS dc ON dc.doc_id = d.doc_id WHERE dc.cat_id = '24';

Note: If it is not then show what output you require.

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