Good evening to everyone,
Sorry if my question apperes sily but I'm pazzled by my very trivial problem
In one of the pages of my project I can't concatenate a string containing ' signs
this string can't be concatenated:
$stidR = "INSERT INTO rec_ret_info VALUES('".$rrcode."', ".$modnum.", '".$sdate."', '".$venue."', ".$fac.", ".$date.", ".$sem.")";
but this can:
$stidR = "INSERT INTO rec_ret_info VALUES(".$rrcode.", ".$modnum.", ".$sdate.", ".$venue.", ".$fac.", ".$date.", ".$sem.")";
Apparently if I remove ' signs it works. But i really need them. I really don't know where is the problem. Would be gratefull if you can point me on it.
Can you use a prepared statement to bind a variable?
Connection to Oracle with PDO - More information!
Update
PDO Prepared Statement as an example. The only thing you need to change is the query structure if Oracle is different to MySql in that regard. The binding of variables and the execution will work the same :)
$queryString= "INSERT INTO tablename (ColumnName1,ColumnName2,ColumnName3,ColumnName4,ColumnName5,ColumnName6,ColumnName7) VALUES (?,?,?,?,?,?,?)";
$query = $db->prepare($queryString);
$query->bindValue(1, $variable1, PDO::PARAM_STR);
$query->bindValue(2, $variable2, PDO::PARAM_STR);
$query->bindValue(3, $variable3, PDO::PARAM_STR);
$query->bindValue(4, $variable4, PDO::PARAM_STR);
$query->bindValue(5, $variable5, PDO::PARAM_STR);
$query->bindValue(6, $variable6, PDO::PARAM_STR);
$query->bindValue(7, $variable7, PDO::PARAM_STR);
$query->execute();
simply make echo of your statement like
echo $stidR ; and check the resulting sql, and see what you are doing wrong
Related
FYI: this file is my very first touch with PDO.
I have converted a mysqli PHP file info a PDO PHP file, it works fine. File's goal is: if user does not pass any value on keys ($ca_key1 - $ca_key3) just insert data on DB. If keys are passed and do not exist on DB, insert data on DB. If they do exist, echo an error.
I knew PDO could seem redundant, but in this case where I use same parameters up to 3 times on the same file, I ask: is there any way of binding parameter just one time and use it on the 3 executions? For example, ca_key1 could be just binded once and used on the 3 executions?
If you find any error/mistake on the file apart from this, I would appreciate if you mention me. I'd like to adapt good habits on PDO from the begining.
<?php
session_start();
include("../conexionbbdd.php");
if($_SESSION['estado'] == 'activo'){
if (isset($_POST['ca_name'])&&isset($_POST['ca_content'])&&isset($_POST['ca_img'])&&isset($_POST['ca_key1'])&&isset($_POST['ca_key2'])&&isset($_POST['ca_key3'])){
//CHECK IF USER PASSED VALUES ON KEYS
$ca_key1=$_POST['ca_key1'];
$ca_key2=$_POST['ca_key2'];
$ca_key3=$_POST['ca_key3'];
//IF PASSED, CHECK IF VALUES EXIST ON DB
if ($ca_key1!=="" || $ca_key2!=="" || $ca_key3!==""){
$selectKeys= "SELECT ca_key1,ca_key2,ca_key3 FROM ws_campaigns WHERE ca_fk_us_id = :us_id AND ("
. " (ca_key1!='' AND ca_key1 = :ca_key1) OR (ca_key2!='' AND ca_key2 = :ca_key1) OR (ca_key3!='' AND ca_key3 = :ca_key1) "
. "OR (ca_key1!='' AND ca_key1 = :ca_key2) OR (ca_key2!='' AND ca_key2 = :ca_key2) OR (ca_key3!='' AND ca_key3 = :ca_key2)"
. "OR (ca_key1!='' AND ca_key1 = :ca_key3) OR (ca_key2!='' AND ca_key2 = :ca_key3) OR (ca_key3!='' AND ca_key3 = :ca_key3))";
$statementKeys = $pdo->prepare($selectKeys);
$statementKeys->bindParam(':us_id', $_SESSION['id'], PDO::PARAM_INT);
$statementKeys->bindParam(':ca_key1', $_POST['ca_key1'], PDO::PARAM_STR);
$statementKeys->bindParam(':ca_key2', $_POST['ca_key2'], PDO::PARAM_STR);
$statementKeys->bindParam(':ca_key3', $_POST['ca_key3'], PDO::PARAM_STR);
$statementKeys->execute();
$cuenta = $statementKeys->rowCount();
//IF NOT EXIST, INSERT DATA
if ($cuenta === 0){
$insertCampaign = "INSERT INTO ws_campaigns(ca_id,ca_name, ca_content,ca_fk_us_id,ca_img,ca_prefix,ca_key1,ca_key2,ca_key3
)VALUES('',:ca_name,:ca_content,:us_id,:ca_img,'34',:ca_key1,:ca_key2,:ca_key3)";
$statementInsertCampaign = $pdo->prepare($insertCampaign);
$statementInsertCampaign->bindParam(':us_id', $_SESSION['id'], PDO::PARAM_INT);
$statementInsertCampaign->bindParam(':ca_name', $_POST['ca_name'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_content', $_POST['ca_content'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_img', $_POST['ca_img'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key1', $_POST['ca_key1'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key2', $_POST['ca_key2'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key3', $_POST['ca_key3'], PDO::PARAM_STR);
$statementInsertCampaign->execute();
$newId = $pdo->lastInsertId();
echo $newId;
}
else{
echo "No se ha creado la campaña. <br>Alguna de las palabras clave utilizadas ya están presentes en una campaña anterior.";
}
}else{
//IF NO VALUES PASSED, INSERT DATA
$insertCampaign = "INSERT INTO ws_campaigns(ca_id,ca_name, ca_content,ca_fk_us_id,ca_img,ca_prefix,ca_key1,ca_key2,ca_key3
)VALUES('',:ca_name,:ca_content,:us_id,:ca_img,'34',:ca_key1,:ca_key2,:ca_key3)";
$statementInsertCampaign = $pdo->prepare($insertCampaign);
$statementInsertCampaign->bindParam(':us_id', $_SESSION['id'], PDO::PARAM_INT);
$statementInsertCampaign->bindParam(':ca_name', $_POST['ca_name'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_content', $_POST['ca_content'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_img', $_POST['ca_img'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key1', $_POST['ca_key1'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key2', $_POST['ca_key2'], PDO::PARAM_STR);
$statementInsertCampaign->bindParam(':ca_key3', $_POST['ca_key3'], PDO::PARAM_STR);
$statementInsertCampaign->execute();
$newId = $pdo->lastInsertId();
echo $newId;
}
}else{
header('location:../paneles/campana.php?msg=nodata');
}
}else{
header('location:../login.php?msg=nopermission');
}
?>
Actually, you don't have to bind [explicitly] at all.
PDO is a great step further compared to mysqli, and this is one of it benefits: you can create an array of variables, and pass them directly into execute(), instead of binding them one by one - PDO will bind them internally, using PDO::PARAM_STR by default, which is not a problem most of time, save for only one case - LIMIT clause parameres.
It is not only greatly reduces amount of code, but also let you to reuse the same set of variables with different queries.
$data = array(
'us_id' => $_SESSION['id'],
'ca_name' => $_POST['ca_name'],
// and so on
);
$stmt->execute($data);
Of course, array keys have to match placeholders in the query. If your queries have different sets of placeholders, you will need different arrays as well.
Following problem:
If I want to search with 'Last Name' it works but if it is a variable in this form $results['22']['BuyerName2']
Here is what I got so far:
$rr=$results[22]['BuyerName2'];
echo $rr; //echos Last Name
$stmt = $db->prepare("Update base_1 SET UpdateStatus=2 WHERE BuyerName LIKE ?");
$stmt->bindValue(1, "%$rr%", PDO::PARAM_STR);
$stmt->execute();
If I put instead $rr the Name directly in the bind value part it works. But not with $rr.
Maybe there are extra spaces in $rr. Try:
$rr = trim($results[22]['BuyerName2']);
In the line:
$stmt->bindValue(1, "%$rr%", PDO::PARAM_STR);
I am unsure whether the $ becomes escaped or not in the string you binded. As far as I know, only the underscore and the percent sign stay unescaped. I would suggest to try:
$rr = "%".$rr."%";
and edit the line to:
$stmt->bindValue(1, $rr, PDO::PARAM_STR);
I am trying to get this script to run, but I fail on a very simple stupid thing that has kept me getting further for the past 2 hours.
I have written a PDO statement in a function of a class that inserts a bunch of integers in a mysql db.
If I call on the function from a file using
$result->createResult(0, 0, 0,0,0,0,0,"1234",0);
it does not work.
If I use
$result->createResult(1, 1, 1,1,1,1,1,"1234",1);
it runs just fine!
the function that created the mysql entry is
public function createResult($id, $pp_id, $i_id, $ii_id, $cs_id, $ed_id, $em_id, $l_id, $ud_id){
if ($this->databaseConnection()) {
$query_new_result_insert = $this->db_connection->prepare('INSERT INTO results (id, pp_id, i_id, ii_id, cs_id, ed_id, em_id, l_id, ud_id, created_at) VALUES(:id, :pp_id, :i_id, :ii_id, :cs_id, :ed_id, :em_id, :l_id, :ud_id, now())');
$query_new_result_insert->bindValue(':id', $id, PDO::PARAM_INT);
$query_new_result_insert->bindValue(':pp_id', $pp_id, PDO::PARAM_INT);
$query_new_result_insert->bindValue(':i_id', $i_id, PDO::PARAM_INT);
$query_new_result_insert->bindValue(':ii_id', $ii_id, PDO::PARAM_INT);
$query_new_result_insert->bindValue(':cs_id', $cs_id, PDO::PARAM_INT);
$query_new_result_insert->bindValue(':ed_id', $ed_id, PDO::PARAM_INT);
$query_new_result_insert->bindValue(':em_id', $em_id, PDO::PARAM_INT);
$query_new_result_insert->bindValue(':l_id', $l_id, PDO::PARAM_STR);
$query_new_result_insert->bindValue(':ud_id', $ud_id, PDO::PARAM_INT);
$query_new_result_insert->execute();
}
}
this seems to crash on 0 values. if I check (empty($i_id)) it returns true.
I can't get my head around this! Could anyone be so kind to help?
Ok, I finally figured it out...
It wasn't the table structure, but the empty check...
empty returns true on value 0 as described here
I have two inserts on a processing page. The first works without a hitch. The second will not even activate. I even tried putting a PDO query to see if it would work but still nothing.
$cpinsert = $db->prepare('insert into Chatposts values (0, :chatid, :name, :url, :text, now(), :ipaddress, 0)');
$cpinsert -> bindParam(':chatid', $chatroomid, PDO::PARAM_INT);
$cpinsert -> bindParam(':name', $name, PDO::PARAM_STR);
$cpinsert -> bindParam(':url', $url, PDO::PARAM_STR);
$cpinsert -> bindParam(':text', $text, PDO::PARAM_STR);
$cpinsert -> bindParam(':ipaddress', $ipaddress, PDO::PARAM_STR);
$cpinsert -> execute();
// Needs an error checker
$cpid = $cpinsert ->lastInsertID();
$cpinsert->closeCursor();
^ That works fine, though I don't know about the lastinsertid since I cannot test it.
\V/ Nothing in there will execute no matter what I try. Something is preventing anything there from executing or I didn't close the above's connection properly.
// Targets Insert
//if (isset($target)):
$query = "insert into Targets values (9,'rommel')";
$db->query($query);
$targetinsert = $db->prepare('insert into Targets values (:cpid,:tname)');
foreach ($target as $tname):
$targetinsert -> bindParam(':cpid', $cpid, PDO::PARAM_INT);
$targetinsert -> bindParam(':tname', $tname, PDO::PARAM_STR);
endforeach;
$targetinsert -> execute();
//endif;
I have tried everything I know of and no luck. It is quite possible I did a minor mistake since I am new to PDO. Closecursor didn't seem to do anything either when I added it in.
You said you need to do execute many inserts, but for some reason you are executing your query only once.
Also, please remove these try..catch things from your code - they are the reason why you have no idea what's going wrong
I had to recreate a half functional model of my page but I found the problem, it was lastinsertid(). I was applying a PDOstatement class on a PDO class.
Before:
$cpid = $cpinsert->lastInsertID();
After:
$cpid = $db->lastInsertID();
I just had to call the Database instead of the prepare with that line of code.
Just as usual i was looking around best practices with PHP, and prepared statements seems the kind of stuff i should now how do with my eyes closed. So i started playing around with some examples i've found.
I've got this error when running the script:
Fatal error: Call to a member function
bindParam() on a non-object in
/opt/lampp/htdocs/phpSecurity/PreparedStatments/Insert-Multi-Binded-Params/Insert
Simple Method.php on line 10
Here it goes the code.
Insert Simple Method.php
<?php
require_once '../config.php';
$stmt = $db->prepare("INSERT INTO coisas (nome, telefone, bi) VALUES (?, ?, ?)");
$nome = 'Fabio Antunes';
$telefone = 916810641;
$bi = 123093456;
$stmt->bindParam(1, $nome);
$stmt->bindParam(2, $telefone);
$stmt->bindParam(3, $bi);
$stmt->execute();
$stmt->close();
$db->close();
?>
config.php
<?php
$server_host = 'localhost';
$server_user = 'root';
$server_password = '';
$server_db = 'PreparedStatements';
$db = new mysqli($server_host, $server_user, $server_password, $server_db);
?>
Not sure what i'm doing wrong here, this is similar example found at php.net, why isn't working?
PS: I think the mysqli connection isn't the problem because I've used it to do some prepared statements with SELECT SQL commands. And worked pretty well.
EDIT
The Resolution and why.
Well in the example i should use bind_param() for each value in the query. But thanks to Bart, he managed to solve the problem with my code.
Where it is:
$stmt->bindParam(1, $nome);
$stmt->bindParam(2, $telefone);
$stmt->bindParam(3, $bi);
It should be:
$stmt->bind_param("sii", $nome, $telefone, $bi);
Now for those who might wondering what is "sii".
Well bind_param for what i see it binds the "$var" to each question mark "?" in order.
So with one bind_param() i can bind them all at the same time, and the normal use of bind_param() requires to specify the type of data being binded.
My first value to be binded is $nome a String, specified by the "s";
And the others $telefone and $bi are Integers for that he have "i";
For others that have a similar problem here it goes other data types (from php.net).
i = Integer;
s = String;
d = Double;
b = Blob;
If someone as a better explanation please post it or comment. So i can improve my own.
Thanks.
You may think there's nothing wrong with the connection, but you should check to make sure:
$db = new mysqli($server_host, $server_user, $server_password, $server_db);
if (mysqli_connect_errno()) {
printf("DB error: %s", mysqli_connect_error());
exit();
}
EDIT:
What happens when you do:
$stmt = $db->prepare("INSERT INTO coisas (nome, telefone, bi) VALUES (?, ?, ?)");
$stmt->bind_param("sii", $nome, $telefone, $bi);
$stmt->execute();
?
Is the table coisas spelled properly?
do a print_r on $stmt after you get it back on line 4. Is it a real object? I am guessing no.