objSQL Helper Method: Select
The obj_select() helper method executes a select statement with minimal SQL markup and is called from the objSQL class.
- The $table name argument is required. Supplying only this argument will return all rows from the named table.
- The optional $cols argument specifies which columns to return and is entered as a comma delimited string. Entering an empty value is equivilent to an asterisk (*).
- The optional $where argument allows you to filter your query and only requires the column and its value. You can use any of the normal operators used in SQL statements:
- "location IN ('Athens','London')"
- "location='Valdosta' AND dept='IT'"
- "location LIKE 's%'"
- "salary BETWEEN 20000 AND 40000"
- The optional $order_by argument is used to sort the resultset and only requires the column name.
- The optional $sort_order argument is used to sort the $order_by argument in descending (desc) or ascending (asc) order.
Returns: Result resource/object or false on failure.
<?php
//usage: $dbh->obj_select( $table, $cols, $where, $order_by, $sort_order )
try
{
//Return all rows from table
$rs = $dbh->obj_select( "mytable" );
if ( $dbh->obj_error() )
throw new Exception( $dbh->obj_error_message() );
echo $rs->obj_num_rows();
$rs->obj_free_result();
}
catch ( Exception $e )
{
//log error and/or redirect user to error page
}
try
{
//Return selected cols from table with filter
$rs = $dbh->obj_select( "mytable","color,size,price","product='balloons'","price" );
if ( $dbh->obj_error() )
throw new Exception( $dbh->obj_error_message() );
while ( $obj = $rs->obj_fetch_object() )
{
printf ( "%s %s %s \n", $obj->color,
$obj->size,
$obj->price );
}
$rs->obj_free_result();
}
catch ( Exception $e )
{
//log error and/or redirect user to error page
}
?>