Check if ID exists in database - php

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.

Related

How do I can skip a duplicate value before adding it to the database?

I have table with favorites programm. I will add with ajax query to database favorite programm id's to table with user id. How I can skip a duplicate programm id with current user id.
I now create this method for skip duplicate values but not working in calling:
public function test($programm_id){
$fav = new \App\Favorite;
$user_id = Auth::id();
$fav_count = $fav::where('id_user', Auth::user()->id)->count();
$getFavorites = $fav::where('id_user', $user_id)->get()->toArray();
$userProgramms = $fav->where('id_user', $user_id)->select('id_program')->get()->toArray();
$bool = true;
foreach ($userProgramms as $array) {
foreach ($array as $value) {
if($value === $programm_id) $bool = false;
}
}
if($fav_count <= 5){
if ($bool){
$fav->id_user = Auth::user()->id;
$fav->id_program = $programm_id;
$fav->save();
}
}
}
Here my table:
Please see my method favorite() in this controller: Controller
My updated code can't more 1 saves to database.
$fav = new \App\Favorite;
$fav_count = $fav::where('id_user', Auth::user()->id)->count();
if($fav_count <= 5)
{
$fav->updateOrInsert(['id_user' => Auth::id()], ['id_program' => $post['id_program']]);
}
Every user can add to table max 6 favorite id programms
Add an unique index on the table:
ALTER TABLE `tableName` ADD UNIQUE `unique_index`(`id_user`, `id_program`);
and use the INSERT INTO ... OR UPDATE:
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE t1 SET c=c+1 WHERE a=1;
In that manner your query will insert a new record if there isn't already a record with the same couple of id_user and id_program values, in case of it it'll perform an update on that row.
If you want to do it in PHP and assuming your values are stored in an array, you can use array_unique().
Check it out here: http://php.net/manual/en/function.array-unique.php

How to create unique registration number

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 to insert unique table data except id in codeigniter?

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!

Generating new ID: Getting actual IDs

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.

How to lock mysql tables in php

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!

Categories