Sunday, October 4, 2009

MySQL and PDO

This will display all of the links and descriptions

//change these
$user = 'root';
$pass = '';
try
{
//localhost, test database
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
//table is called test
foreach($dbh->query('SELECT * from test') as $row)
{
print "{$row['name']} : {$row['desc']}
";
}
$dbh = null;
}
catch (PDOException $e)
{ print "Error!: " . $e->getMessage() . "
";
die();
}
?>

Thursday, October 1, 2009

Count the number of rows in a MySQL database

Often there may be a requirement to count the number of entries in a MySQL table.


//connect to server with username and password
$connection = mysql_connect ("localhost","username", "password") or die ("Cannot make the connection");
//connect to database
$db = mysql_select_db ("test",$connection) or die ("Cannot connect to database");
//our SQL query
$sql_query = "SELECT * FROM test";
//store the SQL query in the result variable
$result = mysql_query($sql_query);
$rows = mysql_num_rows($result);
//output total
echo $rows;
?>