How to create unique registration number - php

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);
?>

Related

Auto-increment in mysql query

I need to populate several columns of MYSQL table with data from arrays. So one column corresponds to one array. I have used the following code to fill just one column with data:
function addSystemDataTanks ($db, $tankNamesArray, $tankVolumesArray) {
$myArray = array();
$myString = implode ("'), ('",$myArray);
$statement = "replace into myTable (ID, NAME)";
$statement .= "values (' ";
$statement .= $myString;
$statement .= "')";
$result = mysqli_query($db, $statement);
if ($result) {
return true;
}
}
I need the ID field to be populated by auto-generated incremented numbers. But I need these rows to be replaced with new values next time this form is submitted. For the "replace" to work the ID has to be the same as previously used, otherwise it will just create new entries.
Also, is there a better way to input arrays as columns in MYSQL table, other than one by one, cause I need all row values to match to each other and the ID should be unique and start from 0 or 1 next time the form is submitted.
Thanks for any help.
If you just want the row ID to be incremental you're making life hard for yourself! When you create the table in MySQL, use AUTO_INCREMENT on the ID, then you can just enter a NULL value for the ID in your code:
CREATE TABLE blah (ID INT NOT NULL AUTO_INCREMENT, name VARCHAR(50), PRIMARY KEY(ID));
$sql = "INSERT INTO blah VALUES(NULL, 'Adam')";
"Adam" will now have an ID of 1 :)

how to auto increment variable

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)

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!

Check if ID exists in database

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.

PHP and MySQL SELECT problem

Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks!
MySQL code.
SELECT *
FROM names
WHERE name = '" . $_POST['name'] . "'
AND userID = '$userID'
Here is the MySQL table.
CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
If $_POST['name'] is actually an array of strings, as you say, then try this PHP:
$namesString = '';
foreach ($i=0; $i < count($_POST['name']) $i++)
{
$namesString .= "'" . mysql_real_escape_string($_POST['name'][$i]) . "'";
if(isset($_POST['name'][$i + 1]) $nameString .= ', ';
}
With this query:
SELECT * FROM `names`
WHERE `name` IN ( $namesString )
AND `userID` = '$userID'
The query will return all the rows in which the name is the same as string in $_POST['name'].
First of all, if the userID field is unique, you should add a unique index on it in your table.
Also, watch out for SQL injection attacks!
Using something like this is much more secure:
$sqlQuery = sprintf('SELECT COUNT(id) AS "found" FROM names WHERE userID = "%s"', mysql_real_escape_string($_POST['name'], $conn));
This SQL query will return 1 row with 1 field (named found) which will return you the number of matched rows (0 if none). This is perfect if you only want to check if the userID exists (you don't need to fetch all data for this).
As for the dynamic array, you will have to post more information and I'll update my answer.
Meanwhile here are some usefull PHP functions that can help you do what you want:
For MySQL queries:
mysql_connect
mysql_real_escape_string
mysql_query
mysql_fetch_assoc
For your list of users:
explode
implode
Stated as you say, I'm quite sure the code does exactly what you are asking for. The SELECT should return the records that respond both to the name sent and the current user ID.
If you need some php code, here it is (should be refined):
$result = mysql_query('YOUR SELECT HERE');
if (!$result) {
die('ERROR MESSAGE');
} else {
$row = mysql_fetch_assoc($result));
// $row is an associative array whose keys are the columns of your select.
}
Remember to escape the $_POST.

Categories