1

I'm trying to echo the values of an associative array that contains all the rows in a table using foreach in a table.

Here is the code:

<?php 
    $result = doSql("SELECT * FROM carts WHERE userID =".$userID);
     if($result && mysqli_num_rows($result)>0) {
        $cartRows = mysqli_fetch_all($result); 

             foreach($cartRows as $key => $value) {

                echo "<tr>
                    <td scope='col'>" .$value['cartID']. "</td>
                    <td scope='col'>" .$value["productToCartQty"]. "</td>
                    <td scope='col' colspan='2'>".$value['invoiced']."</td>
                    <td scope='col' colspan='2'>" .$value['customization']."</td>
                   </tr>";
                }
            } 
 ?>

The error: Array to string conversion

I don't understand why I'm getting this error as I am only echoing out the value inside of the array $value i.e. echo $value['cartID']?

Here is the screenshot of the error: https://gyazo.com/cdc8dde8c2e09e91b5209c2b50bcb72c

Any ideas?

2
  • Do print_r($cartRows) before foreach and see if its really an array Commented Nov 19, 2015 at 4:23
  • you can use mysqli_fetch_array($result) Commented Nov 19, 2015 at 4:24

1 Answer 1

1

You need to change:

$cartRows = mysqli_fetch_all($result);

to:

$cartRows = mysqli_fetch_all($result,MYSQLI_ASSOC);
Sign up to request clarification or add additional context in comments.

1 Comment

Omg! It worked. The reason why I left out the second parameter is because it was optional (I researched). Can please explain why I was getting the error: String to Array conversion if I don't have that parameter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.