objSQL Helper Method: Insert
The obj_insert() helper method executes an insert statement which requires no SQL markup and is called from the objSQL class.
- The table name argument is required.
- The $data argument is required and MUST be a key value pair array with the table column as the key.
Returns: Result resource/object or false on failure.
See also: Inserting multiple rows
<?php
//usage: $dbh->obj_insert( $table, $data )
try
{
$data = array( "product" => "balloon",
"color" => "red",
"size" => "small",
"price" => 2.50 );
$rs = $dbh->obj_insert( "mytable", $data );
if ( $dbh->obj_error() )
throw new Exception( $dbh->obj_error_message() );
echo $rs->obj_affected_rows();
}
catch ( Exception $e )
{
//log error and/or redirect user to error page
}
?>
Inserting Multiple Rows
The obj_insert() helper method additionally allows you to easily insert multiple rows.
- The $data value argument can be a comma delimited string or an array.
- The latest version of PHP uses SQLite3 3.7.7.1 which doesn't support inserting multiple rows in a single statement.
<?php
//usage: $dbh->obj_insert( $table, array( "column" => "val1,val2,val3,val4" )
try
{
$data = array( "product" => "balloon,balloon,balloon,balloon",
"color" => "red,green,blue,pink",
"size" => "small,small,small,small",
"price" => 2.50,2.50,2.50,2.50 );
$rs = $dbh->obj_insert( "mytable", $data );
if ( $dbh->obj_error() )
throw new Exception( $dbh->obj_error_message() );
echo $rs->obj_affected_rows();
}
catch ( Exception $e )
{
//log error and/or redirect user to error page
}
//usage: $dbh->obj_insert( $table, array( "column" => array("val1","val2","val3","val4") )
try
{
$data = array( "product" => array( "balloon","balloon","balloon","balloon" ),
"color" => array( "red","green","blue","pink" ),
"size" => array( "small","small","small","small" ),
"price" => array( 2.50,2.50,2.50,2.50 ) );
$rs = $dbh->obj_insert( "mytable", $data );
if ( $dbh->obj_error() )
throw new Exception( $dbh->obj_error_message() );
echo $rs->obj_affected_rows();
}
catch ( Exception $e )
{
//log error and/or redirect user to error page
}
?>