Comparing A Time Value Against Database To Stop Repeat Entries - php

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...
}

Related

How to loop multiple variable from first row of table PHP

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.

MSSQL INSERT query failing for a specific table when called with PHP

I need to read the date that a request was created from our website. When that request is created, the information corresponding to that request and its meta-request is inserted in the DAI_REQ.REQUEST and DAI_REQ.META_REQUEST tables, respectively. We also have a dev server and a public deployment server. The problem happens only on our deployment server for some reason..
Unfortunately, the INSERT query to insert the information of the meta-request in the DAI_REQ.META_REQUEST table does not work, but the SELECT query I do right after does (so in my eyes, this removes any connection problems with the database/table itself). I also use the same syntax as the INSERT query I do on the DAI_REQ.REQUEST, so I do not think it is a query syntax problem. I also tried manually inserting as line within sql-server and it works fine. Finally, I echo'ed the value of $this->userId that I use as a parameter for the INSERT query to see if it contained the right ID, and it does. I did the same for the return value of $this->db->query(...), and it does NOT return anything (on our deployment server only).
I also know that my way of retrieving the last inserted row in a table is not perfect, but this is not the problem at hand here and it will be changed later on.
Here is the actual code where the problem happens:
public function dbInsert(){
// The actual problematic query
$this->db->query("INSERT INTO DAI_REQ.META_REQUEST ".
"(DATE_RECU, DATE_TERMINEE, USER_ID, STATUS) ".
"VALUES(GETDATE(), '', ?, 'R');", array($this->userId));
// This works fine though
$mr_select = $this->db->query("SELECT TOP 1 ID FROM DAI_REQ.META_REQUEST WHERE USER_ID = ? ORDER BY ID DESC;",
array($this->userId));
$mr_result = $mr_select->result_array();
$mr_id = $mr_result[0]['ID'];
$sim = 'N/A';
if(isset($this->recurrenceType))
$sim = 'Recurrent';
$this->db->query("INSERT INTO DAI_REQ.REQUEST ".
"(USER_ID, ASSIGNED_DATE, REQUEST_END_DATE, MODEL, EXPERIMENT, VARIABLE, START_DATE, END_DATE, ".
"LON_FROM, LAT_FROM, LON_TO, LAT_TO, RESOLUTION, FORMAT, SIMULATION, STATUS, ".
"CANCELLED_YN, PROJECT, MR_ID, URL_ORIGIN, DATE_EMAIL) ".
"VALUES(?, GETDATE(), '', ?, 'N/A', 'N/A', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'R', 0, 'N/A', ?, ?, ?);",
array($this->userId, $this->model, $this->startDate, $this->endDate,
$this->lonFrom, $this->latFrom, $this->lonTo, $this->latTo,
$this->resolution, $this->format, $sim, $mr_id, $this->url_origin, $this->date_email));
$r_select = $this->db->query("SELECT TOP 1 ID FROM DAI_REQ.REQUEST WHERE USER_ID = ? ORDER BY ID DESC;",
array($this->userId));
$r_result = $r_select->result_array();
$this->id = $r_result[0]['ID'];
}
The database that the deployment server is using isn't set up to auto increment the ID column. In Microsoft SQL Server, for the ID column, you can set the Identity to Yes and Identity Increment to whatever number you want the ID column to increment by.

Entering Values To DB With Facebook API ID Is Same For All Entries

When entering each tagged_places from the Facebook API the id and the place_id are entered as the same random number.
When I print the object to the screen before entry both the id and the place_id are completely different numbers than what is entered in to the DB.
These numbers should be unique from each other, but every entry in the DB from my FB user account has the same id and place_id matching each other.
Does anyone have knowledge of this issue I am having? I need the id to be unique so I can use it to identify repeat inserts into my DB.
EDIT I notice that the number that is entered in my database for every new entry is the same number which has 10 digits. I am thinking this could be a phone number... EDIT
This is an example of an ID from the output of the variable,
[id] => 10202525749041541
And this is what shows up in the DB 2147483647
Here is my insertion code,
<?php
$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
));
}
}
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
?>
My problem was the Mysql field is set to int for id and place_id
int max value is 2147483647
And I was trying to enter a value of 10202525749041541
Solution for this problem was change the Mysql field from INT to BIGINT

Concatenating a string and primary key Id while inserting

I have a user table in mysql, I insert data like this:
/* prepare query */
$query = 'INSERT INTO `users`(`first_name`,
`last_name`,
`gender`,
`username`,
`profile_picture`,
`provider`,
`provider_id`,
`provider_username`,
`provider_profile`,
`provider_profile_picture`,
`last_login`,
`created_date`,
`ip_address`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), INET_ATON(?))';
/* Prepare an insert statement */
$stmt = $mysqli->prepare($query);
if($stmt){
$stmt->bind_param("sssssssssss", $user['first_name'],
$user['last_name'],
$user['gender'],
$user['username'],
$user['profile_picture'],
$user['provider'],
$user['id'],
$user['username'],
$user['link'],
$user['profile_picture'],
$_SERVER['REMOTE_ADDR']);
$stmt->execute();
/* Execute the statement */
I would like to make the username be equal to 'user' + userId which is autoincremental primary key field.
so that the usernames get in order:
user1
user2
user3 and so forth
what is a slick way to accomplish that?
If user_id is an AUTO_INCREMENT primary key, then you can't do this with a single statement, even if you use a trigger.
The problem is that the AUTO_INCREMENT value isn't generated until after the BEFORE INSERT trigger runs, but you can't change username in the AFTER INSERT trigger.
So you just have to do the INSERT, then immediately do an UPDATE.
If user_id is not an AUTO_INCREMENT, but instead is something you specify yourself, then it's easy, you just do the concatenation in your PHP code before you pass the values as parameters.
Update: You can't do it with MySQL 5.7 generated columns either. It results in this error when you try to create the table:
Generated column 'username' cannot refer to auto-increment column.
Assuming the username is always 'user' + userid, the slickest way I can think of to do this is to have a table with everything except username in it, and a view on top of that table that adds username. You would then do any inserts and updates on the table, and any selects that require username could be done on the view.
CREATE VIEW userview AS
SELECT user_id, first_name, last_name, gender, profile_picture, provider,
provider_id, provider_username, provider_profile, provider_profile_picture,
last_login, created_date, ip_address, 'user' + user_id as username
FROM USER

mysql/php insert/update on duplicate key

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

Categories