Home › Forums › Back End › function in php › Re: function in php
okay, let’s try this:
first, don’t use the `mysql_*()` functions. [They are deprecated and not recommended for new code](http://php.net/mysqlinfo.api.choosing).
I prefer the [mysql**i** extension](http://php.net/mysqli) – it is object-oriented, but also has a procedural api that is very similar to the mysql_*() functions if that’s what you prefer.
function insertArticle( $DB,$title,$content ){
// check the database handle
if( !($DB instanceof mysqli) ){
// $DB is not a database connection!
// abort
return false;
}
// this will hold your SQL statement:
static $query;
// “static” means it will be “remembered” between calls,
// so it only needs to be set up once.
if( !($query instanceof mysqli_stmt) ){
// not set up yet.
// here’s your statement:
$SQL = “INSERT INTO `article`
( `title`,`content` )
VALUES( ?,? )”;
// assign the prepared statement to $query
$query = $DB->prepare( $SQL );
// bind $title and $content to the ? markers in the query
$query->bind_param( ‘ss’,$title,$content );
// ready to go.
}
// execute the query,
// using current values in $title and $content.
$query->execute();
// check if query was successful or not
if( $query->affected_rows === 1 ){
// perfect!
return true;
}
// no good.
return false;
}
This assumes your `id` column is an AUTO_INCREMENT key. You’ll get an SQL error if not; let me know if that is the case.
Here’s how you might use your function:
// set up mysqli DB connection
$DB = new mysqli( ‘DBhost’,’username’,’password’,’DatabaseName’ );
// check connection
if( mysqli_connect_error() ){
print “couldn’t connect to the database.”;
}
// later, get the info you want to insert
$title = $_POST;
$content = $_POST;
// you’ll probably want to make sure the info is valid.
// but you don’t need to worry about sanitization:
// the prepared statement will take care of that.
// now, call the function:
$result = insertArticle( $DB,$title,$content );
// and check if it was successful or not:
print $result?
“data inserted successfully!”:
“data insertion failed.”;
That’s it.