Php strict standards: Only variables should be passed by reference [duplicate] - php

This question already has answers here:
Error message "Strict standards: Only variables should be passed by reference"
(6 answers)
Closed 6 years ago.
So my code look like this:
$sql = "INSERT INTO users (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', sha1($_POST['password']));
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
Where the error is caused by this line:
$stmt->bindParam(':password', sha1($_POST['password']));
Hope someone can help me remove the 'Strict standards: Only variables should be passed by reference' error. Since its still executing everything.

bindParam takes a reference to the second argument instead of the value. This is done so changes to the variable value before executing the statement are recognized or, to rephrase it, so the value of the bound variable at execution time of the query is used, not the value the variable had when binding it.
References only work on variables - you cannot pass a reference to a function call. If you use a function call as second aprameter of bindParam, the value is passed instead of a reference, which is why everything keeps working - but it defeats the purpose of using a reference in the first place.
To fix the error message:
$passSha1 = sha1($_POST['password'])
$stmt->bindParam(':password', $passSha1);
// if you change passSha1 here, the new value will be used later
// in the execution of the statement
if( $stmt->execute() ):
// ...

Have you tried extracting a variable? Something like this:
$passwordHash = sha1($_POST['password']);
$stmt->bindParam(':password', $passwordHash);

Related

Cannot pass parameter 2 by reference - PDO [duplicate]

This question already has answers here:
Cannot pass parameter 2 by reference error in php PDO
(2 answers)
Closed 6 years ago.
I am experiencing this error:
"Cannot pass parameter 2 by reference"
I looked up several threads, not a single solution actually worked for me, it might be a really stupid mistake/type..?
$stmt = $dbh->prepare("INSERT INTO messages (message, sender, key) VALUES (:message, :sender, :key)");
$stmt -> bindParam(':message', $message);
$stmt -> bindParam(':sender', 'Smith');
$stmt -> bindParam(':key', 'Test-Key');
$stmt -> execute();
This is my code.. The error is pointing at line 32, which is the "sender" line... I personally think it's the message line instead.
Thank you for your help! :)
The bindParam() method binds the parameter to a variable. Strings are what are called constants.
In order to make this work you have to pass a variable to the method, like this:
// Prepare the statement
$stmt = $dbh->prepare("INSERT INTO messages (message, sender, key) VALUES (:message, :sender, :key)");
// Bind variables to the parameters
$stmt->bindParam(':message', $message);
$stmt->bindParam(':sender', $sender);
$stmt->bindParam(':key', $key);
// Give the bound variables a value
$message = 'The message...';
$sender = 'Smith';
$key = 'Test-Key';
// And then execute the statement
$stmt->execute();

