I have two update queries with different where statements.
Is it possible to do the job with a single one?
$sql = "update users set light = replace(light, '" . $clicked . ",', '') where userid = :aid";
$st = $db->prepare($sql);
$st->execute([":aid" => $_SESSION['userid']]);
$sql = "update users set seen = 'seen' where userid = :aid and xfrom = :axfrom";
$st = $db->prepare($sql);
$st->execute([
":axfrom" => $clicked,
":aid" => $_SESSION['userid']
]);
You could do this in a single update with the help of a CASE expression:
UPDATE users
SET
light = REPLACE(light, ?, ''),
seen = CASE WHEN xfrom = :axfrom THEN 'seen' ELSE seen END
WHERE userid = :aid
Both your updates share a portion of the same WHERE logic, so we can leave that WHERE clause as is. For updating the seen column, we only make a change if the xfrom condition matches, otherwise we no-op.
Not sure if you should also be using a placeholder in the call to REPLACE, but other than this it is good that you are using prepared statements.
Related
I am writing php to update a user's balance, but my UPDATE query seems to be throwing an error when it is executed.
$student = $database->quote($_POST ["studentID"]);
$amount = $database->quote($_POST ["update_balance"]);
//sets query to update user balance
$query = "UPDATE `User` SET `balance`= (`.$amount.`) WHERE `userID`= (`.$student.`)";
//excecutes the query
$database->exec($query);
The 'studentID' and 'update_balance' are names of input fields being captured in the HTML.
remove (`. things . and run sql query
$query = "UPDATE `User` SET `balance`= '$amount' WHERE `userID`= '$student'";
You should use prepared statements as it's considered much safer than any string escaping mechanism:
$statement = $somePdoInstance->prepare("UPDATE user SET balance = :balance WHERE userId = :user_id");
$statement->execute(array(
"balance" => $amount, // the values from POST
"user_id" => $student
));
Now your update query should work fine and it's much safer.
I want to know, can I just use prepared statements one time?
Here is my script:
$stm = $db->prepare("UPDATE
qanda AS ans1
JOIN qanda AS ans2 ON ans2.related = ans1.related
JOIN qanda AS ques ON ans2.related = ques.id
SET ans1.acceptedanswer = 1,
ans1.aadate = IF( ans1.id <> ?, ans1.aadate, ?)
WHERE ques.author_id = ? AND ans2.author_id = ?
");
$stm->execute(array($answer_id, time(), $_SESSION["Id"], $author_id));
$done = $stm->rowCount();
if ($done){
/* I don't use prepared statement here */
$stm1 = $db->prepare("UPDATE user SET rep = rep + 15 WHERE id = $author_id");
$stm1->execute();
}
As you see I didn't use prepared statement for second query. Because I did it for first query and if first query is working then I'm sure arguments are valid and don't need to bind them by prepared statement.
Please don't ask me why you don't want to use prepared statemen't for second query, because the reason is too long.
So what I'm doing is correct? Isn't there any security problem?
The straight answer is: yes, you can.
The reason why is actually up to you, since it's anyway good practice to use prepared statement whenever you pass values.
Also consider that, if you are not binding any parameter, it makes more sense to use the query() method, just to be explicit on the fact that you are not going to bind anything. So your second query would be
$stm1 = $db->query("UPDATE user SET rep = rep + 15 WHERE id = $author_id");
(see http://php.net/manual/en/pdo.query.php)
instead of
$stm1 = $db->prepare("UPDATE user SET rep = rep + 15 WHERE id = $author_id");
$stm1->execute();
Moreover you mentioned a dynamic query, but this is not the case of your sample code. Anyway I will give you an example of how two use prepared statement also on queries dynamically generated.
It's a silly example, but should be enough to give you an idea.
Assume we have some values to update 'email', 'date_of_birth' and 'website'. Let's say we want to do some check on this data before inserting them. I'll pretend we have a valid() function already in place.
$dynamic_sql = array();
$parameters[':date_of_bird'] = $date_of_birth;
if(valid($email)) {
$dynamic_sql['email_sql'] = "email = :email";
$parameters[':email'] = $email;
}
if(valid($website)) {
$dynamic_sql['website_sql'] = "website = :website";
$parameters[':website'] = $website;
}
if(count($dynamic_sql)>0) {
$dynamic_sql = ','.implode($dynamic_sql);
}
$query = "UPDATE user
SET date_of_birth = :date_of_birth $dynamic_sql
WHERE
user_id = :user_id";
$stm = $db->prepare($query);
$stm->execute($parameters);
This kind of approach will allow you to keep using prepared statement also with dynamically generated SQL.
I have the following query
$products = $this->mysqliengine->query("select * from temp_all_product where download_status = 0") or die($this->mysqliengine->error());
$temp_status_update = $this->mysqliengine->prepare("update temp_all_product set download_status = ? where id = ?") or die($this->mysqliengine->error);
$temp_status_update->bind_result($download_status, $id);
while($product = $products->fetch_assoc()) {
$id = $product['id'];
$download_status = 1;
$temp_status_update->execute();
}
In the above statement I can select the values from temp table but unable to update the status. What is the problem here
You need to use bind_param in your update statement instead of bind_result.
$temp_status_update->bind_param('dd', $download_status, $id);
The 'dd' just tells the system that each input is a number.
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
#eggyal was merely suggesting that you could replace all your code with a single update statement. Your remark about LIMIT does not make much sense.
Suggestion: If you don't have much invested in mysqli then switch to PDO. It allows using named parameters which can make your code more robust and easier to maintain:
$sql = "UPDATE temp_all_product SET download_status = :status where id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(array('status' => 1, 'id' => $product['id']));
Plus you can configure it to throw exceptions so you don't need all this error checking.
http://www.php.net/manual/en/book.pdo.php
http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/
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.
I want to execute a parameterized query to perform a search by user-supplied parameters. There are quite a few parameters and not all of them are going to be supplied all the time. How can I make a standard query that specifies all possible parameters, but ignore some of these parameters if the user didn't choose a meaningful parameter value?
Here's an imaginary example to illustrate what I'm going for
$sql = 'SELECT * FROM people WHERE first_name = :first_name AND last_name = :last_name AND age = :age AND sex = :sex';
$query = $db->prepare($sql);
$query->execute(array(':first_name' => 'John', ':age' => '27');
Obviously, this will not work because the number of provided parameters does not match the number of expected parameters. Do I have to craft the query every time with only the specified parameters being included in the WHERE clause, or is there a way to get some of these parameters to be ignored or always return true when checked?
SELECT * FROM people
WHERE (first_name = :first_name or :first_name is null)
AND (last_name = :last_name or :last_name is null)
AND (age = :age or :age is null)
AND (sex = :sex or :sex is null)
When passing parameters, supply null for the ones you don't need.
Note that to be able to run a query this way, emulation mode for PDO have to be turned ON
First, start by changing your $sql string to simply:
$sql = 'SELECT * FROM people WHERE 1 = 1';
The WHERE 1 = 1 will allow you to not include any additional parameters...
Next, selectively concatenate to your $sql string any additional parameter that has a meaningful value:
$sql .= ' AND first_name = :first_name'
$sql .= ' AND age = :age'
Your $sql string now only contains the parameters that you plan on providing, so you can proceed as before:
$query = $db->prepare($sql);
$query->execute(array(':first_name' => 'John', ':age' => '27');
If you can't solve your problem by changing your query... There are several libraries that help with assembling queries. I've used Zend_Db_Select in the past but every framework likely has something similar:
$select = new Zend_Db_Select;
$select->from('people');
if (!empty($lastName)) {
$select->where('lastname = ?', $lastname);
}
$select->order('lastname desc')->limit(10);
echo $select; // SELECT * FROM people WHERE lastname = '...' ORDER BY lastname desc LIMIT 10
I've tested the solution given by #juergen but it gives a PDOException since number of bound variables does not match. The following (not so elegant) code works regardless of no of parameters:
function searchPeople( $inputArr )
{
$allowed = array(':first_name'=>'first_name', ':last_name'=>'last_name', ':age'=>'age', ':sex'=>'sex');
$sql = 'SELECT * FROM sf_guard_user WHERE 1 = 1';
foreach($allowed AS $key => $val)
{
if( array_key_exists( $key, $inputArr ) ){
$sql .= ' AND '. $val .' = '. $key;
}
}
$query = $db->prepare( $sql );
$query->execute( $inputArr );
return $query->fetchAll();
}
Usage:
$result = searchPeople(array(':first_name' => 'John', ':age' => '27'));