Populate 2 column HTML table with a single PHP result set

Viewed 381

Please forgive me as I am beginner in PHP.

I am trying to populate 2 two column table with inventory information. With my current code, I have the below image: Inventory

I would like to have two stores next to each other in this table. i.e Store Number 2 and Store Number 7 on the table row in the table, then Store 10 and 11 on the same row, and so on. Below is the code I am using so far to achieve this:

global $wpdb;

$result = $wpdb->get_results( 
    $wpdb->prepare( "
        SELECT STORE_NAME,REPLACE(STORE_NAME, ' ', '-') as STOREURL, INVENTORY, STORE_NUMBER FROM StoreInventory 
        WHERE SKU = %s", 
        $product_sku 
    ) 
);

if ($result){
    echo '<table class=\'inventory\'>';
    foreach($result as $row) {
        echo '<tr><td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td></tr>';
    }
    echo '</table>';
} else {
    echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}

The problem I am having is that I am looping through the record set row by row, and adding the data to each row. I have attempted to have a loop inside a loop, which will not give me the correct results.

Is it possible to split the result set into two multi-dimensional arrays and loop through each one separately then add them to the table? Can I call out a specific row with a counter within the loop?

Any advise or direction would be a great help.

2 Answers

A relatively simple approach would be to create a dummy variable to store the column. EX:

$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
    echo '<td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td>';
    $column_number += 1;
    if ($column_number == 2) {
        echo '</tr><tr>';
        $column_number = 0;
    }
}
echo '</tr></table>';

Final answer based on ARubiksCube's answer:

if ($result){
    $column_number = 0;
    echo '<table class=\'inventory\'><tr>';
    foreach($result as $row) {
        echo '<td \' width=\'50%\' ><div><a href=\'https://shopliquornl.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>' . $row->STORE_NAME . '</a><br/>' .$row->INVENTORY. ' on hand</div></td>';
        $column_number += 1;
        if ($column_number == 2) {
            echo '</tr><tr>';
            $column_number = 0;
        }
    }
    echo '</table>';
} else {
    echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}
Related