PHP parameter binding for mysql insert if not exist - php

I am reading and referencing different posts on how to insert if not exists. This is a good thread but I need some additional help.
I need to add a new record with about 10 columns in it, but only insert it if two columns don't match. I also need to do parameter binding on it.
$query = "INSERT INTO Customers (col1,col2,col3,col4,col5,col6)
SELECT * FROM (SELECT ?,?,?,?,?,?) AS tmp
WHERE NOT EXISTS (
SELECT col1 from Customers WHERE uid=? AND pid=?
) LIMIT 1;"
$results = dbQuery($query,(array($val1,$val2,$val3,$val4,$val5,$val6,$uid,$pid)) ;
What am I doing wrong here?
And here is dbQuery call:
function dbQuery($query,$data) {
global $pdo ;
$stmt = $pdo->prepare($query);
$result = $stmt->execute($data) ;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$error = $stmt->errorInfo() ;
if ($result == false) {
var_dump($error) ;
}
return array($result,$error,$rows) ;
}

"?" parameter placeholders aren't named, they're passed by position, so you can't use them more than once.
You could pass uid/pwd twice; but better is to used named parameters passed as a map
(https://www.php.net/manual/en/pdostatement.execute.php)
$query = "INSERT INTO Customers (uid,pid,col3,col4,col5,col6)
SELECT * FROM (SELECT :uid, :pid, :val3, :val4, :val5, :val6) AS tmp
WHERE NOT EXISTS (
SELECT * from Customers WHERE uid = :uid AND pid = :pid
)";
$results = dbQuery($query,(array("uid"=>$uid, "pid"=>$pid, "val3"=>$val3, "val4"=>$val4, "val5"=>$val5, "val6"->$val6)));
Note using the parameter array means all the parameters come through as strings, which may not be what you want. You would have to use bindParam to set specifically typed values.
Best of all would be a stored procedure that allows you to define parameters, use proper binding, and prevent any accidental datatype mismatches.

Related

How to match auto increment from table 1 into table 2 in POST method PHP [duplicate]

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.

Pass an SQL query to php PDO function and execute [duplicate]

Currently Im trying to create a PDO class where I will have a method to run a query like INSERT, UPDATE, or DELETE.
For examaple this is my method for a SELECT
public function getPreparedQuery($sql){
$stmt = $this->dbc->prepare($sql);
$stmt->execute([5]);
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(!$arr) exit('No rows');
$stmt = null;
return $arr;
}
And i Simply call it like this:
$stmt = $database->getPreparedQuery($sql2);
var_export($stmt);
And so far I know that a runQuery should work something similar to this:
Insert Example without using a method:
$idRol = "6";
$nomRol = "test6";
$stmt = $database->dbc->prepare("insert into roles (idRol, NomRol) values (?, ?)");
$stmt->execute(array($idRol,$nomRol));
$stmt = null;
But I want to make it into an universal method where i simply can pass the sql sentence, something like this:
$database->runQuery($query);
but the query can happen to be
$query = "INSERT INTO roles (idRol, NomRol) VALUES ('4','test')";
or
$query = "INSERT INTO movies (movName, movLength, movArg) VALUES ('name1','15','movie about...')";
So how do I slice the arg $query so I can get all the variables that are being used in order to make an universal runQuery?
Because I can imagine that my method should be something like this
runQuery([$var1 , $var2, $var3....(there can be more)] , [$var1value, $var2value, $var3value...(there can be more)]){
$stmt = $database->dbc->prepare("insert into movies($var1 , $var2, $var3....(there can be more)) values (?, ? , ? (those are the values and there ca be more than 3)"); //how do i get those "?" value and amount of them, and the name of the table fields [movName, movLength, movArg can be variable depending of the sentence]?
$stmt->execute(array($var1,$var2, $var3, ...)); //this is wrong , i dont know how to execute it
$stmt = null;
}
You need to add a second parameter to your function. Simply an array where all those variables would go. An array by definition can have an arbitrary number of elements, which solves your problem exactly:
public function runQuery($sql, $parameters = []) {
$stmt = $this->dbc->prepare($sql);
$stmt->execute($parameters);
return $stmt;
}
this simple function will run ANY query. You can see the usage example in my article dedicated to PDO helper functions:
// getting the number of rows in the table
$count = $db->runQuery("SELECT count(*) FROM users")->fetchColumn();
// the user data based on email
$user = $db->runQuery("SELECT * FROM users WHERE email=?", [$email])->fetch();
// getting many rows from the table
$data = $db->runQuery("SELECT * FROM users WHERE salary > ?", [$salary])->fetchAll();
// getting the number of affected rows from DELETE/UPDATE/INSERT
$deleted = $db->runQuery("DELETE FROM users WHERE id=?", [$id])->rowCount();
// insert
$db->runQuery("INSERT INTO users VALUES (null, ?,?,?)", [$name, $email, $password]);
// named placeholders are also welcome though I find them a bit too verbose
$db->runQuery("UPDATE users SET name=:name WHERE id=:id", ['id'=>$id, 'name'=>$name]);
// using a sophisticated fetch mode, indexing the returned array by id
$indexed = $db->runQuery("SELECT id, name FROM users")->fetchAll(PDO::FETCH_KEY_PAIR);
As you can see, now your function can be used with any query with any number of parameters

Query after query in pdo? Binding problems [duplicate]

This question already has an answer here:
PDO pagination with LIKE
(1 answer)
Closed 2 years ago.
I have one doubt about PDO.
I have a method in the class that returns data from the database for sent filters.
I want to get a number of rows for that query, but there are LIMIT and STAR in the query.
So because of that, I am using two queries to get a number of rows and data but to work, I need to bind the same value two times. Is there any more elegant way to achieve not have repeated code?
The method that I use is below.
$db = $this->openConnection();
$sql = " SELECT * FROM contacts";
// Filter data by main search input
if(!empty($search_query)){
$sql .= " WHERE ( location LIKE :search_query_location OR address LIKE :search_query_address ) ";
}
$sql .=" ORDER BY ".$order;
$stmt = $db->prepare($sql);
if(!empty($search_query)){
$stmt->bindValue(':search_query_location', (string) $search_query.'%');
$stmt->bindValue(':search_query_address', (string) $search_query.'%');
}
// Get number of rows after filter
$stmt->execute();
$total = $stmt->rowCount();
$sql .=" LIMIT :start, :limit_num";
$stmt = $db->prepare($sql);
if(!empty($search_query)){
$stmt->bindValue(':search_query_location', (string) $search_query.'%');
$stmt->bindValue(':search_query_address', (string) $search_query.'%');
}
// Bind start and limit value
$stmt->bindValue(':start', (int) $start, PDO::PARAM_INT);
$stmt->bindValue(':limit_num', (int) $limit, PDO::PARAM_INT);
// Get filtered data
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
return array($total,$data);
WHY I NEED TO REPEAT BINDING FOR TWO SAME QUERIES ONE WITHOUT LIMITS TO WORK IS THERE ANY ELEGANT SOLUTION
Problem
The reason that you have to bind twice is that $pdo->prepare($sql) returns a PDOStatement which isn't editable after it's been set. So when you update it you have to overwrite it and start again... Obviously the new statement doesn't retain the old bound parameters.
If you think of it as an array that you add some data to and then overwrite with a new, blank, array... You then can't read the information from the original array because it doesn't exist in the new one:
$array = [];
$array[] = 1;
$array[] = 2;
$array[] = 3;
var_dump($array);
/*
Output...
Array
(
[0] => 1
[1] => 2
[2] => 3
)
*/
$array = [];
print_r($array);
/*
Output...
Array
(
)
*/
The difference is that PDOStatement is an object not an array. But it's functionally the same thing!
N.B.
While $pdo->rowCount() may return the number of results from a SELECT query it isn't guaranteed so usually it's best practice not to use it.
I wouldn't overwrite the variable with a new query anyway... Better to use a different variable name e.g. $countQuery and $dataQuery
Solutions
So, if the only reason is that you're trying to reduce the amount of code then there are a bunch of solutions that you could use. However, this doesn't appear to be code golf, so why does it matter?
Solution 1
Assuming you don't have an unreasonable amount of unneeded results returned by the query then you could just return the array from the first query and use array_slice to take the place of the second query...
$pdo = $this->openConnection();
$sql = "SELECT * FROM contacts";
if($search_query){
$sql .= " WHERE ( location LIKE :search_query_location OR address LIKE :search_query_address ) ";
}
$sql .= " ORDER BY :order";
$query = $pdo->prepare($sql);
if($search_query){
$query->bindValue(':search_query_location', $search_query.'%');
$query->bindValue(':search_query_address', $search_query.'%');
}
$query->bindValue(':order', $order);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$count = count($result);
return [$count, array_slice($result, $start, $limit)];
Solution 2
If you're worried about readability and code maintenance then you should remember that: it's usual for a method/function to have a reasonably specific function, for example...
Return the number of rows which match a query
Return the data which matches a query
Implementing this would mean you have each of your queries in separate functions:
function countContacts(...)
{
$sql = 'SELECT count(*) FROM contacts WHERE ...';
$query = $pdo->prepare($sql);
$query->bindValue(...);
$query->execute();
return $query->fetchColumn();
}
function getContacts(...)
{
$sql = 'SELECT * FROM contacts WHERE ... ORDER BY ... LIMIT ...';
$query = $pdo->prepare($sql);
$query->bindValue(...);
$query->execute();
return $result->fetchAll(PDO::FETCH_ASSOC);
}
Solution 3
I wouldn't use this, but it technically solves the issue
You could use a union and run two queries in one, then you could use emulated prepared statements (as per #Straberry's answer) to bind once...
Although, again, emulated prepared statements are not something that anyone on here is likely to suggest you should use without good reason. Of course you could use normal prepares and use different bind parameter names.
Either way, this isn't a great solution. I wouldn't use it.
$sql = "
SELECT COUNT(*) as col1, null as col2, null as col3, null as col4, null as col5 FROM contacts WHERE ...
UNTION
SELECT col1, col2, col3, col4, col5 FROM contacts WHERE ... ORDER BY ... LIMIT ...
";
$query = $pdo->prepare($sql);
$query->bindValue(...);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
return [$result[0]["col1"], array_slice($result, 1)];

How to make a PDO class method for inserting/updating/deleting with an unknown number of parameters in the arg

Currently Im trying to create a PDO class where I will have a method to run a query like INSERT, UPDATE, or DELETE.
For examaple this is my method for a SELECT
public function getPreparedQuery($sql){
$stmt = $this->dbc->prepare($sql);
$stmt->execute([5]);
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(!$arr) exit('No rows');
$stmt = null;
return $arr;
}
And i Simply call it like this:
$stmt = $database->getPreparedQuery($sql2);
var_export($stmt);
And so far I know that a runQuery should work something similar to this:
Insert Example without using a method:
$idRol = "6";
$nomRol = "test6";
$stmt = $database->dbc->prepare("insert into roles (idRol, NomRol) values (?, ?)");
$stmt->execute(array($idRol,$nomRol));
$stmt = null;
But I want to make it into an universal method where i simply can pass the sql sentence, something like this:
$database->runQuery($query);
but the query can happen to be
$query = "INSERT INTO roles (idRol, NomRol) VALUES ('4','test')";
or
$query = "INSERT INTO movies (movName, movLength, movArg) VALUES ('name1','15','movie about...')";
So how do I slice the arg $query so I can get all the variables that are being used in order to make an universal runQuery?
Because I can imagine that my method should be something like this
runQuery([$var1 , $var2, $var3....(there can be more)] , [$var1value, $var2value, $var3value...(there can be more)]){
$stmt = $database->dbc->prepare("insert into movies($var1 , $var2, $var3....(there can be more)) values (?, ? , ? (those are the values and there ca be more than 3)"); //how do i get those "?" value and amount of them, and the name of the table fields [movName, movLength, movArg can be variable depending of the sentence]?
$stmt->execute(array($var1,$var2, $var3, ...)); //this is wrong , i dont know how to execute it
$stmt = null;
}
You need to add a second parameter to your function. Simply an array where all those variables would go. An array by definition can have an arbitrary number of elements, which solves your problem exactly:
public function runQuery($sql, $parameters = []) {
$stmt = $this->dbc->prepare($sql);
$stmt->execute($parameters);
return $stmt;
}
this simple function will run ANY query. You can see the usage example in my article dedicated to PDO helper functions:
// getting the number of rows in the table
$count = $db->runQuery("SELECT count(*) FROM users")->fetchColumn();
// the user data based on email
$user = $db->runQuery("SELECT * FROM users WHERE email=?", [$email])->fetch();
// getting many rows from the table
$data = $db->runQuery("SELECT * FROM users WHERE salary > ?", [$salary])->fetchAll();
// getting the number of affected rows from DELETE/UPDATE/INSERT
$deleted = $db->runQuery("DELETE FROM users WHERE id=?", [$id])->rowCount();
// insert
$db->runQuery("INSERT INTO users VALUES (null, ?,?,?)", [$name, $email, $password]);
// named placeholders are also welcome though I find them a bit too verbose
$db->runQuery("UPDATE users SET name=:name WHERE id=:id", ['id'=>$id, 'name'=>$name]);
// using a sophisticated fetch mode, indexing the returned array by id
$indexed = $db->runQuery("SELECT id, name FROM users")->fetchAll(PDO::FETCH_KEY_PAIR);
As you can see, now your function can be used with any query with any number of parameters

Possible to have PHP MYSQL query ignore empty variable in WHERE clause?

Not sure how I can do this. Basically I have variables that are populated with a combobox and then passed on to form the filters for a MQSQL query via the where clause. What I need to do is allow the combo box to be left empty by the user and then have that variable ignored in the where clause. Is this possible?
i.e., from this code. Assume that the combobox that populates $value1 is left empty, is there any way to have this ignored and only the 2nd filter applied.
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND location = '$value1' AND english_name = $value2 ";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Thanks for any help.
C
Use
$where = "WHERE user_id = '$username'";
if(!empty($value1)){
$where .= "and location = '$value1'";
}
if(!empty($value2 )){
$where .= "and english_name= '$value2 '";
}
$query = "SELECT * FROM moth_sightings $where";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Several other answers mention the risk of SQL injection, and a couple explicitly mention using prepared statements, but none of them explicitly show how you might do that, which might be a big ask for a beginner.
My current preferred method of solving this problem uses a MySQL "IF" statement to check whether the parameter in question is null/empty/0 (depending on type). If it is empty, then it compares the field value against itself ( WHERE field1=field1 always returns true). If the parameter is not empty/null/zero, the field value is compared against the parameter.
So here's an example using MySQLi prepared statements (assuming $mysqli is an already-instantiated mysqli object):
$sql = "SELECT *
FROM moth_sightings
WHERE user_id = ?
AND location = IF(? = '', location, ?)
AND english_name = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ssss', $username, $value1, $value1, $value2);
$stmt->execute();
(I'm assuming that $value2 is a string based on the field name, despite the lack of quotes in OP's example SQL.)
There is no way in MySQLi to bind the same parameter to multiple placeholders within the statement, so we have to explicitly bind $value1 twice. The advantage that MySQLi has in this case is the explicit typing of the parameter - if we pass in $value1 as a string, we know that we need to compare it against the empty string ''. If $value1 were an integer value, we could explicitly declare that like so:
$stmt->bind_param('siis', $username, $value1, $value1, $value2);
and compare it against 0 instead.
Here is a PDO example using named parameters, because I think they result in much more readable code with less counting:
$sql = "SELECT *
FROM moth_sightings
WHERE user_id = :user_id
AND location = IF(:location_id = '', location, :location_id)
AND english_name = :name";
$stmt = $pdo->prepare($sql);
$params = [
':user_id' => $username,
':location_id' => $value1,
':name' => $value2
];
$stmt->execute($params);
Note that with PDO named parameters, we can refer to :location_id multiple times in the query while only having to bind it once.
if ( isset($value1) )
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND location = '$value1' AND english_name = $value2 ";
else
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND english_name = $value2 ";
But, you can also make a function to return the query based on the inputs you have.
And also don't forget to escape your $values before generating the query.
1.) don't use the simply mysql php extension, use either the advanced mysqli extension or the much safer PDO / MDB2 wrappers.
2.) don't specify the full statement like that (apart from that you dont even encode and escape the values given...). Instead use something like this:
sprintf("SELECT * FROM moth_sightings WHERE 1=1 AND %s", ...);
Then fill that raw query using an array holding all values you actually get from your form:
$clause=array(
'user_id="'.$username.'"',
'location="'.$value1.'"',
'english_name="'.$value2.'"'
);
You can manipulate this array in any way, for example testing for empty values or whatever. Now just implode the array to complete the raw question from above:
sprintf("SELECT * FROM moth_sightings WHERE 1=1 AND %s",
implode(' AND ', $clause) );
Big advantage: even if the clause array is completely empty the query syntax is valid.
First, please read about SQL Injections.
Second, $r = mysql_numrows($result) should be $r = mysql_num_rows($result);
You can use IF in MySQL, something like this:
SELECT * FROM moth_sightings WHERE user_id = '$username' AND IF('$value1'!='',location = '$value1',1) AND IF('$value2'!='',english_name = '$value2',1); -- BUT PLEASE READ ABOUT SQL Injections. Your code is not safe.
Sure,
$sql = "";
if(!empty($value1))
$sql = "AND location = '{$value1}' ";
if(!empty($value2))
$sql .= "AND english_name = '{$value2}'";
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' {$sql} ";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Be aware of sql injection and deprecation of mysql_*, use mysqli or PDO instead
I thought of two other ways to solve this:
SELECT * FROM moth_sightings
WHERE
user_id = '$username'
AND location = '%$value1%'
AND english_name = $value2 ";
This will return results only for this user_id, where the location field contains $value1. If $value1 is empty, this will still return all rows for this user_id, blank or not.
OR
SELECT * FROM moth_sightings
WHERE
user_id = '$username'
AND (location = '$value1' OR location IS NULL OR location = '')
AND english_name = $value2 ";
This will give you all rows for this user_id that have $value1 for location or have blank values.

Categories