Problem with PHP INSERT in to MySQL database - php

I am hoping that I've just been looking at and debugging this code too long (days now!) and I'm just not seeing the problem.
I'm obviously trying to add an entry in to a MySQL database via my PHP code. To use the classic phrase "this code has always worked before and now it doesn't and I didn't change anything" ;-)
My code, with my current debugging traps, looks like this:
// Prepare SQL Insert
$strInsert = "INSERT INTO Horses ( HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM) " .
"VALUES (:HORSENAME, :HORSEYOB ,:HORSECOB, :HORSESEX, :HORSEYOD, :HORSEDEAD, :FAM, :FDM)";
$DBInsertHorse = $DB->prepare($strInsert);
// Insert new Horse
$iCtr = 0;
do {
try {
$DBInsertHorse->execute(array(
'HORSENAME' => strtoupper($HorseName),
'HORSEYOB' => $YOB,
'HORSECOB' => $COB,
'HORSESEX' => strtoupper($HorseSex),
'HORSEYOD' => $YOD,
'HORSEDEAD' => $bDead,
'FAM' => $FAM,
'FDM' => $FDM)
);
}
catch (Exception $error) {
die($error->getMessage());
}
} while ($find($DB, strtoupper($HorseName), $YOB, $COB) == false && ++$iCtr < MAX_INSERT_ATTEMPTS);
// Could not insert
if ($iCtr == MAX_INSERT_ATTEMPTS) {
// DEBUG HORSE IMPORT
if (is_null($HorseName))
$HorseName = 'NULL';
if (is_null($YOB))
$YOB = -2;
if (is_null($COB))
$COB = 'NULL';
if (is_null($HorseSex))
$HorseSex = 'NULL';
if (is_null($YOD))
$YOD = -2;
if (is_null($bDead) || !$bDead)
$Dead = -2;
if (is_null($FAM))
$FAM = 'NULL';
if (is_null($FDM))
$FDM = 'NULL';
error_log('INSERT ERROR: Horse: \'' . strtoupper($HorseName) . '\' - YOB: ' . $YOB . ' - COB: \'' . $COB . '\' - SEX: \'' . strtoupper($HorseSex) . '\' - YOD: ' . $YOD . ' - Dead: ' . $bDead . ' - FAM: ' . $FAM . ' - FDM: ' . $FDM);
return(false);
}
If I go my favourite SQL editor (SQLPro for MySQL) and I enter in the insert manually it works fine:
INSERT INTO Horses (HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM)
VALUES ('HorseName', 2001, null, 'M', null, false, null, null)
For info:
The find() function used is my own and wraps a "SELECT FROM ..." query and works fine. If I do a SELECT from the Horses table in the database afterwards the Horse was never added.
MAX_INSERT_ATTEMPTS is my constant and the value is currently set at 5.
I'm working with MaMP PRO and I've looked in my PHP error log, where only the message I sent there appears and no other errors and in my MySQL error log, where no error message appears.
I can't figure out where to look next and I'm hoping whatever my stupid error might be is going to jump out at someone else looking at my code.
Thanks for looking and for any ideas, suggestions or corrections you may have.
UPDATED CODE WITH DEBUGGING
do {
try {
$DBInsertHorse->bindValue(':HORSENAME', strtoupper($this->Name));
$DBInsertHorse->bindValue(':HORSEYOB', $this->YOB);
$DBInsertHorse->bindValue(':HORSECOB', $this->COB);
$DBInsertHorse->bindValue(':HORSESEX', strtoupper($this->Sex));
$DBInsertHorse->bindValue(':HORSEYOD', $this->YOD);
$DBInsertHorse->bindValue(':HORSEDEAD', (int)$this->Dead);
$DBInsertHorse->bindValue(':FAM', $this->FAM);
$DBInsertHorse->bindValue(':FDM', $this->FDM);
$DBInsertHorse->execute();
}
catch (PDOException $e) {
error_log('SQL INSERT ERROR: ' . $e->getMessage());
}
} while($this->find($DB, strtoupper($this->Name), $this->YOB, $this->COB) == false && ++$iCtr < MAX_INSERT_ATTEMPTS);

