druzuz321103 2019-01-15 05:00 采纳率: 100%
浏览 53

如何修复PHP的“试图获取非对象的属性”?

What I am basically trying to do is run through a loop to look through all inventory slots in the player's inventory and figure out what item ids they are and throwback item names when the player goes onto the inventory page, I have that working.

The issue comes when I want to include quantity and I want to iterate through every slot_x_quantity table in the database in one fell swoop, but I keep getting errors like

Undefined index: 'slot_1_quantity''

I am putting $selectstatement in the query to find the quantities because I want to be able to go through slot_x_quantity 1-9 in the loop.

I've tried not even having $selectstatement and doing $query = "SELECT slot_'$indexaddone'_quantity FROM inventory WHERE char_id='$char_id'"; But then $result throws false, as if it is not able to find the table(s).

foreach($char_inv_slots as $key=>$value) {
                    if($value != 0) {
                        $item_id = $value;
                        $query = "SELECT item_name FROM items WHERE id='$item_id'";
                        $result = mysqli_query($db, $query);
                        $row = $result->fetch_assoc();
                        $item_name = $row['item_name'];

                        $indexaddone = (int)$key + 1;
                        $selectstatement = "slot_" . $indexaddone . "_quantity";

                        $query = "SELECT '$selectstatement' FROM inventory WHERE char_id='$char_id'";
                        $result = mysqli_query($db, $query) or die($query->error);
                        $row = $result->fetch_assoc();
                        $item_quantity = $row["'$selectstatement''"];

                        if($value == 8001) {
                            echo($item_name . " - " . $item_quantity);
                        } else {
                        echo($item_name . "<br>");
                    }

I want, on my inventory page, to see the " - " with only items that are stackable, but I can't seem to get the quantitys to show through this loop.

  • 写回答

1条回答 默认 最新

  • douyanqu9722 2019-01-15 06:31
    关注

    Use this code it will return only set row value and escape if row is not set already

    $row = $result->fetch_assoc();
    $item_quantity = isset($row[$selectstatement]) ? $row[$selectstatement] : "0";
    

    It will show your Item name with item quantity if any otherwise show item name with item quantity 0.

    Also Replace $row["'$selectstatement''"]; To $row[$selectstatement];

    Make sure 'slot_1_quantity' etc present in your row from where you are fetching the records otherwise item quantity will remains 0 every time.

    评论

报告相同问题?