PHP Fatal error: Call to a member function bind_param() [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 months ago.
I've been stuck on this error , please help me this is my code
PHP Fatal error: Call to a member function bind_param()
$statement= $db->prepare("insert into uploaddetails(idnum,title,desc,author,tags,title) values(?,?,?,?,?,?)");
$id='NULL';
$title=$_POST['title'];
$description=$_POST['description'];
$author=$_POST['author'];
$tags=$_POST['tags'];
$file= basename($_FILES["fileToUpload"]["name"]);
$statement->bind_param( 'isssss', $id,$title, $description,$author,$tags,$file);
$statement->execute();
$db->close();
$statement->close();
Since nobody else has spotted the issue, I'll post it for you. The reason you're prepare() is failing is because you're trying to use a MySQL Reserved Word. The word desc is a reserved word in MYSQL, which means you need to wrap it in backticks like this:
$statement= $db->prepare("insert into uploaddetails(idnum,title,`desc`,author,tags,file) values(?,?,?,?,?,?)");
It also helps to use proper practice when inserting into a database/using prepared statements.
$statement= $db->prepare("insert into uploaddetails(idnum,title,`desc`,author,tags,title) values(?,?,?,?,?,?)");
if($statement !== FALSE) {
// do the binds...etc
}
Notes
file is also a reserved word, I don't know what your actual file columns name is, so keep that in mind.
Your prepare statement is failing because of the query, what you need to do is to make sure the statement is not false in order to execute bind_param, otherwise view the prepare query error as follows :
//Make sure the statement is not false
if($statement !== FALSE)
{
$statement->bind_param( 'isssss', $id,$title, $description,$author,$tags,$file);
$statement->execute();
$db->close();
$statement->close();
}
//Otherwise check why the prepare statement failed
else
{
die('prepare() failed: ' . htmlspecialchars($db->error));
}
Try this. your code is modified.
$statement= $db->prepare("INSERT INTO uploaddetails (title,desc,author,tags,file) VALUES(?,?,?,?,?)");
//$id='NULL';
$title=$_POST['title'];
$description=$_POST['description'];
$author=$_POST['author'];
$tags=$_POST['tags'];
$file= $_FILES["fileToUpload"]["name"];
$statement->bind_param( 'isssss',$title, $description,$author,$tags,$file);
$statement->execute();
$db->close();
$statement->close();
//---- Move the file to desired location...
-ID is not required because it is auto increment and mysql will take care of it,
-and you had wrong field name for file, which was title and I change it to file(correct it if you have any other name instead).
possible errors
1)column count in the table is different from your query.
2)although it shows the error in the bind_param line, the error may occur in the prepare statement line(in your case line 1)
3)you can put echo statement before and after these lines and caught the error
(in my case I repeated the same field name twice in the prepared statement)
fetch following code with your requirements and tryout
$stmt = $conn->prepare("INSERT INTO SalesReturn(CRDNUMBER, CRDDATE, REFERENCE,CUSTOMER,ITEM,QTYRETURN,UNITPRICE,TIAMOUNT1,TIAMOUNT2,EXTCRDMISC,TAMOUNT1,TAMOUNT2,CRDSUBTOT,CRDNET,CRDETAXTOT,CRDNETNOTX,CRDNETWTX,TransactionType) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
echo "after prepare";
$stmt->bind_param("ssssssssssssssssss",$CRDNUMBER,$CRDDATE,$REFERENCE,$CUSTOMER,$ITEM,$QTYRETURN,$UNITPRICE,$TIAMOUNT1,$TIAMOUNT2,$EXTCRDMISC,$TAMOUNT1,$TAMOUNT2,$CRDSUBTOT,$CRDNET,$CRDETAXTOT,$CRDNETNOTX,$CRDNETWTX,$TransactionType);
echo "after bind_param statement";

PHP MySQL Call to a member function execute() on a non-object

I got an error when I prepare my $query.
Here are the lines :
$query="INSERT INTO bm(title,season) VALUES(:title, :season)";
$stmt = $mysqli->prepare($query);
//$stmt->bind_param("ss", $title, $season);
$stmt->execute(array(':title' => $title, ':season' => $season));
I put the line with bind_param in //
I saw on others that could solve but error became roughly the same :
Fatal error: Call to a member function bind_param() on a non-object
So, I thought of my query but it's so simple I can't see anymore clearly. It's driving me nuts. :-/ I also tested the var $titleand $season with an echo just before the $query line to be sure, like this :
echo $title." et ".$season;
but nothing is wrong, values are ok. These are strings var. Any help would be very appreciated. Thanks.
Here is the complete code :
<?php
include("connexion.php");
// Get vars from previous form
//$id="";
$title = isset($_POST['title']) ? $_POST['title'] : "";
$season = isset($_POST['season']) ? $_POST['season'] : "";
// Testing vars
if (empty($titre) && empty($saison))
{
echo '<font color="red">Must be filled...</font>';
}
// Vars ok : could be inserted in "bm" table
else
{
// Protect - inject SQL
$title=$mysqli->real_escape_string(strip_tags($title));
$season=$mysqli->real_escape_string(strip_tags($season));
// Test
echo $title." et ".$season;
// Insert method
$query="INSERT INTO bm(title,season) VALUES(:title, :season)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $title, $season);
$stmt->execute(array(':title' => $title, ':season' => $season));
// Insert ok ?
if ($stmt) {
echo "Insert ok.";
}
else {
echo "Insert failed !";
}
}
//Close connexion
$mysqli->close();
?>
Try to change your database call as follows:
$query="INSERT INTO bm(title,season) VALUES(?, ?)";
$stmt = $mysqli->prepare($query);
//could be false if prepared statemant is somehow wrong
if ($stmt === false){
echo "Insert failed !";
}
else{
//bind the params to the variables
$stmt->bind_param("ss", $title, $season);
//no parameters allowed for execute method according to the doc
$success = $stmt->execute();
//check for $success if true/false
}
Why not use the most common used queing to fetch data from the database? The most commonly used is by using while loop for fetching data from the database right? I think that your approach(based on your code) perfectly works if you are using sqlsrv, but mysql and mysqli has almost the same syntax unlike from sqlsrv wherein it uses params to pass data, just my opinion :D
If you reference the documentation on PHP MYSQLI (http://php.net/manual/en/mysqli.prepare.php) you will notice that FALSE is returned when an error occurs in the prepare.
mysqli_prepare() returns a statement object or FALSE if an error occurred.
Instead of the call being from a mysqli_stmt object, it is from a FALSE boolean.
My assumption would be that the error occurs in your connection string if you are passing in proper variables. More code would be needed to troubleshoot further.

PHP & MySQL (Parse Error ) [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Parse error: syntax error, unexpected '[', expecting ')' [duplicate]
(2 answers)
Closed 7 years ago.
I am getting error:
Parse error: syntax error, unexpected ',', expecting '&' or variable (T_VARIABLE) in /root/folder/MySQLDao.php on line 67
However, everything seems fine. The chunk of code is:
public function registerUser($Facebookid, $firstname, $lastname, $FBpictureURL, $Gender, $UserEmail)
{
$sql = "insert into Users set FacebookId=?, firstname=?, lastname=?, FBpictureURL=?, Gender=?, UserEmail=?";
$statement = $this->conn->prepare($sql); // Line 66
// Line 67 is here
if (!$statement) // Line 68
throw new Exception($statement->error);
$statement->bind_param("isssss", $Facebookid, $firstname, $lastname, $FBpictureURL, $Gender, $UserEmail);
$returnValue = $statement->execute();
return $returnValue;
}
Edit: I got lots of criticism about duplicate post, however, none of the answers solved my solution so far. I have of course checked StackOverflow before I post my question. Anyway, the ones still willing to help, I pasted my code in here: http://justpaste.it/phpsql
Note:
Make sure that your given code is in MySQLDao.php file. Because it is hard to believe that it will return such error for that line (67), which is just blank.
Your insert query setup looks okay if your extension supports MySQL
It would look like this in standard form:
$sql = "INSERT INTO Users (FacebookId, firstname, lastname, FBpictureURL, Gender, UserEmail)
VALUES (?,?,?,?,?,?)";
Did you call the function correctly? Make sure that the passed-on variables for your registerUser() function is correctly passed-on from your POST form.
You may call your function like this (this is just an example way to call the function):
registerUser($_POST["Facebookid"],$_POST["firstname"],$_POST["lastname"],$_POST["FBPictureURL"],$_POST["Gender"],$_POST["UserEmail"]);
If the code in your given link is your updated copy, you forgot "SET" in your query.
It should look like this:
"INSERT INTO Users SET FacebookId=?, firstname=?, lastname=?, FBpictureURL=?, Gender=?, UserEmail=?";
in your sql statement there is 6 columns and in your bind_param function you are providing 7 params if there is no need of "issss" then please remove it because i thing it is id and if you have settle it as primary key and auto increment then you don't need to provide this argument
expected code:
$statement->bind_param($Facebookid, $firstname, $lastname, $FBpictureURL, $Gender, $UserEmail);

Fatal error: Cannot pass parameter 2 by reference when using PHP and MYSQL [duplicate]

This question already has answers here:
Cannot pass parameter 2 by reference - uuid PDO
(4 answers)
Closed 1 year ago.
I am using PHP PDO to insert into a MYSQL database using PHP. I am getting the error:
Fatal error: Cannot pass parameter 2 by reference in
/home/sandyit/public_html/hosting/findibuzz/design2/sign-up.php on
line 200
This is my code:
$ID is an auto incremented integer while the rest are varchar variables filled out as below as an example:
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'dbusername', 'dbpass');
$FULLNAME = "David";
$PW_HASH = "sadsad";
$SALT = "adadad";
$EMAIL_ADDRESS = "david#gmail.com";
$ID=0;
$addrequest = $db->prepare("INSERT INTO FB_USERS (ID,FULL_NAME,PASSWORD,PASSWORD_SALT,EMAIL_ADDRESS) VALUES (:ID,:FULL_NAME,:PASSWORD,:PASSWORD_SALT,:EMAIL_ADDRESS)");
$addrequest->bindParam(':ID',$ID, PDO::PARAM_INT);
$addrequest->bindParam(':FULL_NAME',$FULL_NAME, PDO::PARAM_STR);
$addrequest->bindParam(':PASSWORD',$PW_HASH, PDO::PARAM_STR);
$addrequest->bindParam(':PASSWORD_SALT',$SALT, PDO::PARAM_STR);
$addrequest->bindParam(':EMAIL_ADDRESS',$EMAIL_ADDRESS, PDO::PARAM_STR);
$addrequest->execute();
$addrequest->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I know i have something wrong, but i cannot spot the error, can i have some advise please?
Thanks
Just for reference. I know this wont help solve your problem, but you could do something like this (see code below) to achieve the same result:
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'dbusername', 'dbpass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO FB_USERS (FULL_NAME,PASSWORD,PASSWORD_SALT,EMAIL_ADDRESS)
VALUES (:FULL_NAME,:PASSWORD,:PASSWORD_SALT,:EMAIL_ADDRESS)";
$stmt = $db->prepare($sql);
$params = array
(
'FULL_NAME'=>'David',
'PASSWORD'=>'sadsad',
'PASSWORD_SALT'=>'adadad',
'EMAIL_ADDRESS'=>'david#gmail.com'
);
$stmt->execute($params)
I find it easier to work with an array and than to just pass it to the statment.
But I guess its just a mather of taste.
Like I said this is just for reference and wont help you resolve your issue.
Remove quotation marks from '$ID'
$addrequest->bindParam(':ID',$ID, PDO::PARAM_INT);

Categories