<?php
if ( !$rResource = mysql_query( $sQuery ) )
{
// Query have failed
echo '<u>The page data could not be displayed !</u><br><br>';
}
else
{
// Query succied
if ( mysql_num_rows( $rResource ) == 0 )
{
// there are no results
echo 'There are no results available';
}
else
{
// there its results, reflect that trade
while ( $aResult = mysql_fetch_assoc( $rResource ) )
{
echo $aResult['content'];
}
}
}
}
?>
Refactorings
No refactoring yet !
John
October 9, 2007, October 09, 2007 16:33, permalink
You could just put the whole thing into a class and handle errors with exceptions, but this is PHP5 and I don't know what your intentions are. If you only want to display some results you could better keep the code your way, if you're planning to expand your code, you can better put into a class like this one.
Have fun~!
<?php
class dbQuery
{
public output;
// constructor
public function __construct($row = 'content') {
$sqlQuery = "SELECT * FROM table WHERE condition = '1'";
$sqlResult = mysql_query($sqlQuery);
// error : query failed
if($sqlResult === false)
{
throw new Exception("Your SQL query failed: ".$sqlQuery." <br /> MySQL says: ".mysql_error());
}
// check available number of results
$sqlNumRows = mysql_num_rows($sqlResult);
// error : no results
if($sqlNumRows == 0)
{
throw new Exception("We have got no results to return, I'm sorry");
}
// while loop
while($aData = mysql_fetch_assoc($sqlResult)
{
$this->output . = $aData[$row].'<br />';
}
return $this->output;
}
?>
Now, when you implement this class into another file, do it like this:
<?php
require 'queryclass.php';
try {
$query = new dbQuery();
// leave empty to leave it at 'content' (the default)
// or $query = new dbQuery('otherrow');
}
catch(exception $e) {
echo $e->getMessage();
exit();
}
?>
John
October 9, 2007, October 09, 2007 16:35, permalink
You need to echo the output, I forgot to do this.
<?php
require 'queryclass.php';
try {
$query = new dbQuery();
echo $query->output;
// leave empty to leave it at 'content' (the default)
// or $query = new dbQuery('otherrow');
}
catch(exception $e) {
echo $e->getMessage();
exit();
}
?>
zaadjis
October 10, 2007, October 10, 2007 14:33, permalink
<?php
/**
* @link http://php.net/PDO
*/
//$db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
if ($rows = $db->query($sQuery)->fetchAll()) {
foreach ($rows as $row) {
echo $row['content'];
}
} else {
echo 'none';
}
} catch (PDOException $e) {
echo $e->getMessage();
}
This is my code for picking up text out of the DB. Are there any refactoring? :-)
Please let me know THNX!!