0
-----------------------------------------
      Table Name: product_cat
-----------------------------------------
id         - int(11)     - auto_increment
           -             -
cat_name   - varchar(30) -
           -             -
branch_code- varchar(30) -
           -             -
date       - datetime    -



-----------------------------------------
      Table Name: product_brand
-----------------------------------------
id          - int(11)     - auto_increment
            -             -
parent_id   - int(11)     -
            -             -
branch_name - varchar(40) -
            -             -
category    - varchar(40) -

I applied foreign key in product_brand table by this query(alter table product_brand add constraint ta1 foreign key(parent_id) references product_cat(id))

and I am inserting data in product_brand table by following way

<table>
         <form action="index.php?tanzil=brand_added" method="post">        
     <tr>
       <td>Brand Name:</td>
       <td>
         <input type="text" name="brand_name" />
       </td>
     </tr>
     <tr>
      <td>Category:</td>
      <td>
        <select name="cat_name">

<?php
db_connect();
$q="select * from product_cat order by cat_name";
$rs=mysql_query($q);
for($i=0;$i<mysql_num_rows($rs);$i++){

$rd=mysql_fetch_object($rs);
echo"<option value='$rd->id'>$rd->cat_name</option>";

}
?>

        </select>
      </td>
    </tr>
    <tr>
     <td>
       <input type="submit" value="submit" />
     </td>
   </tr>
      </form>
 </table>

and inserting data in database by this way

db_connect();
$name_of_cat = $_POST['cat_name'];
$name_of_brand = $_POST['brand_name'];
$g ="insert into product_brand (parent_id,brand_name,category) values ('$name_of_cat','$name_of_brand','$name_of_cat')";
if(mysql_query($g)){
echo "Done";    
}
else{   
echo"Some error occured";
}

and displaying data by this way

$query= "select * from product_brand";
$result= mysql_query($query);
while($row=mysql_fetch_object($result))
{
echo $row['brand_name'];
}

but I am not getting cat_name name from product_cat table reference of parent_id

How can I get it?

4

2 回答 2

2

JOIN两张表:

SELECT
  p.id,
  p.branch_name,
  c.cat_name
FROM product_Brand     AS p
INNER JOIN Product_cat AS c ON c.id = c.parent_id;
于 2013-03-21T12:28:06.353 回答
0

由于结果必须包含“Product_brand”表中的所有行,因此尝试使用 LEFT JOIN,如下所示,

$query= "SELECT
      pb.*,
      pc.cat_name
    FROM product_Brand  pb
    LEFT JOIN Product_cat pc ON pb.id = pc.parent_id";
$result= mysql_query($query);
while($row=mysql_fetch_object($result))
{
echo $row['brand_name'];
}
于 2013-03-21T12:44:37.467 回答