I need to get either a 1 (the record was inserted) or a 2 (the record was updated). How can this be done using Laravel? I can't find any information about this in their documentation.
DB::insert('insert into ratings
(owner_id, game_id, rating) values (?, ?, ?)
on duplicate key update rating = values(rating)',
[
(int)$body['user'], (int)$gameId, (int)$body['amount']
]);
I know I can get pdo like this:
$pdo = DB::connection()->getPdo();
but I don't think that helps...
You will want to use the function affectingStatement which seems to return the number of affected rows...
$res = DB::affectingStatement('insert into ratings
(owner_id, game_id, rating) values (?, ?, ?)
on duplicate key update rating = values(rating)', [
(int)$body['user'],
(int)$gameId,
(int)$body['amount']
]);
For me, this was returning 2 when a row updates, 1 when a row is inserted, and 0 on failure as expected.
Related
I based on the sales person to loop and insert the data with 3 rows into database 2. But I cannot insert the category with 2 times with 2 sales person based on the first row, it keep get the last row of category data and insert to database. Like below image of 1.
$product_type = $request->post('product_type');
$emp_amount = $request->post('amount');
foreach($_POST['employee'] as $index => $employee_list){
$statement = $this->db->prepare('
INSERT INTO `selling_employee` (
invoice_no, payment_id, category, sale_person, amount, created_at
) VALUES (?, ?, ?, ?, ?, ?)
');
$statement->execute([
$invoice_id, $payment_id, $product_type[$index], $employee_list, $emp_amount[$index], $created_at
]);
}
Any solution how to detect the first row got more than sales person and insert multiple same data based on first row.
Please help me with mysql query...
i have this situation:
table 1 -- tasks
**id**|task_name|status|created_at|updated_at|user_id
and table 2 -- samples
id|sample_name|...|...|...many other things|**task_id**|user_id
i want that in table 2 in column "task_id" is "id" from table 1 or "tasks.id" ?
I have this query but it's result is number 1 in each column instead of the id of each entry..
INSERT INTO samples(task_id),
SELECT tasks.id from tasks
JOIN samples
ON task_id = tasks.id
thanks for help...
Assuming you are doing this through PHP (based on you tagging it) and assuming that you need an insert into both tables, the basic jist would be (also assuming the id field in tasks is auto-increment):
$stmt1 = $conn->prepare("INSERT INTO tasks (fields, other_fields) VALUES (?, ?)"))
{
$stmt1->bind_param("ss",$fields, $other_fields);
$stmt1->execute();
$lastid = $conn->insert_id;
$stmt1->close();
}
Now you can use the variable $lastid as the value when you insert the samples data.
$stmt2 = $conn->prepare("INSERT INTO samples (id, other_fields, task_id) VALUES (?, ?, /)"))
{
$stmt2->bind_param("isi",$ID, $other_fields, $lastid);
$stmt2->execute();
$stmt2->close();
}
If samples already exists and you need to update it with the id from tasks, you'd just update samples after the insert into tasks, assuming you have something to use in the where clause that can uniquely identify the record you want updated :
$stmt2 = $conn->prepare("UPDATE samples set task_id = ? where user_id - ?)
$stmt2->bind_param("ii",$lastid, $user_id);
$stmt2->execute();
$stmt2->close();
}
else {
die(mysqli_error($conn));
}
I'm making a lot of assumptions, I know. But I can't comment yet so this is my only way of assisting.
Unfortunately your method is not true and not logical.
At you at the moment of recording there is no field which could unite the data of the table, so you need to get the task_id first and then insert it into the query
I have a table which contains pageid, department, position and active. While updating, I have to update active column if pageid is already exists, if not I will insert a new row with the pageid.
I am getting pageid values through checkbox and my update query is like this
$sql = "INSERT INTO access_level (page_id, department, position, active)
VALUES (".$sn.", ".$department.", ".$position.", 1)
ON DUPLICATE KEY UPDATE
department=VALUES(".$department."),
position=VALUES(".$position."),
active=VALUES(1)";
But everything is getting inserted twice in this case.
Where I am doing wrong? Can somebody guide me?
This should probably work for you:
$sql = "INSERT INTO access_level (page_id, department, position, active)
VALUES (".$sn.", ".$department.", ".$position.", 1)
ON DUPLICATE KEY UPDATE
id=LAST_INSERT_ID(id),
active=VALUES(1)";
I am inserting values into a database.
If the time the values were created is less than 24 hours then I insert like this,
$stmt = $con->prepare('
INSERT INTO taggedPlaces
(id, created_time, place_id, city, country, latitude, longitude, state, street, zip, name)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
');
foreach($graphObject['tagged_places']->data as $data) {
if (time() - strtotime($data->created_time) < 86400) {
$stmt->execute(array(
$data->id,
$data->created_time,
$data->place->id,
$data->place->location->city,
$data->place->location->country,
$data->place->location->latitude,
$data->place->location->longitude,
$data->place->location->state,
$data->place->location->street,
$data->place->location->zip,
$data->place->name
));
}
}
Everytime I return to the page it takes the same entries and continuously adds them to the database.
I would like to say something like
if $data->created_time == any created_time value in the DB then don't add this value,
as well as currently I am doing
if (time() - strtotime($data->created_time) < 86400)
to make sure it is not older then 24 hours.
How can I add this condition?
Option 1: (Recommeded)
Make id the primary key for your table, taggedPlaces:
ALTER TABLE taggedPlaces ADD PRIMARY KEY(id)
Then change your insert statement to use INSERT IGNORE which will skip duplicate inserts.
Option 2:
Make created_time a unique field in taggedPlaces:
ALTER TABLE taggedPlaces ADD UNIQUE(created_time);
Then, again, use INSERT IGNORE to skip duplicates.
Option 3: (Not recommeded, but will work)
Prior to running your insert, perform another query to check if $data->created_time is already in the table:
$check = $con->prepare('
SELECT id FROM taggedPlaces
WHERE created_time = ?
');
$check->execute(array($data->created_time));
if (count($check->fetchAll()) == 0) {
// No duplicates found. Proceed...
}
I have a product info table with more than 130 columns/fields.
I want to write a php script that adds a new product to the table OR updates the existing product if it already exist. The first field is the product key.
The product information is stored in a numbered php array : $product_info[0] to $product_info[130].
Basically something like this :
INSERT INTO table (a,b,c) VALUES ($product_info[0],$product_info[1],$product_info[2])
ON DUPLICATE KEY UPDATE a='$product_info[0]', b='$product_info[1]', c='$product_info[2]'
Is there something more efficient than typing each of the 130 fields twice?
Yes, there is, use the VALUES() function:
INSERT INTO `table` (a, b, c) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE a = VALUES(a), b = VALUES (b), c = VALUES(c)
Basically, in the UPDATE part, VALUES(column) will return the specified value for that column for the current row in question. So you can do interesting things like:
ON DUPLICATE KEY UPDATE
a = VALUES(a),
b = VALUES(b) + VALUES(c),
The beauty of that syntax, is it also supports multiple insert rows:
INSERT INTO `table` (a, b, c)
VALUES (?, ?, ?),
VALUES (?, ?, ?),
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE a = VALUES(a), b = VALUES (b), c = VALUES(c)
Unfortunately MySQL does not support merging... having an ORM can help ease the pain of coding multiple IF EXISTS UPDATE ... ELSE INSERT code
REPLACE