As #BillKarwin mentioned I was missing a proper call to
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Once that was in place I was able to see where the error was. This error apparently has appeared since my upgrade to PHP 7.2.10.
I also changed my call to array to a list of calls to bindValue... I may go back to array() but that's not important. ;-)
The PHP code did not like my passing "false" to a tinyint field. I had to type the variable with a call to (int)varname and everything works fine now.
(int)$this->Dead;
THANK YOU ALL!

Check this, it's tested and it works. Also check do while statement.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO Horses ( HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM)
VALUES (:HORSENAME, :HORSEYOB ,:HORSECOB, :HORSESEX, :HORSEYOD, :HORSEDEAD, :FAM, :FDM)");
$stmt->bindParam(':HORSENAME',$HorseName);
$stmt->bindParam(':HORSEYOB', $YOB);
$stmt->bindParam(':HORSECOB', $COB);
$stmt->bindParam(':HORSESEX', $HorseSex);
$stmt->bindParam(':HORSEYOD', $YOD);
$stmt->bindParam(':HORSEDEAD', $bDead);
$stmt->bindParam(':FAM', $FAM);
$stmt->bindParam(':FDM', $FDM);
// insert a row
$HorseName = strtoupper($HorseName);
$YOB = "John";
$COB = "John";
$HorseSex = strtoupper($HorseSex);
$YOD = "John";
$bDead = "John";
$FAM = "John";
$FDM = "John";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;

Related

Inserting form data to a mysql database

