$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$items = 'SELECT items FROM menus';
$itemLink = 'SELECT itemLink FROM menus';
$itemQuery = $db->query($items);
$linkQuery = $db->query($itemLink);
$fetchItem = $itemQuery->fetch(PDO::FETCH_ASSOC);
$fetchLink = $linkQuery->fetch(PDO::FETCH_ASSOC);
$merged = array_merge($fetchItem,$fetchLink);
foreach($merged as $key=>$value){
echo "${key} => ${value} <br />";
}
This is what it looks like in the database:
items |itemLink
----------------------
Kill Bill|Kill Bill link
Preman |Preman link
So, the expected output, or at least what I thought must be this:
items => Kill Bill
items => Preman
itemLink => Kill Bill Link
itemLink => Preman Link
But the resulted output from the code is this:
items => Kill Bill
itemLink => Kill Bill Link
It’s missing the other items and itemLink
So, how do I achieve the output that I want?
This only fetches the first row of each resultset. You need
fetchAll:and adjust the rest of your code.
EDIT:
The call of
fetchonly retrieved the first row of the resultset, whereasfetchAllparses the complete resultset into an Array. So the Objects look like this afterwards:array_mergeconcatenate both arrays to the following:So we now have a two dimensional array. To traverse the values we need first to select each
$entry, which is done in the outerforeachand can afterwards access the key/value structure in the innerforeach.As pointed out in the other comment: If you want to preserve the connection between
itemsanditemLink, you should change the query in the first place to