How to insert unique table data except id in codeigniter? - php

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!

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 remove data duplicacy in customer table

i have a table customer_stock_entries.. i want to insert the item if the item and supplier is not available and i want to update the item if item and supplier is available
Example in my table i have stock_supplier_name and quantity. What i want to do is that if the stock supplier name entry is new then insert it into the table and if the entry is already there then delete the previous value in column 'quantity' and insert the new value.
i am stuck with this. Please help me out
I have tried something like this.
for ($i = 0; $i < count($stock_name); $i++) {
$count = $db->countOf("customer_stock", "name='$stock_name[$i]'");
if ($count == 0) {
$db->query("insert into customer_stock(name,quantity) values('$stock_name[$i]',$quty[$i])");
echo "<br><font color=green size=+1 >New Stock Entry Inserted !</font>";
$db->query("insert into stock_details(stock_id,stock_name,stock_quatity,supplier_id,company_price,selling_price) values('$autoid','$stock_name[$i]',0,'$supplier','$cost[$i]','$sell[$i]')");
$db->query("INSERT INTO customer_stock_entries(stock_id,stock_name, stock_supplier_name, quantity, company_price, selling_price, opening_stock, closing_stock, date, username, type, total, payment, balance, mode, description, due, subtotal,count1,billnumber) VALUES ( '$autoid1','$stock_name[$i]','$supplier','$quty[$i]','$cost[$i]','$sell[$i]',0,'$quty[$i]','$date','$username','entry','$total[$i]','$payment','$balance','$mode','$description','$due','$subtotal',$i+1,'$bill_no')");
} else if ($count == 1) {
$amount = $db->queryUniqueValue("SELECT quantity FROM customer_stock WHERE name='$stock_name[$i]'");
$amount1 = $amount + $quty[$i];
$db->execute("UPDATE customer_stock SET quantity='$amount' WHERE name='$stock_name[$i]'");
$db->query("INSERT INTO customer_stock_entries(stock_id,stock_name,stock_supplier_name,quantity,company_price,selling_price,opening_stock,closing_stock,date,username,type,total,payment,balance,mode,description,due,subtotal,count1,billnumber) VALUES ('$autoid1','$stock_name[$i]','$supplier','$quty[$i]','$cost[$i]','$sell[$i]','$amount','$amount1','$date','$username','entry','$total[$i]','$payment','$balance','$mode','$description','$due','$subtotal',$i+1,'$bill_no')");
Thanks
Typical solution to this problem involve following typical steps:
Check if the record for the stock supplier exists by using a select query and if it exists, update the quantity attribute.
If the the record doesn't exist, then insert the record in the table.
Sample Code as requested:
IF EXISTS(SELECT * FROM Users WHERE UserId = #UserId)
BEGIN
UPDATE TC_Users SET Salary = 25000 WHERE UserId = #UserId
END
ELSE
BEGIN
INSERT INTO TC_Users(UserId, Salary) VALUES(#UserId, 25000)
END
Hope this helps you.
Hare are some information's regarding your problem:
Primary Keys (To Avoid Duplication Of Data) :
Always use primary keys in your Database Table Structure i.e consider one column as primary key in order for it to be unique so that duplicate value won't be able to be inserted in your records.
Example : For instance I have a table with following columns as id,username,password,name .Now in order for to avoid duplication of data i.e that I don't want people to register with same username which means that username column value should be unique so instead I mark my username column as Primary Key.So now the new upcoming members won't be able to register with the same username which is already available in database i.e someone already registered using that username.Instead they will be needed to register with unique username.
Solution :
While here is code for to update your quantity value if supplier is already present in the database and if not so then insert the new record..!
$supplier_name = $_POST['supplier];
$query = mysqli_query($mysqli,"SELECT * FROM table");
$results = mysqli_fetch_array($query);
for ($i=0;$i<=count($results);$i++) {
//IF supplier is available in database
if ($results[$i]['supplier'] == $supplier_name) {
$query = mysqli_query($mysqli,"UPDATE table SET quantity=$quanity_new_value WHERE supplier=$supplier_name");
} else {
// If supplier is not available in database so it will insert new record
$query = mysqli_query($mysqli,"INSERT INTO table (supplier, quanity, email) VALUES ($supplier_name, $quantity, $email)");
}
}

MySQL INSERT --- get the ID (auto_increment) IF one value is UNIQUE

Is there a better or faster way to return the ID?
The column customer is unique
$inserted_id = null;
if( !$mysqli->query("INSERT INTO users (id,customer) VALUES(null,'foo')" ){
// Is it possible to avoid this 2nd query?
$result = $mysqli->query("SELECT id FROM users WHERE customer='foo'");
$inserted_id = $result->fetch_assoc()['id'];
} else {
$inserted_id = $mysqli->insert_id;
}
Use $last_id = $mysqli->insert_id(); after your insert. That get's the last generated auto increment. Your code as it stands will not be accurate. Updated for Object Oriented perspective.
You can modify the insert query to UPDATE auto incremented column when a duplicate record is attempted to INSERT.
INSERT INTO users (id,customer)
VALUES (null,'foo')
ON DUPLICATE KEY UPDATE
id = LAST_INSERT_ID(id)
id = LAST_INSERT_ID(id) will return the value of the AUTOINCREMENT column for the last INSERT and set the value for mysqli_insert_id. This will make last insert id available during all inserts.
Have modified your code:
$inserted_id = null;
if($mysqli->query("INSERT INTO users (id,customer) VALUES(null,'foo') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)" )
{
$inserted_id = $mysqli->insert_id; // Will return last insert ID in case of successful inserts as well as failed inserts due to duplicate key
}

How to get a tuple's values that is inserted into PostgreSql db using php?

I am trying to insert a tuple into PostgreSql using PHP. After inserting the tuple I want to get the value of one of the columns of the inserted row. This column value is generated automatically by the db as it is defined as SERIAL in DDL.
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me')";
$result = pg_query($dbh,$query);
if (!$result) {
$status = 0;
} else {
$status = 1;
}
$row = pg_fetch_assoc($result);
$pID = $row['postID'];
$array = array(
'status' => $status,
'pID' => $pID
);
#Delete query is only for checking if the code is working.
$query = "DELETE FROM posts WHERE postID='$pID'";
$result = pg_query($dbh,$query);
The table 'posts' has following DDL:
CREATE TABLE posts
( title CHAR(20),
content CHAR(42),
x_coor INTEGER,
y_coor INTEGER,
userID CHAR(50),
time_stamp TIMESTAMP default current_timestamp,
postID SERIAL,
PRIMARY KEY(postID),
FOREIGN KEY (userID) REFERENCES users ON DELETE CASCADE);
I want to get the value of 'postID' column when I insert a row into the table 'posts' to perform additional functions based on postID. I have tried pg_fetch_assoc, pg_fetch_row, pg_fetch_object & pg_fetch_array. None of those seem to work. (I made appropriate modifications to the code when using each of those functions.)
Is there something incorrect in the code or perhaps I am missing something?
Thanks!
A good way is the returning clause:
INSERT INTO posts
VALUES('$title','$msg',$x,$y,'$me')
RETURNING id;
My PHP is a bit rusty, but it'd look something like:
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me') RETURNING id";
$result = pg_query($dbh, $query);
if ($result) {
$row = pg_fetch_row($result);
$inserted_id = $row[0];
}

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

Categories