Main Content

Using print_r in PHP to explore mysql database requests

Archive - Originally posted on "The Horse's Mouth" - 2009-10-01 21:16:40 - Graham Ellis

The print_r function in PHP lets you "print raw" the contents of a variable - great for debugging and far better that print which - if you pass it an array helpfully says Array

Embed your print_r into <pre> to </pre> tags ... so that you get a good display on your browser ... otherwise you'll end up with the spaces removed and a mess. Here's an example - showing the global $_SERVER array, and also the contents of a table that's been brought back to an array of arrays:

<pre><?php
# Show server variables
print_r($_SERVER);
print ("----------------------------\n");
mysql_connect("127.0.0.1","wellho","xxxxxx");
mysql_select_db("wellho");
$rr = mysql_query("select * from recent limit 15");
print_r($rr);
print ("----------------------------\n");
$stuff = array();
while ($nextrow = mysql_fetch_assoc($rr)) {
  array_push($stuff,$nextrow); }
print_r ($stuff);
?></pre>


Select here to see what you get when you run that code. Note how the mysql_query call just returns a resource handle, and you then have to use something like mysql_fetch_assoc to get the actual data back.