Insert if not exists with Codeigniter - php

I am encountering the following problem I am trying to insert data into the table if
phone, sushi_service_id both has a row with active = 1
for example:
ID | Phone | sushi_service_id | active
---------------------------------------
1 | 455 | 1 | 1 (LEGAL)
3 | 455 | 1 | 0 (LEGAL)
4 | 455 | 1 | 0 (LEGAL)
5 | 455 | 1 | 1 (NOT LEGAL! HAS THE SAME PHONE+SUSHI_SERVICE_ID+ACTIVE=1)
This is my codeigniter code:
how can I improve it in order to work like I said above?
public function add($service, $phone, $sushi_subscription_id, $answer_id, $affiliate_id, $ip, $query, $invite_type, $invite_msg_id)
{
$this->db->set('service_id', $service->id);
$this->db->set('sushi_service_id', $service->sushi_service_id);
$this->db->set('phone', $phone);
if ($sushi_subscription_id) {
$this->db->set('sushi_subscription_id', $sushi_subscription_id);
}
$this->db->set('answer_id', $answer_id);
if ($affiliate_id) {
$this->db->set('affiliate_id', $affiliate_id);
}
$this->db->set('added', 'NOW()', FALSE);
$this->db->set('active', 1);
$this->db->set('ip', $ip);
$this->db->set('query', $query);
if ($invite_type) {
$this->db->set('invite_type', $invite_type);
}
if ($invite_msg_id) {
$this->db->set('invite_msg_id', $invite_msg_id);
}
return ($this->db->insert($this->_table_name)) ? $this->db->insert_id() : FALSE;
}

I would just do a select * from XX where active = 1 and then based on the result of num_rows the insert query.

Easiest way to do this would be in a single INSERT with ON DUPLICATE KEY UPDATE query.
Example structure:
INSERT INTO table ... VALUES .... ON DUPLICATE KEY UPDATE

Related

Duplicate Data Stop in MySQL

I have a table below :
+-----+-------+------+------------+
| ID | RefID | Type | EventTime |
+-----+-------+------+------------+
| 101 | 228 | 1 | 1437195633 |
| 102 | 228 | 5 | 1437195633 |
| 103 | 228 | 1 | 1437195633 |
| 104 | 228 | 1 | 1437195442 |
| 105 | 228 | 1 | 1437195442 |
| 106 | 228 | 5 | 1437195442 |
| 107 | 228 | 1 | 1437165634 |
| 108 | 228 | 5 | 1437165442 |
| 109 | 228 | 1 | 1437165634 |
| 110 | 228 | 5 | 1437165442 |
+-----+-------+------+------------+
In that I want to stop inserting duplicate data based on the columns RefID,Type,EventTime only when value of Type = 1.
In the above table ID pair is duplicate (101,103), (104,105), (107,109).
If now I will insert another data say :
INSERT INTO table VALUES('',228,1,1437165634);
Then it should not insert. I am checking while inserting into that table but that is not working as I have checked at the same time 2 insert query is happening, I need to stop it using UNIQUE key constraints.
You need change DB architecture. Add table with unique index by RefId, here you will write record with Type "1". In your Yii model in method beforesave check your Type if is 1 to write in added table otherwise write to old table. And you need change beforefind method
And I'm sorry for my english
Please try:
public function unique($attribute, $params)
{
if(!empty($model_name)){
$this->addError('RefID', 'RefID already exists! Please choose a different one');
return true;}
}
as a custom function in before save. and call it for the fields you want in the rule. I'm showing you the template for a single field refID
I have solved it by using trigger as below :
DB Trigger
delimiter $$
drop trigger if exists stop_duplicate $$
create trigger stop_duplicate before insert on table
for each row
begin
set #found := false;
if new.Type = 1 then
SELECT
TRUE
INTO #found FROM
table
WHERE
RefID = new.RefID AND EventTime= new.EventTime AND Type= new.Type;
if #found then
signal sqlstate '23000' set message_text = 'CUSTOM_MSG_DUPLICATE';
end if;
end if;
end $$
delimiter ;
Yii Model Code
public function save($runValidation = true, $attributes = null) {
Yii::log(__METHOD__.":: Start ", 'info');
try {
return parent::save();
} catch (Exception $e) {
$errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
$message = $e->getMessage();
Yii::log(__METHOD__ . ": errorcode :{$e->getCode()}, errormessage:{$message} ", 'info');
// Added for handling duplicate entry issue for index
if ((int) $e->getCode() === 23000 && strpos($message, 'CUSTOM_MSG_DUPLICATE') !== false) {
return false;
}
throw new CDbException(Yii::t('yii', 'CDbCommand failed to execute the SQL statement: {error}', array('{error}' => $message)), (int) $e->getCode(), $errorInfo);
}
}

