I've got two tables; one a list of location names, another a list of companies, a field of which stores potentially multiple locations that the company operates in:
id LocationName
1 Aberdeen
2 Dundee
3 Edinburgh
4 Glasgow
idCompany CompanyName Locations
1 CompanyA 1, 2, 3, 4
2 CompanyB 2, 4
3 CompanyC 1
For each company's details page, I want to list the locations in which they operate, displaying the name of each. Eg. for Company B:
Dundee
Glasgow
etc.
Coming from a VB background, I'd just loop through each dataset and compare each to find the matches, but this is in PHP and I can't get it to work:
// Query for specific firm
$sqlCompany= "SELECT * FROM company_details WHERE CompanyID='".$CompanyID."';";
$rstCompany= mysqli_query($conn, $sqlCompany);
$row = mysqli_fetch_assoc($rstCompany);
// Query list of Locations
$sqlLocationNames= "SELECT * FROM Locations ORDER BY LocationName ASC;";
$rstLocationNames= mysqli_query($conn, $sqlLocationNames);
// Explode the field of locations into an array:
$LocationArray = $row["Locations"];
$LocationArray = explode (",", $LocationArray);
for ($i = 0; $i < count($LocationArray); $i++) {
while ($rowLocationNames = mysqli_fetch_assoc($rstLocationNames)) {
if ($LocationArray[$i]==$rowLocationNames["idLocation"]) {
echo $rowLocationNames["LocationName"]."<br />";
}
}
}
Running this for Company A, I'd expect to get the list of four locations from above, but I only get the first location (Aberdeen). I've tried every combination I can think of, to no avail. I need to keep the data structured this way, as I intend having a select multiple for inserting and also editing the data when I can get this working. Any ideas where I'm going wrong?
Locationstable with one row for every company location and join it.mysqliyou should be using parameterized queries andbind_paramto add any data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put$_POST,$_GETor data of any kind directly into a query, it can be very harmful if someone seeks to exploit your mistake.mysqliis significantly less verbose, making code easier to read and audit, and is not easily confused with the obsoletemysql_queryinterface. Before you get too invested in the procedural style it’s worth switching over. Example:$db = new mysqli(…)and$db->prepare("…")The procedural interface is an artifact from the PHP 4 era whenmysqliAPI was introduced and ideally should not be used in new code.