Sunday, August 22, 2010

Start Up PHP/MySQL Code and Table Record Count

Here is the basic PHP/MySQL code for initiating a db connection, accessing a table and returning a record count:

<?php

// Connect to the database server
$con = mysql_connect("localhost","root*","pswd");
if (!$con) { die('Could not connect to the db server: ' . mysql_error()); }
// Select the database
if (!@mysql_select_db('databasename')) { die('Could not find the db: ' . mysql_error()); }
// Obtain number of records
$countit = mysql_query("SELECT COUNT(*) FROM table1");
if (!$countit) { die('Could not perform query: ' . mysql_error()); }
while($c1 = mysql_fetch_array($countit))
{ $count= $c1['COUNT(*)']; }
echo "Record count = " . $count;
mysql_close($con);
?>

-SandyZ