I am using named placeholders like so:
$job['services_flag'] = 0;
$SQL = "INSERT INTO jobs (
services_flag
)
VALUES (
:services_flag
)";
$STH = $DBH->prepare($SQL);
$STH->execute($job);
However, this insists on inserting 1.
If I don't use named placeholders:
$SQL = "INSERT INTO jobs (
services_flag
)
VALUES (
0
)";
$STH = $DBH->prepare($SQL);
$STH->execute();
Then it inserts 0. Eh?
Update:
The data type of the services_flag field in my SQL database is BIT. I don't know if that makes any difference.
This is a known bug with BIT type, you should use bindParam for it
You need to bind a value to it:
$STH->bindValue(':services_flag', $job['services_flag']);
$STH->execute();
That's one way to do it. I've seen an array with values mapped to placeholders passed in the execute() as well.
Related
Is it possible to retrieve the rowid of the last inserted Oracle row in PHP? I was trying:
$statement = oci_parse($conn, "INSERT INTO myTable (...) VALUES ( ...)");
$results = oci_execute($statement);
while($row = oci_fetch_assoc($statement)) {
$rowid = $row['ROWID'];
}
With no luck. I'm getting the error define not done before fetch or execute and fetch at the fetch line.
Declare:
$var = "AAAV1vAAGAAIb4CAAC";
Use:
INSERT INTO myTable (...) VALUES ( ...)
RETURNING RowId INTO :p_val
Bind your variable to a PHP variable:
oci_bind_by_name($statement, ":p_val", $val, 18);
As the previous answer was not really clear to me because it lacks some important information I will point out a similar approach.
In your SQL statement, add the RETURNING INTOclause.
$statement = oci_parse($conn, "INSERT INTO myTable (...) VALUES ( ...) RETURNING ID INTO :id");
Here ID is the name of the column you want to return. Before executing the $statement, you need to bind a PHP variable to your return value. Here I used $returnId (you don't need to declare it beforehand or assign any default value).
oci_bind_by_name($statement, ":id", $returnId);
Only after binding the variable, the statement can be executed.
$success = #oci_execute($statement);
$returnId now has the value of the ID column inserted previously.
I am preparing mysql configuration settings using class. I am confused about it. I always use bindParam. It also possible to insert using array. I mean, what are the differences between array and bindparam.
eg array
$query = $db->prepare("INSERT INTO users SET
username = :uname,
password = :upass,
email = :umail");
$insert = $query->execute(array(
"upass" => "123456",
"umail" => "user#user.com",
"uname" => "username",
));
if ( $insert ){
$last_id = $db->lastInsertId();
}
eg
$stmt = $this -> db_conn -> prepare("INSERT into users(username, password) VALUES(:uname, :upass)");
$stmt -> bindParam(':uname', $username);
$stmt -> bindParam(':upass', $password);
$stmt -> execute();
Desconsidering the fact that with execute you can't choose the data type (it's always PDO::PARAM_STR) There's only a main difference between both (which is from core). PDOStatement::bindParam is by reference while PDOStatement::execute isn't. PDOStatement::execute do internnaly the same thing as PDOStatement::bindValue, but twice.
Internally (in C), bindValue calls the same method which execute calls. The method name which is called is really_register_bound_param.
On the other hand, bindParam calls other method called register_bound_param.
It means that bindValue calls the same method called by execute more than one time while bindParam calls a method to bind as a reference and only "really register" the param when execute is called.
Thinking about bind by reference, it's only possible using bindParam:
//fictional code
$stmt= $pdo->prepare("INSERT INTO table (column) VALUES (:value)");
$stmt->bindParam(":value", $randomValue);
for($i = 0 ; $i < 1000; $i))
{ $randomValue = rand(1000,1000000);
$stmt->execute();
}
Is it worthy? Perhaps while a while with a complex insert with multiples parameters could reduce the overhead with rebinding a new parameter or a big amount of them.
I am trying to get the id of the last record inserted in an mssql database using pdo via php. I HAVE read many posts, but still can't get this simple example to work, so I am turning to you. Many of the previous answers only give the SQL code, but don't explain how to incorporate that into the PHP. I honestly don't think this is a duplicate. The basic insert code is:
$CustID = "a123";
$Name="James"
$stmt = "
INSERT INTO OrderHeader (
CustID,
Name
) VALUES (
:CustID,
:Name
)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
I have to use PDO querying an MSSQL database. Unfortunately, the driver does not support the lastinsertid() function with this database. I've read some solutions, but need more help in getting them to work.
One post here suggests using SELECT SCOPE_IDENTITY(), but does not give an example of how incorporate this into the basic insert code above. Another user suggested:
$temp = $stmt->fetch(PDO::FETCH_ASSOC);
But, that didn't yield any result.
If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this:
$CustID = "a123";
$Name="James"
$stmt = "INSERT INTO OrderHeader (CustID, Name)
OUTPUT INSERTED.id
VALUES (:CustID, :Name)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result["id"]; //This is the last inserted id returned by the insert query
Read more at:
https://msdn.microsoft.com/en-us/library/ms177564.aspx
http://php.net/manual/es/pdo.lastinsertid.php
I need to insert encrypted values in mysql table, but when I use traditional pdo method to insert its inserting the data in wrong format. ex: I insert aes_encrypt(value, key) in place of inserting encrypted value its inserting this as string.
Following is the code :
$update = "insert into `$table` $cols values ".$values;
$dbh = $this->pdo->prepare($update);
$dbh->execute($colVals);
$arr = array("col"=>"aes_encrypt ($val, $DBKey)");
I know i am doing it wrong, but not able to find correct way.
You are almost there, here is a simplified version:
<?php
$sql = "insert into `users` (`username`,`password`) values (?, aes_encrypt(?, ?))";
$stmt = $this->pdo->prepare($sql);
// Do not use associative array
// Just set values in the order of the question marks in $sql
// $fill_array[0] = $_POST['username'] gets assigned to first ? mark
// $fill_array[1] = $_POST['password'] gets assigned to second ? mark
// $fill_array[2] = $DBKey gets assigned to third ? mark
$fill_array = array($_POST['username'], $_POST['password'], $DBKey); // Three values for 3 question marks
// Put your array of values into the execute
// MySQL will do all the escaping for you
// Your SQL will be compiled by MySQL itself (not PHP) and render something like this:
// insert into `users` (`username`,`password`) values ('a_username', aes_encrypt('my_password', 'SupersecretDBKey45368857'))
// If any single quotes, backslashes, double-dashes, etc are encountered then they get handled automatically
$stmt->execute($fill_array); // Returns boolean TRUE/FALSE
// Errors?
echo $stmt->errorCode().'<br><br>'; // Five zeros are good like this 00000 but HY001 is a common error
// How many inserted?
echo $stmt->rowCount();
?>
you can try it like this.
$sql = "INSERT INTO $table (col) VALUES (:col1)";
$q = $conn->prepare($sql);
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey)));
I've gotten a little confused with the PDO::prepare functions.
I have something like this
array('user_email'=>'hello#net.com','user_pass'=>'password')
and i'd like to translate it into something like this
INSERT INTO user_info (user_email, user_pass) VALUES (hello#net.com, password)
using parameterized queries with PDO (or mysqli, I'm open to suggestions).
Another idea -
array('uid'=>'10', 'first_name'=>'robert', 'last_name'=>'jones')
array("email", "number")
into
SELECT email, number FROM t1 WHERE uid=10 AND first_name=robert AND last_name=jones
I know the answer lies somewhere with PDO::prepare and call_user_func_array, but I've gotten really confused on how the latter function works, and would appreciate an explanation.
I'm confused, and maybe you are too. Here is a simple example:
$sth = $dbh->prepare('SELECT * FROM table WHERE id = ? AND date = ?');
$sth->execute(array(150, '2009-04-04'));
$data = $sth->fetchAll();
Or:
$sth = $dbh->prepare("INSERT table VALUES(:foo, :bar)");
$sth->bindParam(":foo", $foo);
$sth->bindParam(":bar", $bar);
Or:
$sth = $dbh->prepare("INSERT INTO user_info (user_email, user_pass) VALUES (:email, :pass)");
$sth->execute(array(':email' => 'foo#example.org', ':pass' => '1234'));
Hope this helps!
PDOStatement::execute() works with parameters markers, so you have to construct query before calling PDO::prepare().
You don't have to use call_user_func_array(). PDOStatement::execute() takes associative arrays by default.
$stmt = $pdo->prepare("SELECT fld FROM tbl WHERE fld=:parameter1 AND fld2=:parameter2");
$stmt->execute(array(":parameter1" => "value1", ":parameter2" => "value2"));
...
http://se.php.net/manual/en/pdo.prepare.php