mysql prepared statements, trouble understanding how it works
i am trying to use prepared statements but having trouble getting it to successfully run. here is my code:
function addAlbum($album){
$connection = mysqli_connect(HOST,USER,PASS,DATABASE);
/*$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$result = mysqli_query($connection,$sql);*/
$stmt = $dbh->prepare('INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")');
$stmt->bindParam(':albumName', $albu开发者_StackOverflowm);
$result = $stmt->execute();
if($result){
header("Location: index.php?success");
} else {
header("Location: index.php?fail");
}
}
i have ran this in firefox with errors on and this is what i get:
Fatal error: Call to undefined method mysqli_stmt::bindParam() in /Applications/MAMP/htdocs/PHPproject/includes/functions.inc.php on line 16
could any one please tell me where i am going wrong?
many thanks
First argument for bind should be the type of variable:
$stmt->bind_param("s", $album);
Also you should check the return value of execute()
and not the $stmt
:
$result = $stmt->execute();
if($result){
echo "yes";
}
else {
echo "no";
}
Also I'd say that it's not a good ideea to prepare the statement each time you insert something. Prepared statements should be class variables or if you're not in oop, global variables, so you don't prepare the statement each time you call the function. Just write a function init()
that will prepare all the statements that you'll use.
精彩评论