i want to combine a SELECT and UPDATE query, to avoid duplicat select of rows.
Here is my example code:
private function getNewRCode() {
$getrcodesql = "SELECT * FROM `{$this->mysqlprefix}codes` WHERE `used` = 0 LIMIT 1;";
$getrcodequery = $this->mysqlconn->query($getrcodesql);
if(#$getrcodequery->num_rows > 0){
$rcode = $getrcodequery->fetch_array();
$updatercodesql = "UPDATE `{$this->mysqlprefix}codes` SET `used` = '1' WHERE `id` = {$rcode['id']};";
$this->mysqlconn->query($updatercodesql);
$updateusersql = "UPDATE `{$this->mysqlprefix}users` SET `used_codes` = `used_codes`+1, `last_code` = '{$rcode['code']}', `last_code_date` = NOW() WHERE `uid` = {$this->uid};";
$this->mysqlconn->query($updateusersql);
$output = array('code' => $rcode['code'],
'time' => time() + 60*60*$this->houroffset,
'now' => time()
);
return $output;
}
}
I would like to execute $getrcodesql and $updatercodesql at once, to avoid that the same code is used for different users.
I hope you understand my problem and know a solution for this.
Greetings,
Frederick
It's easier if you do it the other way round.
The point is that that your client can generate a unique value before you do the UPDATE and SELECT.
Change the type of your used column to something else, so that you can store a GUID or a timestamp in it, and not just 0 and 1.
(I'm not a PHP/MySQL expert, so you probably know better than me what exactly to use)
Then you can do this (in pseudocode):
// create unique GUID (I don't know how to do this in PHP, but you probably do)
$guid = Create_Guid_In_PHP();
// update one row and set the GUID that you just created
update codes
set used = '$guid'
where id in
(
select id
from codes
where used = ''
limit 1
);
// now you can be sure that no one else selected the row with "your" GUID
select *
from codes
where used = '$guid'
// do your stuff with the selected row
Related
I created a new column in mysql, that is going to store a unique value for all of the elements inside the database.
Now I would like to populate all rows with this unique value using uniqid().
But since the function makes use of microtime(), I can't update all rows together.
How could I do it?
$unique_id = uniqid();
$sql = "UPDATE posts SET unique_id = :unique_id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['unique_id' => $unique_id]);
This code updates the same value for all rows.
How can every row be unique?
try with below code
SET #r := 0;
UPDATE posts
SET unique_id = (#r := #r + 1)
ORDER BY RAND();
Try this ,
update posts set unique_id = #i:=#i+1 order by rand();
The numbers will now randomly assigned to rows, but each row has a unique value.
uniqid('', TRUE),
You can use uniqid with the entropy to make it more sensitive in time to narrow down even more the chance of duplicates but keep one thing in mind:
This function does not guarantee uniqueness of return value. Since
most systems adjust system clock by NTP or like, system time is
changed constantly. Therefore, it is possible that this function does
not return unique ID for the process/thread. Use more_entropy to
increase likelihood of uniqueness.
What you can do as well is to put a random prefix like:
uniqid(mt_rand(), TRUE);
That will eliminate every chance to generate a duplicate.
You are going to use a random prefix + entropy sensitivity. The generated value will be unique even if your script runs that fast that the timestamp happens to be the same even in miliseconds.
The problem with your code is that you use uniqid() function one time by assigning it to a variable and from there you get duplicates of course cause you use this variable:
Try this code:
$sql = "UPDATE posts SET unique_id = uuid()";
$stmt = $pdo->prepare($sql);
$stmt->execute();
So after some tries I came across my own solution, using uniqid().
Here's my code, commented:
// Selecting all the posts
$sql = "SELECT id, pro_key FROM posts";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$posts = $stmt->fetchAll();
// Looping through all the results and updating them one by one with a delay of 1 second between the updates
foreach($posts as $post) {
$sql = "UPDATE posts SET unique_id = :unique_id WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => $post->id, 'unique_id' => uniqid()]);
// delay
sleep(1);
}
Hope this helps.
code:
<?php
$this->db->select('*');
$this->db->from('bugs');
$where = "project_name = '".$project."'";
$this->db->where($where);
$sql = $this->db->get();
$res = $sql->num_rows();
if($res === 0)
{
$i = 1;
foreach ($bug as $row)
{
echo $i;
}
}
else
{
$i = 1;
foreach ($bug as $row)
{
echo ++$i;
}
}
?>
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
In this code I have a table name bugs where I have a column i.e. bug_id. Now, I want to insert data into my table if table row having no value it insert bug_id = 1 and after that insert 2 and then 3 and so on. But now when I click on submit button it insert bug_id = 1 and then 2 but when I click on third it insert again bug_id 2 . So, How can I fix this problem?Please help me.
Thank You
MySQL has integrated AUTO_INCREMENT. Either you log into phpMyAdmin and change the properties of your bug_id field by clicking on edit, then selecting the "A_I" field.
Or you can do it with a SQL query:
ALTER TABLE YOUR_TABLE MODIFY bug_id INTEGER NOT NULL AUTO_INCREMENT;
If #Twinfriends answer doesn't fit your needs (but that should be the correct way to do that, you shouldn't reinvent the wheel) then maybe the problem is with your:
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
Since you are actually using $this->input->post('bug_id') as your new id, maybe you want to use something else?
Where does your $bug var come from? To be sure of not getting duplicated ids or wrong one you could add to your MySql query something like "ORDER BY bug_id DESC LIMIT 1" (so that you take 1 row as result with the highest bug_id) and then just use that result + 1 as the new id
I updated with success
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
but how can I get the "queue2" value without opening a new request to MySQL
I can simply get the new value with this command
$selresult = mysql_query("SELECT * FROM $table WHERE `id` = '$getid'") or die(mysql_error());
but I'm afraid that the database can get new update again and i will get higher number
Any idea how to do it ?
you can use query to update the value.
mysql_query("UPDATE user_profile SET userpoints = userpoints + 1 WHERE user_id = '".$user_id."'");
See URL:-
PHP + MySQL transactions examples
Try this:-
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
You will need to use a transaction between the queries to be certain.
The docs for transactions are here. A good SO question that covers it in detail: PHP + MySQL transactions examples
Edit:
Looking at it from a different angle, why don't you do it in reverse though? It might save the need for a transaction (thought it is possible that you get multiple reads before a write):
Get the value for your queue2 value to display in the page from this:
mysql_query("SELECT * FROM $table WHERE `id` = '$getid'");
You have the true value now, so you can run:
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
No transaction and you know the value of the data before the update.
I have a datatable with user information and a column called 'Bits'. There is a transfer function and I would like to transfer x amount of bits from the logged in user to the user they specify. I have the following function that works, but I would like to know if there is a better (simpler, cleaner, quicker?) way to do all of this, and possibly return the row of the first SQL statement at the end. I am not an advanced MySQL user by any means, but I am pretty sure there is a function I am missing that could make this much easier.
function transferBits($toid, $amount)
{
global $loggedInUser, $db;
$fromid = $loggedInUser->user_id;
$sql = "INSERT INTO `dl_Transfers` SET From_ID = '".$db->sql_escape($fromid)."',
`To_ID`='".$db->sql_escape($toid)."',
`Bits`='".$db->sql_escape($amount)."',
`When`=Now()";
$result = $db->sql_query($sql);
$sql2 = "UPDATE `dl_Users` SET Bits = Bits - '".$db->sql_escape($amount)."' WHERE `User_ID` = '".$db->sql_escape($fromid)."'";
$result2 = $db->sql_query($sql2);
$sql3 = "UPDATE `dl_Users` SET Bits = Bits + '".$db->sql_escape($amount)."' WHERE `User_ID` = '".$db->sql_escape($toid)."'";
$result3 = $db->sql_query($sql3);
}
I think you could hit the update in single query by joining on the previous record id from your insert on dl_Transfers:
UPDATE `dl_Transfers` r
JOIN `dl_Users` f ON ( r.From_ID = f.User_ID )
JOIN `dl_Users` t ON ( r.To_ID = t.User_ID )
SET f.Bits = f.Bits - r.Bits, t.Bits = t.Bits + r.Bits
WHERE r.Transfer_ID = ?;
Also as others stated in their comments, you should definitely use transactions here.
You might consider using a MySQL trigger to handle this. Basically, you would set it up so anytime there is an insert on dl_Transfers, it updates the appropriate rows in dl_Users.
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Hey, I have a field called STATUS and it is either 1 to show or 0 to hide. My code is below. I am using an edit in place editor with jQuery. Everytime you update it creates a new ROW which I want, but I want only the new one to have STATUS = 1 and the others to 0. Any ideas on how I would do that?
<?php
include "../../inc/config.inc.php";
$temp = explode("_", $_REQUEST['element_id'] );
$field = $temp[0];
$id = $temp[1];
$textboxval = stripslashes(mysql_real_escape_string(preg_replace('/[\$]/',"",$_REQUEST["update_value"])));
$query = "INSERT INTO notes ($field,status,date,c_id) VALUES ('$textboxval','1',NOW(),'$id')";
mysql_query($query);
echo($_REQUEST['update_value']);
?>
I am not sure exactly what you mean - do you want to make all the entries except the new one have status = 0? If so, just issue an update before the insert:
UPDATE notes SET status = 0
However, I should also note that you have a potential SQL injection to worry about. By stripping slashes after applying "mysql real escape string", you are potentially allowing someone to put text in your SQL statement that will execute an arbitrary SQL statement.
Something like this, sorry for the post before, I mis read it the first time then went back:
<?php
include "../../inc/config.inc.php";
$temp = explode("_", $_REQUEST['element_id'] );
$field = $temp[0];
$id = $temp[1];
$textboxval = mysql_real_escape_stringstripslashes((preg_replace('/[\$]/',"",$_REQUEST["update_value"])));
// set older entries to 0 - to not show but show in history
$hide_notes = "UPDATE notes SET status = 0";
mysql_query($hide_notes);
// add new entry with status of 1 to show only latest note
$query = "INSERT INTO notes ($field,status,date,c_id) VALUES ('$textboxval','1',NOW(),'$id')";
mysql_query($query);
echo($_REQUEST['update_value']);
?>
i just ran in to a problem I didn't of the set up of my table doesn't allow me to show more than one client a time and i will be having numerous clients, my bad on planning ha
You really want to get the ID of the newly generated row and then trigger an UPDATE where you all rows where the ID is not the new row, e.g.
UPDATE notes SET status = 0 WHERE id != $newly_generated_id
If the ID column in your table is using AUTO_INCREMENT you can get its ID via "SELECT LAST_INSERT_ID()" and then use the return value in that statement in your UPDATE statement.
Pseudo code:
$insert = mysql_query("INSERT INTO ...");
$last_id = mysql_query("SELECT LAST_INSERT_ID()");
$update = mysql_quqery("UPDATE notes SET status = 0 WHERE id != $last_id");
The only caveat to this approach is where you might have a brief moment in time where 2 rows have status=1 (the time between your INSERT and the UPDATE). I would wrap all of this in a transaction to make the whole unit more atomic.