SQL updating tables recursively with PHP

I have a conversation table and conversation reply table:
conversation table:
+-------+-------+--------+
| cid | u_1 | uid_2 |
+-------+-------+--------+
| 1 | 8 | 3 |
| 2 | 8 | 5 |
| 3 | 8 | 2 |
+-------+-------+--------+
conversation_reply table:
+-------+-------+--------+--------+
| cr_id | reply | uid_fk | cid_fk |
+-------+-------+--------+--------+
| 1 | | 8 | 1 |
| 2 | | 8 | 11 |
| 3 | | 8 | 11 |
+-------+-------+--------+--------+
I need to be able to update the conversation table with a new record if one doesn't exist when a new reply is created, however I get the following error:
Cannot add or update a child row: a foreign key constraint fails
(`_db`.`conversation_reply`, CONSTRAINT `conversation_reply_ibfk_2`
FOREIGN KEY (`cid_fk`) REFERENCES `conversation` (`cid`))
Any help much appreciated!!!!
EDIT
I have put the convo reply query into the create new convo query, it will create a new convo but still doesn't insert the reply:
if (!empty($_GET['conv_id'])) {
$cid = mysql_real_escape_string($_GET['conv_id']);
echo $cid;
}
if($user_one!=$user_two){
// Check convo doesn't already exist.
$q_exist= mysql_query("SELECT c_id FROM mc_conversation WHERE (user_one='$user_one' and user_two='$user_two') or (user_one='$user_two' and user_two='$user_one') ") or die(mysql_error());
if(mysql_num_rows($q_exist)==0) {
$query = mysql_query("INSERT INTO mc_conversation (user_one,user_two,ip,time) VALUES ('$user_one','$user_two','$ip','$time')") or die(mysql_error());
$q=mysql_query("SELECT c_id FROM mc_conversation WHERE user_one='$user_one' ORDER BY c_id DESC limit 1");
$v=mysql_fetch_array($q);
return $v['c_id'];
$v_cid = $v['c_id'];
// Insert reply.
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$v_cid')") or die(mysql_error());
// Convo already exists.
} else {
$v=mysql_fetch_array($q_exist);
return $v['c_id'];
// Insert reply
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$cid')") or die(mysql_error());
echo $cid;
}
}
You have called "return" in your else loop, which will end execution of the function, or if called from the global scope, execute the current script.
http://php.net/manual/en/function.return.php
Try this:
// Insert reply
$v=mysql_fetch_array($q_exist);
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$cid')") or die(mysql_error());
echo $cid;
From the code that you have posted I think the problem is with the return statement.
The reply is not getting inserted because you have
return $v['c_id'];
before the INSERT query code. And if this code is inside a function, it will just return the value and not execute any further line.
You should have the return statement at the very end of the function / after doing all required operations. If it is for debugging purpose, you can use echo statement.

How to get in array data from table?

I have a tags_ids array 1,3,2 and
data in my table:
+---------+----------+
| user_id | tag_id |
+---------+----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 2 |
+---------+----------+
I want to get the users ids into array, but not working:
foreach ($tags_ids as $i)
{
if ($result = $mysqli->prepare("SELECT `user_id` FROM `mytable` WHERE `tag_id`=?"))
{
$result->bind_param("i",$i);
$result->execute();
$result->bind_result($d);
$result->fetch();
$result->close();
}
if (!in_array($d,$users_ids)) $users_ids[] = $d;
}
My result is always 1. Whats I'm doing wrong, and can I do it in a more simple way?
you need a while loop, you can find it here for full assist:http://www.youtube.com/watch?v=hO0YOOeJrOE
be sure to watch the other video's too, very helpfull.
goodluck,
PHPNoob

