将三个表连接在一起SQL PHP

时间:2015-10-31 17:29:03

标签: php mysql

我正在处理我的项目,我希望得到来自tablesite + job_name的姓名,家人,电话号码和电子邮件来自job_list +来自关系的评论。这是我的代码:

  <fieldset class="fdex" >
        <legend><span class="style4">لیست مشاغل</span></legend>


        <?php

$db_host = 'localhost';
$db_name= 'site';
$db_table= 'tablesite';
$db_user = 'root';
$db_pass = '';




$con = mysql_connect($db_host,$db_user,$db_pass) or die("خطا در اتصال به پايگاه داده");
$selected=mysql_select_db($db_name, $con) or die("خطا در انتخاب پايگاه داده");
mysql_query("SET CHARACTER SET  utf8");

$dbresult=mysql_query("SELECT tablesite.name,
                          tablesite.family,
                          tablesite.phone_number,
                          tablesite.email,
                          job_list.job_name,
                   FROM  $db_table
                   INNER JOIN relation
                   on tablesite.id_user=relation.user_id
                   INNER JOIN job_list
                   on relation.job_id=job_list.job_id",$con);

while($amch=mysql_fetch_assoc($dbresult))
{?>

<?php
echo "* نام: "."&nbsp&nbsp&nbsp".$amch["tablesite.name"]." ".$amch["tablesite.family"]."&nbsp&nbsp&nbsp"."* عنوان خدمت: ".$amch["job_list.job_name"]."&nbsp&nbsp&nbsp"."* شماره تماس: ".$amch["tablesite.phone_number"]."&nbsp&nbsp&nbsp"."* ایمیل: ".$amch["tablesite.email"].'<br>'
.$amch["relation.comments"].'<br>';

}
?>

</fieldset>

当我运行代码时,我有错误:

  

警告:mysql_fetch_assoc()要求参数1为资源,布尔值在第259行的C:\ wamp \ www \ source \ JobList.php中给出

第259行:

 while($amch=mysql_fetch_assoc($dbresult))

tablesite:id_user,name,family,phone_number,email

job_list:job_id,job_name

relation:job_id,user_id,comments

1 个答案:

答案 0 :(得分:1)

您的查询有一个额外的逗号,不需要更新您的查询:

SELECT tablesite.name,
                      tablesite.family,
                      tablesite.phone_number,
                      tablesite.email,
                      job_list.job_name //<--it was here
               FROM  $db_table
               INNER JOIN relation
               on tablesite.id_user=relation.user_id
               INNER JOIN job_list
               on relation.job_id=job_list.job_id

您也不需要在php中指定表名:

<?php
echo "* نام: "."&nbsp&nbsp&nbsp".$amch["name"]
."     ".$amch["family"]."&nbsp&nbsp&nbsp"."* عنوان خدمت:"
.$amch["job_name"]."&nbsp&nbsp&nbsp"."* شماره تماس:"
.$amch["phone_number"]."&nbsp&nbsp&nbsp"."* ایمیل:"
.$amch["email"].'<br>'.$amch["comments"].'<br>';

}
?>