I'm working on a login module in php and facing some problem generating ids.
On the registration part, I need to generate an unique ID per user. I thought I'd be able to generate this ID by incrementing the last ID in the database by 1, but it doesn't seem to work.
Here's my code:
$user = $_POST['post_username'];
$pass = $_POST['post_password'];
function generateID(){
$aux = mysql_query("SELECT usr_id FROM users");
$i = 0;
$resulArray = mysql_fetch_row($aux) or die("Error fetching!");
$n = mysql_num_rows($aux);
$b = $resulArray[$i];
$c = $b;
for($i = 0; $i < $n; $i = $i +1){
$b = $resulArray[$i];
if($b >= $c) $c = $b;
}
return $c + 1;}
Here's my MySQL structure:
username -> String
password -> String
usr_id -> int
Don't do this. It's unreliable and cannot address race conditions. Just use an auto-increment primary key:
CREATE TABLE users
id unsigned int auto_increment primary key,
...
);
then
INSERT INTO users (id, ....) VALUES (null, ...)
and
$userID = mysql_last_insert_id();
This is inherently reliable, handles race conditions, and will guarantee unique ids for this table. You won't need any custom verification, just auto-increment the id field and let MySQL take care of the ids.
Related
I need some quick help, I need to know if I can somehow increment the $user_id by one so that I do not get a duplicate entry error. Do I just add a +1 after ['user_id']?
public function insert_video($video_id,$user_id,$caption) {
$userObject = array();
$userObject['user_id'] = $user_id;
$userObject['video_id'] = $video_id;
$userObject['caption'] = str_replace(array("'",'"'), '', $caption);
$userObject['description'] = '';
$userObject['votes'] = 0;
$userObject['upload_time'] = date('Y-m-d H:i:s');
$userObject['version'] = $this->contests->contest->version; //4
//if($this->contests->contest->auto_approve)
$userObject['approved'] = 1;
$this->db->insert('photos', $userObject);
return $this->db->insert_id();
ok guys I edited the function and removed any mention of user_id but for some reason I still get the error when I try to submit another video. Should I try dropping that column on the table? here is my updated function
public function insert_video($video_id,$caption) {
$userObject = array();
//$userObject['user_id'] = $user_id+1;
$userObject['video_id'] = $video_id;
$userObject['caption'] = str_replace(array("'",'"'), '', $caption);
$userObject['description'] = '';
$userObject['votes'] = 0;
$userObject['upload_time'] = date('Y-m-d H:i:s');
$userObject['version'] = $this->contests->contest->version; //4
//if($this->contests->contest->auto_approve)
$userObject['approved'] = 1;
$this->db->insert('photos', $userObject);
return $this->db->insert_id();
}
You need to set up your user_id To auto increment. If you find it easier as you clearly have a table already set up, use phpMyAdmin to set the AI tick box to true.
Then when you INSERT, you'll get a unique value. You do not need to specify the user_id as that'll be taken care of.
INSERT INTO users (FirstName,LastName) VALUES ('Matt','HB')
I suppose you need to have 2 tables, one that holds a user info with auto incresment column e.g. "ID".
In table photos don't use auto incresment for user_id, as you need to give users ability to insert multiple photos and update current. just change in your table:
`user_id` to `ID` -> this will auto incresment
create new column `user_id` int 200.. this will be a reference of `column - "ID"` from **userinfo** table;
//then run your query:
INSERT INTO photos (user_id, video_id, caption, description, votes, upload_time, version, approved) VALUES (7339, 'fDTm1IzQf-U', 'new test', '', 0, '2014-11-12 16:17:36', '19', 1)
I am trying to get unique admission number for every student. So I am counting number of rows in database and displaying value in student admission number. But if I enter student details and after submission it will be saved in database and when I delete that and if I again want to enter the new student details its taking the same register number which i deleted .I want unique registration numbers. So please help me to get the unique numbers which should not be repeated.
You can use feature of AUTO_INCREMENT property of MySQL if you have numeric Registration number field.
You can create a column that is AUTO_INCREMENT or you can create a row that is UNIQUE and check before inserting
CREATE TABLE `reg` (
`reg_id` INT AUTO_INCREMENT
);
try this function this will give random number and also check if its gives a same number again call this function
$len = 5;
randID($len);
function randID($len) {
$index = "0123456789";
$out = "";
for ($t=0; $t<$len;$t++) {
$r = rand(0,61);
$out = $out . substr($index,$r,1);
}
return $out;
}
Auto increment is best way like following
CREATE TABLE tbl_name (
`reg_id` INT NOT NULL AUTO_INCREMENT ,
PRIMARY KEY ( `reg_id` )
);
Create a random id and set this in your db:
<?php
function RandStr($length, $encrypt = 10){
$reg_id = '';
for($i=0;$i<$encrypt;$i++){
$reg_id = base64_encode(md5(microtime(true)).$str);}
return substr($reg_id, 0, $length);
}
//Make the REG_ID
echo "REG_ID= ". RandStr(10);
?>
How can insert the unique row in mysql?
id and userid both are different column.
I have set id is unique.But userid and checkin column should not be repeated.
Is this possible?
if($this->dx_auth->is_logged_in()){
$insertData['userid'] = $this->dx_auth->get_user_id();
$insertData['checkin'] = $checkin;
$insertData['checkout'] = $checkout;
$insertData['location'] = $location;
$insertData['guest'] = $nof_guest;
$id = $this->dx_auth->get_user_id();
$result = $this->Common_model->getTableData('searchlist', array("userid" => $id));
if($result->num_rows > 4){
$res = $result->result();
$del_id = $res[0]->id;
$conditions = array("id" => $del_id);
$this->Common_model->deleteTableData('searchlist', $conditions);
}
if($location != "0"){
$this->Common_model->inserTableData('searchlist', $insertData);}}
You can keep your id as primary key and auto increment for your user table.
Then, you have to create combined unique key for userid and checkin.
CREATE UNIQUE INDEX user_checkin_time ON searchlist (userid, checkin);
In controller, you have to validate the userid and checkin before insert / update.
$isExist = $this->Common_model->getTableData('searchlist', array("userid" => $id,"checkin"=>$checkin));
if($isExist->num_rows()>0)
{
// throw error message as checkin time already exist
}
else
{
// continue with further code
}
In this case, you can really make the userid and checkin columns as a composite primary key. If you want you can still use id as the primary key and create a unique index for the 2 other columns combined.
You should probably also check if the record exists before you insert a new combination that would result in a MySQL error.
Cheers!
How can i check if a id exists in a mysql database, and if it does: create a new id and check over again. I have the following code to create a id:
$length = 10;
$id = '';
for ($i = 0; $i < $length; $i++) {
$id .= chr(rand(ord('0'), ord('9')));
}
To check if the id exists i use the code below:
$database->query('SELECT user_id FROM users
WHERE public_id = ':public_id',array(':public_id' => $public_id)');
if($database->count() >= '1') {
//create a new id
} else { }
What you're trying to do is not considered a "best practice", as (theoretically) you could create an infinite loop (creating a random ID, then checking for existence could "hit" on each iteration).
A better solution to create unique IDs is to set a column as your primary key, and increment upon each new insert.
If you want another column to be unique, you can define that column to be unique as well, but you won't have to rely on "random" strings.
How do I lock mysql tables in php? I currently have this code:
$db->query("LOCK TABLES tbl_othercharge WRITE");
for($x=0;$x<=500; $x++){
$id = get_max();
$db->query("INSERT INTO tbl_othercharge SET tblocID = '$id', assessmentID='lock1'");
}
$db->query("UNLOCK TABLES");
Here's the get_max() function, which obviously will fail if the script above executes simultaneously.
<?php
function get_max(){
global $db;
$max = $db->get_var("SELECT MAX(tblocNumber) FROM tbl_othercharge");
if($max == null){
$max = 1;
}else if($max >= 1){
$max = $max + 1;
}
return 'OC'.$max;
}
?>
I'm trying to test if there are still concurrency problems by executing the same script on 2 browsers.
The script above inserts 400+ records instead of 999 records. How do I properly lock the table while I'm inserting something into it.
I want to lock the table to prevent something like this to happen:
As you can see the field with the prefix 'OC' on it should have a number which is equal to the auto-increment primary key.
The only reliable solution is to do an insert with a dummy value, getting the last insert id, and updating the row to the correct value.
mysql_query("INSERT INTO table (field) VALUES (dummy);");
$id = mysql_last_insert_id();
mysql_query("UPDATE table SET field='OC{$id}' WHERE id={$id} LIMIT 1;");
I'd suggest to drop the 'OC' field from the table, e.g.
CREATE TABLE tbl_othercharge (tblocID int AUTO_INCREMENT PRIMARY KEY, assessmentID varchar(100));
CREATE VIEW vw_othercharge SELECT tblocID, concat('OC',tblocID) as OCnumber, assessmentID FROM tbl_othercharge
now direct all relevant SELECTs to vw_othercharge and forget about it.
Have you try:
for($x=0;$x<=500; $x++){
$db->query("LOCK TABLES tbl_othercharge WRITE");
$id = get_max();
$db->query("INSERT INTO tbl_othercharge SET tblocID = '$id', assessmentID='lock1'");
$db->query("UNLOCK TABLES");
}
In this way you will set lock each time you insert a row!