display data from two Mysql tables by getting values from drop down list using php

对着背影说爱祢 提交于 2020-01-06 08:16:25

问题


I have two tables countries, location whose fields are

_countries
    countryid(Primary Key)
    countryname

_location
    locationid(primarykey)
    locationname
    countryid(Foreign key from countries table)

Every thing is done using JavaScript,AJAX and php that when a user selects a country from drop down list, locations against each country will be displaced but the mysql query is not working I am Using the Below Query

$sql="SELECT _location.locationname, _countries.countryname FROM _location 
INNER JOIN _countries ON _location.countryid='".$q."'";

//$q is the countryid selected from drop down list i got it through javascript and php

The drop down list is populated from the countries table My Question is when a user selects a country name from the drop down list what will be the mysql query that fetch the location name against each country name and display data like this

||Location name||Country Name||
  Islamabad       Pakistan
  Karachi         Pakistan

回答1:


 $sql = "SELECT l.locationname, c.countryname
FROM
_countries c
LEFT JOIN _location l ON c.countryid = l.countryid
WHERE c.countryid = ".(int)$q;



回答2:


You want to fetch data from 2 tables and when you using join in this case you must use left join to reach your result change your inner join to left join

I think it works

$sql="SELECT _location.locationname, _countries.countryname FROM _location 
LEFT JOIN _countries ON _location.countryid='".$q."'";


来源:https://stackoverflow.com/questions/6495657/display-data-from-two-mysql-tables-by-getting-values-from-drop-down-list-using-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!