1

I am trying to create a php array that holds all fields and rows of the mysql query that is executed. I have tried the below syntax, but when I do a echo nothing is displayed.

<?php
$con=mysqli_connect("server", "user", "pass", "db");

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM testTable LIMIT 10";
$result = mysqli_query($con,$sql);


foreach($array as $index => $value){
    echo "<p>\$index: {$index}; \$value: {$value[0]}</p>";
   var_export($value);
}

mysqli_free_result($result);

mysqli_close($con);
?>```

If I change the foreach loop and use $result instead of $array - it will print on screen 

    $index: 0; $value:

    $index: 1; $value:

And I want the actual elements (or is values the right word) of the array.  
4
  • 2
    What is $array? Surely you meant foreach($result as $index => $value){? You're not doing anything with the result of the query. Commented Jul 28, 2019 at 22:11
  • if I use $result it prints on screen $index: 0; $value: $index: 1; $value: - I want the actual values Commented Jul 28, 2019 at 22:14
  • php.net/manual/de/mysqli-result.fetch-row.php Commented Jul 28, 2019 at 23:03
  • @cotton - are saying I'll have to iterate each of the fields returned from the select statement in the print statement? Commented Jul 29, 2019 at 0:35

1 Answer 1

1

Okay, following on from your edit and what Obsidian said. Your loop is now correct you just need to update your echo now. Try this and let me know the result:

foreach($result as $index => $value){
    echo "<p>\$index: " . $index . "; \$value: " . $value . "</p>";
    var_export($value);
}

Okay, all good. The $value is just an array. Try this instead:

foreach($result as $index => $value){
    echo "<p>\$index: " . $index . "; \$value: "; print_r($value);  echo "</p>";
    var_export($value);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi - this outputs the below php $index: 0; $value: Array array ( 'salesman' => 'Bob Jones', 'NumberOfSales' => '1', 'MonthSales' => '0.000000', 'LastMOnth' => '0.000000', 'TwoMonths' => '0.000000', ) ?> so it seems the var_export works but the echo does not
@HotTomales I've updated my answer. Check if that works.
YES! That is exactly what I was after. Thank you so much!
No problem. Happy to help :-)

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.