Oct
17
2006

How to: Setting up MySQL recordset as array to be parsed by Smarty

Here is an example of how to setup your MySQL queries so that they can easily be passed into and parsed by Smarty.

The result set will be a multidimensional array. The first dimension of the array is numeric and represents each row of your result set. The second dimension of the array is an associative array where the names of the indexes are the field names you specified in your query.

Code:
//Init the array to hold the results
$results = Array();

//Try to connect to the DB
$mysql = mysql_connect($host, $user, $password) or die(’Could not connect: ‘.mysql_error());

//Setup the SQL statement
$sql = ‘SELECT SQL_CALC_FOUND_ROWS name, address, city, state, zip FROM users’;

//Run the query
$result = mysql_query($sql, $mysql);

//Get the results as an associative array and put each row into the numerically indexed array
while ($row = mysql_fetch_assoc($myresult))
$results[] = $row;

//Now we get set up the query to get the number of results that were returned
$sql = ‘SELECT FOUND_ROWS() as foundrows’;

//Run the query
$result = mysql_query($sql, $mysql);

//Store the resulting row
$row = mysql_fetch_assoc($result);

//Get the total rows
$total = $row['foundrows'];

//Assign the results to smarty
$smarty->assign(’results’, $results);
$smarty->assign(’total’, $total);

//Display the Smarty template
$smarty->display(’index.tpl’);

Your resultset should look something like this:

Code:
Array (2)
0 => Array (5)
name => John Doe
address => 123 Anonymous Way
city => Springfield
state => IL
zip => 62707
1 => Array (5)
name => Jane Doe
address => 777 Luxury Way
city => Beverly Hills
state => CA
zip => 90210

And here is an example using {section} to parse the results

Code:
Displaying {$total} records :<br />
{section name=nr loop=$results}
{$results[nr].name}
{$results[nr].address}
{$results[nr].city}
{$results[nr].state}
{$results[nr].zip}<br />
{sectionelse}
<h1>No results found!</h1>
{/section}

tags: , ,
posted in Guides, Programming by Owen

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
© 2008 - 2012 — All Rights Reserved — Ideamesh, Inc. 22 queries. 0.226 seconds.