INSERT using PDO prepared statements fatal error [duplicate] - php

This question already has answers here:
What is the difference between bindParam and bindValue?
(7 answers)
Closed 7 years ago.
I'm trying to insert values using prepared statements like this:
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user_table (first_name, last_name) VALUES (:tname, :tname2)";
$stmt = $dbh->prepare($sql);
$stmt -> bindParam(':tname', 'John');
$stmt -> bindParam(':tname2', 'Smith');
$stmt -> execute();
However, this is throwing a fatal error: "PHP Fatal error: Cannot pass parameter 2 by reference in /Applications/MAMP/htdocs/live/test_create.php on line 53" This is referring to this line: $stmt -> bindParam(':tname', 'John');
What's causing this problem?

When using bindParam it must be passed by reference.
Use bindValue instead, for the way you are trying to use it here.
More about bindValue vs bindParam here
If you are insistent about using bindParam, it must be supplied as a variable. So you would use $var1="John" and then $stmt->bindParam(':tname',$var1);

Related

Multiple queries mysqli [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
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 years ago.
I'm trying to input multiple queries guys using mysqli. Yet it's not populating the database. Any ideas?
$q2="UPDATE ticketinfo SET ticketstatus = $status where ticketno = $ticket;
insert into ticketinfo (remarks) values ('$remarks')";
$ex2= mysqli_multi_query($conn,$q2);
SQL queries should be executed sequentially. Never use mysqli_multi_query() with variable input. You should be using parameterized prepared statements. There is hardly any use case for mysqli_multi_query() at all.
Your code should look like this:
// your mysqli connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8mb4'); // always set the charset
// First query
$stmt = $mysqli->prepare('UPDATE ticketinfo SET ticketstatus = ? WHERE ticketno = ?');
$stmt->bind_param('ss', $status, $ticket);
$stmt->execute();
// Second query
$stmt = $mysqli->prepare('INSERT INTO ticketinfo (remarks) VALUES (?)');
$stmt->bind_param('s', $remarks);
$stmt->execute();
I used two prepared statements and bound the input separately. This much better, cleaner and safer option than mysqli_multi_query().

Changing PDO to Mysqli [duplicate]

This question already has answers here:
How to convert PDO to mysqli?
(2 answers)
Closed 3 years ago.
I want to convert PDO code to mysqli and having some problem. I'm still new at this and I really don't understand PDO completely.
$query = "INSERT INTO gender(gender) VALUES (:gender)";
$statement = $conn->prepare($query);
$statement->execute(array('gender' => $_POST["gender"]));
$count = $statement->rowCount();
This is far I got.
$statement = $db->prepare ($query);;
$statement = array('gender' => $_POST["gender"]);
$count=mysqli_num_rows($query);
$statement = mysqli_fetch_array ($query);
Try this version:
$query = "INSERT INTO gender(gender) VALUES (?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $_POST["gender"]);
$stmt->execute();
$stmt->close();
You need to use the bind_param() function to bind parameters to your mysqli statement. Note that mysqli, unlike PDO, does not support named parameters. Instead, just use ? as a placeholder to which you bind your actual value later on.

PDO MySQL query failing with more than one comparison operator [duplicate]

This question already has answers here:
php pdo prepare repetitive variables
(2 answers)
PHP's PDO prepared statement: am I able to use one placeholder multiple times? [duplicate]
(1 answer)
Closed 4 years ago.
I'm sure I'm just formatting this incorrectly but I'm getting a PDO exception with one of my queries and the debug isn't helping.
if I run the following it's works fine :
$db = static::getDB();
$sql = 'SELECT * FROM djs WHERE day = :day
AND start_hour = :hr AND shifts LIKE :shift';
$stmt = $db->prepare($sql);
$stmt->bindParam(':day', $arr['day'], PDO::PARAM_STR);
$stmt->bindParam(':hr', $arr['hr'], PDO::PARAM_INT);
$stmt->bindParam(':shift', $shift, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_OBJ);
But when I try to add more than one comparison operator in the query like this :
$sql = 'SELECT * FROM djs WHERE day = :day
AND start_hour > :hr AND end_hour <= :hr
AND shifts LIKE :shift';
It throws the following exception pointing to the line containing the execute command :
Uncaught exception: 'PDOException'
Message: 'SQLSTATE[HY093]: Invalid parameter number'
end_hour is a valid column in the table and I'm trying to ascertain if the star_hour is greater than :hr and the end_hour is less than or equal to :hr. I must be doing this wrong. Any pointers please? It is because I'm using the same named parameter :hr in the query twice but only binding it once? If so what is the solution other than setting up another named parameter with the same data?
Try to use different names for the parameters, even if you are using the same value:
$db = static::getDB();
$sql = 'SELECT * FROM djs WHERE day = :day
AND start_hour > :hr1 AND end_hour <= :hr2
AND shifts LIKE :shift';
$stmt = $db->prepare($sql);
$stmt->bindParam(':day', $arr['day'], PDO::PARAM_STR);
$stmt->bindParam(':hr1', $arr['hr'], PDO::PARAM_INT);
$stmt->bindParam(':hr2', $arr['hr'], PDO::PARAM_INT);
$stmt->bindParam(':shift', $shift, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_OBJ);

Does not work markers in prepeared statments [duplicate]

This question already has answers here:
Table name as parameter using PDO/MySQL prepared statement [duplicate]
(2 answers)
Closed 8 years ago.
$dbh = new PDO('mysql:host=' . $_POST['db_host'], $_POST['db_user'], $_POST['db_user_password']);
$sql = 'CREATE DATABASE :db_name';
$sth = $dbh->prepare($sql);
$sth->bindParam(':db_name', $_POST['db_name']);
var_dump($sth->execute());
It's allways show false. But if directly specify db_name, like this:
$sql = 'CREATE DATABASE database';
$sth = $dbh->prepare($sql);
$sth->execute();
It will work. What I'm doing wrong?
You can only bind data (column values) in parametrized query, not column name and table name. Also, in your code you tried to parametrize connection initialization which I think not correct.
You can alternatively depend on white list of db names:
$databases = array('dbone', 'dbtwo');
then check
if(in_array($_POST['db_name'], $databases) ){
$dbname = $_POST['db_name'];
}

PHP MYSQL PDO lastInsertId is returning 0 when using a procedure to insert rows [duplicate]

This question already has an answer here:
why pdo->lastInsertId() return 0 when i call STORED PROCEDURE in mysql?
(1 answer)
Closed 9 years ago.
I keep getting zero for LastInsertedID, I think it is because I am using a mysql stored procedure. Here is my code:
// Set up a new MYSQL PDO Database Connection
$dbConnection = new PDO('mysql:host=localhost;dbname=database;charset=UTF8', 'username', 'password');
//turn off emulation for prepared statement and set error mode option
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Create a statement and prepare it with parameters
$stmt = $dbConnection->prepare("CALL AddMovieSet(:UserID, :SelectedLibraryID, :txtName, :txtNotes);");
$stmt->bindValue(':UserID', $_SESSION["UserID"], PDO::PARAM_STR);
$stmt->bindValue(':SelectedLibraryID', $_SESSION["SelectedLibraryID"], PDO::PARAM_STR);
$stmt->bindValue(':txtName', $_GET["txtName"], PDO::PARAM_STR);
$stmt->bindValue(':txtNotes', $_GET["txtNotes"], PDO::PARAM_STR);
//execute the prepared statement
$stmt->execute();
//the stored procedure successfully inserts a row
$Name=$_GET["txtName"];
$Notes=$_GET["txtNotes"];
$InsertedID=$dbConnection->lastInsertId();
//$InsertedID is always zero, the table I am inserting a row into has an AUTO_INCREMENT for the first column.
Sometimes PHP and PDO can be buggy with lastInsertID() and stored procedures. Try using this MySQL call instead:
"SELECT LAST_INSERT_ID();"

Categories