How to display data from one table and then insert that data to another table in php?

I need to fetch data from table whose mem_count is equal to 2 and then insert that data to another table after last unique_id.
Here is my code :
$mem_count2=mysql_query("SELECT mem_count,mem_id FROM member_status WHERE mem_count = 2 order by mem_id ASC");
if(mysql_num_rows($mem_count2 )==0){
die(mysql_error());
}
else{
$start_value=00;
// $start_value dynamically comes from other table which i am not mentioning here
// $start_value can starts from any number For Eg. 2, 5.
while ($row=mysql_fetch_array($mem_count2)) {
$uniq_code="PHR-" . str_pad((int) $start_value, 2, "0", STR_PAD_LEFT);
//if mem_id already inserted then use IGNORE in INSERT i.e INSERT IGNORE
$cql = "INSERT IGNORE INTO member_code (mem_id, temp_code,unique_code) values ('".$row['mem_id']."','".$row['mem_count']."','".$uniq_code."')";
mysql_query($cql) or exit(mysql_error());
$start_value++;
}
}
It runs smoothly but sometimes i am getting this output:
+------------+-------------+
| mem_id | unique_code |
+------------+-------------+
| 1 | PHR-01 |
+------------+-------------+
| 5 | PHR-02 |
+------------+-------------+
| 3 | PHR-04 |
+------------+-------------+
Some problem is surely in the INSERT IGNORE query!I have made mem_id as UNIQUE. Please rectify this as i am completely stuck over it !
Member_code structure
+------------+-------------+-----+
| mem_id | unique_code | Id |
+------------+-------------+-----+
| 1 | PHR-01 | 1 |
+------------+-------------+-----+
| 5 | PHR-02 | 5 |
+------------+-------------+-----+
| 3 | PHR-04 | 3 |
+------------+-------------+-----+
It is probably because you are getting an error at some point at this line
mysql_query($cql) or exit(mysql_error());
and then your increment variable will be incremented for the next insert. You should test the insert and if doesn't get error you do the increment.
You are using a variable called $mem_count2 throughout your code, when the results are stored in $mem_count.

How to update multiple rows and database with same value at once? Laravel

I'm stuck in code. I managed to create a form that adds a multiple number of rows in db but I do not know how to update them at the same time when i need to use product_code as id.
This is table 1 (products) structure:
id | product_name | product_code
1 | Name1 | 101
2 | Name2 | 102
3 | Name3 | 103
4 | Name4 | 104
This is table 2 (products_ing) structure:
id | product_code | ing_name | ing_weight
1 | 101 | INGName1 | 110
2 | 101 | INGName2 | 10
3 | 101 | INGName3 | 54
4 | 101 | INGName4 | 248
This is edit function:
public function post_edit($id = null)
{
if(Input::get('submit'))
{
// ID
if($id !== null)
{
$id = trim(filter_var($id, FILTER_SANITIZE_NUMBER_INT));
}
$input = Input::all();
$validation = Validator::make($input);
else
{
foreach ($input as $key => $value)
{
$input[$key] = ($value !== '') ? trim(filter_var($value, FILTER_SANITIZE_STRING)) : null;
}
try
{
DB::table('products')
->whereIn($id)
->update(array(
'product_name' => $items['product_name'],
'product_code' => $items['product_code']
));
}
}
return $this->get_edit($id);
}
With this I can only edit *product_name* and product_code from products table by id.
But I'm trying to update multiple rows from db with same product_code that would serve as id.
// I found on Google images one good image that explains what I'm trying to do but with Laravel:
IMAGE LINK
Is there a solution? Thank you in advance!
Assuming you are using MySQL: Let the database's foreign key do this for you, with the ON UPDATE CASCADE command. This will update all referenced tables if you change the product_code in your base products table.
CREATE-Script of products_ing
...
product_code INT NOT NULL REFERENCES products(product_code) ON UPDATE CASCADE
...
As laravel migration
Schema::create('products_ing', function($table) {
$table->increments('id');
$table->int('product_code');
$table->string('ing_name');
$table->int('ing_weight');
/* All the other key stuff */
$table
->foreign('product_code')
->references('product_code')
->on('products')
->onUpdate('cascade');
});

Categories