how should i update my attempt's using variable ? it wont work
mycode
$db_attempts = 'MAX_ATTEMPTS';
//here
$attemtps_pdo = 'UPDATE `attempts` SET `MAX_ATTEMPTS`= ? +1 WHERE `IP` = ?';
$results = $ALIST->update($attemtps_pdo,$db_attempts,$user_ip);
public function update($sql,$values1,$values2){
try{
$results = $this->connection->prepare($sql);
$results->bindValue(1, $values1);
$results->bindValue(2, $values2);
$results->execute();
return $results;
}
how do i make my MAX_ATTEMPTS +1 to variable , if i do it with my code , the update only update once , once is == 1 it wont update anymore why?
but if i using
$attemtps_pdo = 'UPDATE `attempts` SET `MAX_ATTEMPTS`= `MAX_ATTEMPTS` +1 WHERE `IP` = ?';
it work perfectly.
Because you are not referencing the MAX_ATTEMPTS column when you BIND the variable $db_attempts into your SQL query. Binding prevents stuff like this, because it could potentially lead to SQL injection.
In other words, your second example IS the correct way of doing this. If you want this to be dynamic (eg. if $db_attempts can change), then you have to build the query using string concatenation.
Alternative solutions:
Assuming it will always update by 1 every time the sql gets executed and assuming $value1 is the value currently in the database for MAX_ATTEMPTS.
What I would suggest is to it when you bind the parameters:
$results->bindValue(2, (int)$values1 + 1);
Your sql will be:
$attemtps_pdo = 'UPDATE `attempts` SET `MAX_ATTEMPTS`= ? WHERE `IP` = ?';
OR
Add a database query to find the latest value of MAX_ATTEMPTS and pass it as $value1 which realizes the assumption made in the previous solution.
Just try the incrementation :
UPDATE attempts SET MAX_ATTEMPTS++ WHERE IP = ?
Related
i have an c++ program that sending POST of logs to my server and store it on database, the problem is that the checking of duplicates before insert a new row is not working, i think that the program send the POST very fast and there is no delay between the POSTS to the server so the Mysqli can't handle this, is there any solution from server client? maybe locking rows or something?
$date = date('Y-m-d', time());
$prep_select_qa = 'SELECT * from `logs` WHERE `guid` = ? AND `error_code` = ? AND `date_create` = ?';
$select_qa = $db->prepare($prep_select_qa);
$select_qa->bind_param('sss', $_POST['guid'], $_POST['error_code'], $date);
$select_qa->execute();
$select_qa->store_result();
$num_rows = $select_qa->num_rows;
if($num_rows == 0)
{
$prep_insert_qa = 'INSERT INTO `logs` (`type`, `guid`, `sent_by`, `class_and_method`, `api_method`, `error_code`, `error_text`, `date_create`) VALUES (?,?,?,?,?,?,?,?)';
$insert_qa = $db->prepare($prep_insert_qa);
$insert_qa->bind_param('ssssssss', $new, $_POST['guid'], $_POST['sentBy'], $_POST['classAndMethodName'], $_POST['APImethod'], $_POST['ErrorCode'], $_POST['ErrorText'], $date);
$insert_qa->execute();
$insert_qa->store_result();
}
First, the answer to your question is that you are retrieving all the rows in order to count them. Presumably, this requires reading all the data in the table and returning some of it (unless you have indexes). A faster method is to check the value returned by this query:
SELECT count(*)
FROM `logs`
WHERE `guid` = ? AND `error_code` = ? AND `date_create` = ?';
And an even faster method is not to count but to determine if any row exists:
SELECT EXISTS (SELECT 1
FROM `logs`
WHERE `guid` = ? AND `error_code` = ? AND `date_create` = ?'
)
This will return 1 if the row exists and 0 otherwise. Both of the above queries and your original query will benefit from having an index on guid, error_code, date_create.
In practice, you should follow Marvin's advice and use a unique index. This means the database does the checking via a unique index rather than the application. One very important reason is a race condition. If two users are inserting the same row at the same time, both might execute the if statement, find there are no matching rows in the table, and then insert duplicate rows.
The SELECT scheme must be enclosed in a BEGIN...COMMIT transaction and have FOR UPDATE on it. Otherwise, some other connection can slip in and defeat your check.
Instead, try to do it in a single, atomic, instruction:
Once you have an INDEX that will prevent duplicates...
INSERT IGNORE -- Silently does nothing if it is a dup.
INSERT...ON DUPLICATE KEY UPDATE -- Lets you change something as you try to insert a dup.
Also, the INSERT solutions will be faster (which was your original question).
I am wondering if mysqli works when binding a column reference +1 type of field. Example.
UPDATE `table` SET `sys-helpful-yes` = `sys-helpful-yes`+1 WHERE `id` = 1;
When using mysqli bind parameters, it doesn't add the one.
UPDATE `table` SET `sys-helpful-yes` = ? WHERE `id` = 1;
I am trying to bind
`sys-helpful-yes`+1
Wondering if anyone has a workaround.
What about
UPDATE `table` SET `sys-helpful-yes` = `sys-helpful-yes`+ ? WHERE `id` = 1;
and then, of course, only bind 1 ...
(not tested) ?
I have a query (insecure for the minute) that attempts to set a value of a column to NULL. Basically just revert it to being empty. 'Allow NULL' is checked in the Database design. Its an MSSQL Database. First of all I tried:
$query = "UPDATE Table_Name SET Image = '', Thumb = '' WHERE PageID = 5";
Then:
$query = "UPDATE Table_Name SET Image = NULL, Thumb = NULL WHERE PageID = 5";
The second one produces no errors, but does not set the database value to NULL. From what I can see though (website research) 'NULL' is correct? Sorry, new to PHP.
EDIT
The query is called by an if statement. That checks to see if a GET value is equal to. I am aware that this isn't very secure. I am just trying to test/play a little with techniques. The full call and query are as follows.
<?php
if (isset($_GET['change']) && $_GET['change'] == "image1") {
$query = "UPDATE Table_Name SET Image = NULL, Thumb = NULL WHERE NewsID = ".$_GET['id']." ";
}
?>
This if statement is triggered a delete 'button'. The code looks like:
delete</td>
I now believe, the query isn't getting called? However the button does change and set the values it is meant to do, so all I can assume, is that the if statement doesn't pick up on this. Update.php is the page the queries are currently on so it almost just acts as a refresh.
I haven't used PHP in a very long time, but does NULL need to be enclosed in quotes?
Try this:
$query = "UPDATE Table_Name SET Image = 'NULL', Thumb = 'NULL' WHERE PageID = 5";
Hope this helps.
So I am trying to change the status of something when values are met using WHERE
Code:
$insertstatus = $DBH->prepare("INSERT INTO
csvdata (status) VALUES ('$status') WHERE username = '".$username."'");
$insertstatus->execute();
Not working. If you could give me a hand.
Thank you for your time!
If you want to use the where clause, you need to use update. From the looks of it, you are trying to update anyhow as you are only using one column from your table.
$insertstatus = $DBH->prepare("update
csvdata set status= '$status' WHERE username = '".$username."'");
$insertstatus->execute();
As PeeHaa correctly points out though, using a prepared statement with parameters would be a slight change in your code, and a better option for you. You can do it like this:
$sql="update csvdata set status=:status where username=:username";
$sth=$DBH->prepare($sql);
$sth->execute(array(':status' => $status, ':username' => $username));
This way you are preparing the statement so the database knows what will happen. You then pass the variables to the database via the execute() function in an array.
How can I increment an int in a cell of a MySQL database? I know that auto-increment is no use because I never want to add a new row, just update an existing one. I'm currently using this (POST var used for clarify, is verified in the real code):
$columnToUpdate = 'type'.$_POST['voteid'];
$query = "UPDATE myTable $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
if(!mysql_query($query)) {
echo json_encode(array('success' => false, 'message' => 'Update failed: '.mysql_error()));
exit;
}
In the database I have 6 fields, id, type1, type2, type3, type4, type5, and a single row with id set to 1. The intention is to recieve a number (1-5), and build a reference to the correct column before updating the field. That results in Update failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=type4+1 WHERE id=1' at line 1, so I guess it's not getting the field value out properly before it increments.
Once this is working I'm also going to need to decrement a field in the same way, unless its value is 0. So for bonus points, can I do all this in one query or would it be better to split it up?
I think you've missed the keyword 'SET' from your query - try
$query = "UPDATE myTable SET $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
Edit:
To do the "decrement unless it's zero" you could use something like:
UPDATE myTable SET $columnToUpdate =
CASE $columnToUpdate
WHEN 0 THEN 0
ELSE $columnToUpdate - 1
END CASE
WHERE id=1;`
For bonus points, to decrement:
$query = "UPDATE myTable SET '$columnToUpdate' = '$columnToUpdate'-1 WHERE id=1 AND '$columnToUpdate' > 0";
Besides the injection issues, it seems as if your workflow may need some work. Are you sure you want to choose the column that will be updated based on POST variable? It seems like you would specify the column and use the variable to find the record that needs to be updated:
IE:
"UPDATE myTable SET votes=votes+1 WHERE id=$post_variable;"
Again you should send the variable as a parameterized query to protect yourself from SQL injection.