Search code examples
phpinfo

How to add item information via item id to fetched array codes using mysqli_fetch_array via foreach?


I'm trying to have information show for each item like items in a shop.

like so:

if user has access code 1234, show in foreach via mysqli_fetch_array

in foreach: detects 1234 and shows info for that item

I have a table for the item info and a table for the user access codes connecting to users via user_id.


current codes I have for attempting this:

for fetching arrays/codes via mysqli_fetch_array:

  if (isset($_SESSION['user_login'])) {
$access_query = mysqli_query($connection, "SELECT access FROM user_access WHERE user_id = '$user_id'");
$access_codes = Array();
while ($row = mysqli_fetch_array($access_query,MYSQL_BOTH)) {
    $access_codes[] =  $row['access'];  
}
 }

attempting to grab information for each item with existing item number/access number:

   if (isset($_SESSION['user_login'])) {
    $info_query = mysqli_query($connection, "SELECT * FROM item_info WHERE item_id = '$access_codes'") or die (mysqli_error($connection));
    $info_assoc = mysqli_fetch_assoc($info_query);
    $info_info = $info_assoc['info_id'];
 }

foreach:

foreach ($access_codes as $item_id) {


$item_id = $item_info;

?>

<div style="background-color: #F2F2F2; border: 1px #E3E3E3 solid; padding: 20px; margin: 5px; width: 150px; float: left;"><?php echo $item_id;?></div>


<?php

}
?>

I do have it to the point where it shows the style for each item, but won't show anything. It knows that there are items, and how many, just doesn't show anything within the style.


Solution

  • I think you can simply all that code if you do a JOIN query -

    SELECT i.*
    FROM user_access a 
    LEFT JOIN item_info i 
    ON i.item_id = a.access  
    WHERE a.user_id = '$user_id'
    

    This joins together your user_access table with your item_info table on access = item_id, and where user_id is the logged in user.

    then your code can be reduced to -

    if (isset($_SESSION['user_login'])) {
        $info_query = mysqli_query($connection, "SELECT i.* FROM user_access a LEFT JOIN item_info i ON i.item_id = a.access  WHERE a.user_id = '$user_id'");
        while ($row = mysqli_fetch_assoc($info_query)) { ?>
              <div style="background-color: #F2F2F2; border: 1px #E3E3E3 solid; padding: 20px; margin: 5px; width: 150px; float: left;"><?php echo $row['vid_id']; ?></div>
       <?php }
    }