I have tried multiple times to get this code to run and insert the data into a my database. No matter what I try I cannot figure out the problem. The php looks like this:
<?php
// Create connection
$conn = mysqli_connect("localhost","nmhsmusi_admin" , "********", "nmhsmusi_musicdb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['submit']))
{
$titleTag = $_POST['title'];
$composerTag = $_POST['composer'];
$unicodeTag = $_POST['unicode'];
$tempoTag = $_POST['tempo'];
$yearTag = $_POST['year-used'];
$languageTag = $_POST['language'];
$keyTag = $_POST['key-signature'];
$pianoTag = $_POST['piano'];
$temposelTag = $_POST['temposel'];
$partsTag = $_POST['parts'];
$run = mysqli_query($conn,"INSERT INTO musicdb (title, composer, unicode, temptxt, yearused, languages, pianokeys, piano, temposel, parts)
VALUES
(
'$titleTag', '$composerTag', '$unicodeTag', '$tempoTag', '$yearTag', '$languageTag', '$keyTag', '$pianoTag', '$temposelTag', '$partsTag'
)");
if ($run) {
echo "New record created successfully";
} else {
echo "failed";
}
mysqli_close($conn);
}
?>
Any help would be greatly appreciated
Why do you use mysqli? Has it already fallen into disuse?
PDO is now used.
Here's an example:
<?php
if (isset($_POST['submit'])) {
$titleTag = $_POST['title'];
$composerTag = $_POST['composer'];
$unicodeTag = $_POST['unicode'];
$tempoTag = $_POST['tempo'];
$yearTag = $_POST['year-used'];
$languageTag = $_POST['language'];
$keyTag = $_POST['key-signature'];
$pianoTag = $_POST['piano'];
$temposelTag = $_POST['temposel'];
$partsTag = $_POST['parts'];
try {
$pdo = new PDO(DSN,DBUSER,DBUSERPASSWD);
} catch (PDOException $e) {
echo "Failed to connect to Database: " . $e->getMessage() . "\n"; die();
}
$pdo->exec("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
$sql = "INSERT INTO musicdb (title, composer, unicode, temptxt, yearused, languages, pianokeys, piano, temposel, parts)
VALUES (:titleTag,:composerTag,:unicodeTag,:tempoTag,:yearTag,:languageTag,:keyTag,:pianoTag,:temposelTag,:partsTag)";
$query = $pdo->prepare("$sql");
$query->bindValue(':titleTag',$titleTag);
$query->bindValue(':composerTag',$composerTag);
$query->bindValue(':unicodeTag',$unicodeTag);
$query->bindValue(':tempoTag',$tempoTag);
$query->bindValue(':yearTag',$yearTag);
$query->bindValue(':languageTag',$languageTag);
$query->bindValue(':keyTag',$keyTag);
$query->bindValue(':pianoTag',$pianoTag);
$query->bindValue(':temposelTag',$temposelTag);
$query->bindValue(':partsTag',$partsTag);
$query->execute();
if($query->rowCount() > 0){
echo "New record created successfully!";
} else {
echo "Error!";
}
}
?>
Of course you need to filter everything that comes from the form with regular expressions. Easy thing to do!
Once the regular expressions have analyzed everything you need to convert everything to htmlentities to avoid malicious code:
The regular expression "/([a-zÀ-ÿ0-9\s]+)/i" below allows only letters with or without accents, numbers, and spaces:
<?php
preg_match('/([a-zÀ-ÿ0-9\s]+)/i', $_POST['any_field_form'], $output);
if((isset($output[1]) == true) and ($output[1] != null)) {
//Convert everything to htmlentities to avoid malicious code
$get_the_data = htmlentities($output[1], ENT_QUOTES, 'UTF-8', false);
} else {
$get_the_data = null;
}
?>
With this you avoid problems with forms. Of course for each form field you will have to do a specific regular expression. But that makes your code smarter.
Sorry if there are any errors in the text. I know how to read in English, but I do not know how to write so I used a translator for that.
But that's it, boy!

Can I improve my PDO method (just started)

I just switched to PDO from mySQLi (from mySQL) and it's so far good and easy, especially regarding prepared statements
This is what I have for a select with prepared statement
Main DB file (included in all pages):
class DBi {
public static $conn;
// this I need to make the connection "global"
}
try {
DBi::$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuname, $dbpass);
DBi::$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
DBi::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo '<p class="error">Database error!</p>';
}
And in my page:
try {
$sql = 'SELECT pagetitle, pagecontent FROM mypages WHERE pageid = ? LIMIT 1';
$STH = DBi::$conn->prepare($sql);
$STH->execute(array($thispageid)); // $thispageid is from a GET var
}
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
if ($STH) { // does this really need an if clause for it self?
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
echo '<h1>'.$row['pagetitle'].'</h1>
<p>'.$row['pagecontent'].'</p>';
}
}
It all works. But am I doing it right? Or can I make it more simple some places?
Is using if (!empty($row)) {} an ok solution to check if there was a result row with content? Can't find other decent way to check for numrows on a prepared narrowed select
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
I would use the opportunity to log which database query error occurred.
See example here: http://php.net/manual/en/pdostatement.errorinfo.php
Also if you catch an error, you should probably return from the function or the script.
if ($STH) { // does this really need an if clause for it self?
If $STH isn't valid, then it should have generated an exception and been caught previously. And if you had returned from the function in that catch block, then you wouldn't get to this point in the code, so there's no need to test $STH for being non-null again. Just start fetching from it.
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
I would write it this way:
$found_one = false;
while ($row = $STH->fetch()) {
$found_one = true;
. . . do other stuff with data . . .
}
if (!$found_one) {
echo "Sorry! Nothing found. Here's some default info:";
. . . output default info here . . .
}
No need to test if it's empty, because if it were, the loop would exit.

Update query not working using PDO

I tried updating my data like so but it doesn't work
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(!empty($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$query_params = array(':shell' => $_POST['shell'], ':reporter' => $_POST['reporter']);//Updates likes
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
the config.inc.php
<?php
// These variables define the connection information for your MySQL database
$username = "xmnj3jh0jhtheu_14265914";
$password = "jhikjskjiavethew";
$host = "sqlkjnlkkjlk101.x3kuhiu0lkj.us";
$dbname = "x3lnklj0u_1426jbkb5914_gbabbjkhjajhlert";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like � or �, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
don't know what's wrong and it gives no error it goes into the else statement, meaning the values were not updated. i tried the same code in sqlfiddle and it works but not in my PhpMyAdmin.
I know the updated value is supposed to be passed into the $query_params but am incrementing the value of likes each time it is run, and am not sure how to do that in the $query_params unless i use a seperate query to get the numberof likes and then increament it but that could be costly.
Query without PDO still it does not work this time it give update unsuccessful
<?php
$username = "x3jbhiukhkj0u426jbhjnbvh591mbhb4";
$password = "savjiuejbiuhilkmthljiew";
$host = "sqlnjhbjhnkjjjhbj";
$dbname = "x3hjbh0ukjioiuhgbjhvhgvh";
$shell = "Rustig";
$reporter = "davies";
//query
$query = "UPDATE `shellingdb`
SET `favs` = 1
WHERE `shell` = 'Rustig'";
$link = mysql_connect($host, $username, $password);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}else
{
echo 'Connected successfully';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected)
{
die ('Can\'t use foo : ' . mysql_error());
}else
{
echo 'Connected to database successfully';
if(empty($_POST))
{
$retval = mysql_query( $query, $link )or die(mysql_error($link));;
if(! $retval )
{
die('Could not query database: ' . mysql_error());
}else
{
if(mysql_affected_rows() > 0)
{
echo "Updated data successfully\n";
}else
{
//echo "shell=".$shell." reporter=".$reporter';
echo "Updated data Unsuccessfully\n";
}
}
}
}
}
mysql_close($link);
?>
The below is the output of the PDOStatement::debugDumpParams(); for the first php syntax
SQL: [124] UPDATE shellingdb SET likes = likes + 1 WHERE shell = :shell AND reporter >= :reporter Params: 2 Key: Name: [6] :shell paramno=-1 name=[6] ":shell" is_param=1 param_type=2 Key: Name: [9] :reporter paramno=-1 name=[9] ":reporter" is_param=1 param_type=2
I used bindParam. bindParam is a method on PDOStatement.
Try:
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(isset($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$stmt = $db->prepare($query);
$stmt->bindParam(":shell", $shell);
$stmt->bindParam(":reporter", $reporter);
$stmt->execute();
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
some how, after long hours of try and error(Brut Forcing) this finally worked
$query = "UPDATE `shellingdb` SET `likes`=`likes`+1 WHERE `shell` = :shell AND `reporter` = :reporter";
Thanks all those who tried to help. :)

updating data in mysql database using arrays

I would like to update information that is already in the database, but using an array. I get 'successfully update' message white the data in the database is not updated.
the following is the function I use to do the insertion:
function update_knowledge_modules($update_data,$value)
{
$update = array();
array_walk($update_data,'array_clean');
foreach($update_data as $field=>$data)
{
$update[] = '.$field. = \''.$data.'\'';
}
$query = "UPDATE knowledge_modules SET".implode(', ',$update)."WHERE curr_code =$value";
mysql_query($query)
or die(mysql_error);
}
<?php
if(isset($_GET['success']) == true && empty($_GET['success'])==true)
{
echo 'Changed successfully';
}
else
{
if(empty($_POST)== false && empty($errors)== true )
{
$update_module = array(
'KM_Number'=>$_POST['KM_Number'],
'KM_Title'=>$_POST['KM_Title'],
'NQF_Level'=>$_POST['NQF_Level'],
'Credits'=>$_POST['Credits']
);
update_knowledge_modules($update_module,$_SESSION['Curr_Code']);
header('Location:edit_km_details.php?success');
exit();
}
else if(empty($errors)== false)
{
echo output($errors);
}
?>
<form action="edit_km_details.php" method="POST">
Well, first of all, you are outputting the "changed successfully" message solely based on $_GET['success'] being truthy. It has nothing to do with whether you had success or failure in your update_knowledge_modules function call at all, which seems odd.
Second of all, I don't see anywhere where you are actually making a database connection.
Third, your query is undoubtedly being formed improperly. Look at this:
$update[] = '.$field. = \''.$data.'\'';
you are going to get a literal $field and backslashes in your query string. Try this:
$update[] = $field . " = '" . $data . "'";
Also where you put your imploded array in the final query, you don't have spaces after SET and before WHERE.
Anytime you are having problems with a query, just var_dump it and run it on the database directly to see why it isn't working and look at your errors, including mysql errors.
Finally, you should not be using the mysql_* family of functions. They are deprecated.
Try: $update[] = $field . " = '" . $data . "'";
Output:
Array
(
[0] => KM_Number = 'blah'
)

Cannot pass parameter when attempting prepared statement

I'm attempting to learn prepared statements right now in PHP/MYSQL because of many suggestions around here. I keep getting this error:
Fatal error: Cannot pass parameter 2 by reference in C:\xampp\htdocs\blog\admin\create.php on line 57
Can anyone tell me how to fix this problem? I've been searching around and I can't find anything that will help me solve this.
Here is my code:
<?php
require_once '../config.php';
// Check to see if the title was entered from new.php
if ($_POST['title'])
{
$title = $_POST['title'];
} else {
echo "No title was entered. Please go back. <br />";
}
// Check to see if the body was entered from new.php
if ($_POST['body'])
{
$body = $_POST['body'];
} else {
echo "No body was entered. Please go back. <br />";
}
// Get the date
$date = time();
// ID = NULL because of auto-increment
$id = 'NULL';
// If magic_quotes_gpc returns true then it's enabled on the serever and all variables will be
// automatically escaped with slashes. If it isn't true then it's done manually
if (!get_magic_quotes_gpc())
{
$title = addslashes($title);
$body = addslashes($body);
$date = addslashes($date);
}
// Connect to the database
$db = new mysqli('localhost','username','password','database');
// Check to see if the connection works
if ($db->connect_errno)
{
echo 'Error: Could not connect to database. Please try again.';
exit;
}
// Prepared statement for a query to place something in the database
if(!($stmt = $db->prepare("insert into pages (id, title, body, date) values (?,?,?,?)")))
{
echo "Prepare failed: (" .$db->errno . ")" . $db->error;
}
// THIS IS THE LINE WHERE I'M RECEIVING THE ERROR!!!!!!!!
if (!$stmt->bind_param('isss', ''.$id.'', ''.$title.'',''.$body.'',''.$date.''))
{
echo "Binding parameters failed: (" .$stmt->errno. ")" . $stmt->error;
}
if (!$stmt->execute())
{
echo "Execute failed: (" .$stmt->errno . ") " .$stmt->error;
}
$db->close;
?>
You should have a look at the corresponding mysqli_stmt::bind_param documentation. More precisely, have a look at the function's definition:
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
Notice the mixed &$var1 part? This basically states that your paramters are passed by reference and not by value (which would look like mixed $var1 - the & makes the difference).
Now, the problem with your invocation is that you are trying to pass an expression rather than a variable by reference. From the PHP documentation:
The following things can be passed by reference:
- Variables, i.e. foo($a)
- New statements, i.e. foo(new foobar())
- References returned from functions, [...]
The simple remedy is to first call the binding with uninitialized variables which are then assigned your processed input data, i.e.
// Prepared statement for a query to place something in the database
$stmt = $db->prepare("insert into pages (id, title, body, date) values (?,?,?,?)");
if ( !$stmt ) {
echo "Prepare failed: (" .$db->errno . ")" . $db->error;
}
if ( !$stmt->bind_param('isss', $stmt_id, $stmt_title, $stmt_body, $stmt_date) ) {
echo "Binding parameters failed: (" .$stmt->errno. ")" . $stmt->error;
}
$stmt_id = (int) $id;
$stmt_title = (string) $title;
$stmt_body = (string) $body;
$stmt_date = (string) $date;
if ( !$stmt->execute() ) {
echo "Execute failed: (" .$stmt->errno . ") " .$stmt->error;
}

Categories