Morning, budies. I have an API call to bring me the profilesIds registereds in my websystem. I wanna make delete from my sqlserver table what is not content in my request response.
I do a select with the properties to show me what i have in common with my slqserver table and my response, and i do a delete with remaining.
In theory, it was supposed to work but no.
Have any mistake in sintax plz?
I currently have have 391 registers in my sql server table and only 389 is comum with my sqlserver table and response call.
When i do a select, bring me only that registers in common, idk wasnt working.
Select Query (bring me only 389 registers that i mentioned, is right).
foreach ($result as $indUser => $userInfos){
$agentId = $userInfos['id'];
$dhInsert = date("Y-m-d H:i:s");
foreach ($userInfos['profileIds'] as $indProfile => $idProfile){
$sql = "SELECT agentId, profileId
FROM LIVEPERSON_USERPROFILES
WHERE agentId = :agentId
AND profileId = :idProfile";
$stmt = Conexao::getConnection()->prepare($sql);
$stmt->bindValue(":agentId",$agentId,PDO::PARAM_STR);
$stmt->bindValue(":idProfile",$idProfile,PDO::PARAM_STR);
$rows = $stmt->execute();
}
}
Delete Query not working.
foreach ($result as $indUser => $userInfos){
$agentId = $userInfos['id'];
$dhInsert = date("Y-m-d H:i:s");
foreach ($userInfos['profileIds'] as $indProfile => $idProfile){
$sql = "DELETE FROM LIVEPERSON_USERPROFILES
WHERE NOT EXISTS (SELECT agentId, profileId
FROM LIVEPERSON_USERPROFILES
WHERE agentId = :agentId
AND profileId = :idProfile)";
$stmt = Conexao::getConnection()->prepare($sql);
$stmt->bindValue(":agentId",$agentId,PDO::PARAM_STR);
$stmt->bindValue(":idProfile",$idProfile,PDO::PARAM_STR);
$rows = $stmt->execute();
}
}
Data of table:
insert into testTable (agentId, profileId) values ('1536989','12345')
insert into testTable (agentId, profileId) values ('1536989','56789')
insert into testTable (agentId, profileId) values ('1536989','99999')
insert into testTable (agentId, profileId) values ('1536874','56789')
insert into testTable (agentId, profileId) values ('1536874','56984')
insert into testTable (agentId, profileId) values ('7568594','99999')
insert into testTable (agentId, profileId) values ('8895874','56984')
insert into testTable (agentId, profileId) values ('8895874','56789')
insert into testTable (agentId, profileId) values ('8895874','77777')
insert into testTable (agentId, profileId) values ('8895874','99999')
insert into testTable (agentId, profileId) values ('1235689','56789')
insert into testTable (agentId, profileId) values ('1235689','77777')
insert into testTable (agentId, profileId) values ('1245365','56984')
insert into testTable (agentId, profileId) values ('1245365','56789')
insert into testTable (agentId, profileId) values ('1245365','77777')
insert into testTable (agentId, profileId) values ('1245365','99999')
Obs: One agentId can have multiples profileIds, so, agentId is duplicated.
In data of table, i show that agentId 1536989 have a profile: 12345, 56789 and 99999. But in request, this agent have only 12345, 56789 profile. So i need delete from table the skill 9999 (f that happens it is successfull).
You don't need the subquery.
$sql = "DELETE FROM LIVEPERSON_USERPROFILES
WHERE agentId = :agentId AND profileId <> :idProfile)";
How i solved:
First, in foreach that i use to open the loop of response, i made a array to save this values and transform in querystring:
foreach ($result as $indUser => $userInfos){
$agentId = $userInfos['id'];
$dhInsert = date("Y-m-d H:i:s");
$forDelete[] = array(
'agentIdForDelete' => "'".$agentId."'",
'profileIdForDelete' => "'".implode("','",$userInfos['profileIds'])."'",
);
After, i print $forDelete and get this response:
Responsejson
Then i set a loop to iterate index and execute my delete query:
for ($i = 0; $i < count($forDelete); $i++){
$agentIdForDelete = $forDelete[$i]['agentIdForDelete'];
$profileIdForDelete = $forDelete[$i]['profileIdForDelete'];
$sql = "DELETE FROM LIVEPERSON_USERPROFILES
WHERE agentId = $agentIdForDelete AND profileId NOT IN ($profileIdForDelete)";
$stmt = Conexao::getConnection()->prepare($sql);
$stmt->execute();
}
That was the way I found to solve the problem. If anyone has another suggestion, i'm available :D
Related
I have a little problem to insert data in 2 tables and need some help with it.
For example:
Table 1:
CREATE TABLE tb1 (
tb1_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
tb1_title varchar(50),
tb1_cat varchar(50)
);
Table 2:
CREATE TABLE tb2 (
tb2_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
tb2_title varchar(50),
tb2_doc varchar(200),
id_tb1 int(5) not null REFERENCES tb1(tb1_id)
);
One entry of tb1 can have many information(rows) of tb2, but how to insert the id of tb1 in some rows of tb2?
formular.php:
$sqla = "INSERT INTO tb_1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
$sqlb = "INSERT INTO tb_2 (tb2_title, tb2_doc, <b>[? ? ?]</b>) VALUES ('$tb2_title', '$tb2_doc', <b>[? ? ?]</b>)";
mysqli_query($db, $sqla);
mysqli_query($db, $sqlb);
What do I have to change here?
You can get the value of tb1_id using mysqli_insert_id(), and then insert that into tb2:
$sqla = "INSERT INTO tb1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
if (mysqli_query($db, $sqla)) {
$tb1_id = mysqli_insert_id($db);
$sqlb = "INSERT INTO tb2 (tb2_title, tb2_doc, id_tb1) VALUES ('$tb2_title', '$tb2_doc', $tb1_id)";
mysqli_query($db, $sqlb);
}
Yes you can.. try this..
BEGIN;
INSERT INTO tb_1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat');
INSERT INTO tb_2 (tb2_title, tb2_doc, <b>[? ? ?]</b>,id_tb1) VALUES ('$tb2_title', '$tb2_doc', <b>[? ? ?]</b>,LAST_INSERT_ID());
COMMIT;
$sqla = "INSERT INTO tableA (col1, col2) VALUES (val1, val2)";
mysqli_query($db,$sqla);
$id = mysqli_insert_id($db); //add it here.
$sqlb = "INSERT INTO tableB (col1,col2) VALUES (val1, val2, ...)";
//then you can pass the id into your second query
//...
My project is a simple attendance record for my small school. I am submitting entry and exit logs through an online form, and writing them to a database with this query:
$sql = "INSERT INTO table_one (first_name, last_name, location)
VALUES ('$first_name', '$last_name', '$location')";
It works fine - so far so good.
At the same moment I would like to write some of this submitted information to another table in the same database. This query works fine by itself when standing alone:
$sql = "UPDATE another_table SET location='$location' WHERE first_name='$first_name'";
However my problem is how to make them both happen, in sequence. Just listing them successively doesn't work:
$sql = "INSERT INTO table_one (first_name, last_name, location) VALUES
('$first_name', '$last_name', '$location')";
$sql = "UPDATE personnel_table SET location='$location' WHERE
first_name='$first_name'";
What is the most effective (and safest) way to combine both commands so that they execute together?
You need to use transaction so that if one query fail, both should fail. Only if both query success that it will add/update the database.
$db= new PDO('mysql:host=localhost; dbname=test', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$db->beginTransaction();
$sh = $db->prepare("INSERT INTO table_one (first_name, last_name, location) VALUES (?, ?, ?)");
$sh->execute([$first_name, $last_name, $location]);
$sh = $db->prepare("UPDATE personnel_table SET location=? WHERE first_name=?");
$sh->execute([$location, $first_name]);
$db->commit();
} catch ( Exception $e ) {
$db->rollBack();
}
for this problem you must use trigger option in database (forEx mysql).
trigger is like an event. when insert in on table automate update second table. forEx:
mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));
Query OK, 0 rows affected (0.03 sec)
mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account
FOR EACH ROW SET #sum = #sum + NEW.amount;
Query OK, 0 rows affected (0.01 sec)
this trigger that is a object for account table. update #sum variable and then use for update second table
You can create a trigger like below:
delimiter #
create trigger after_ins_trig after insert on first_table
for each row begin
UPDATE second_table
SET new.location=old.location
WHERE new.first_name=old.first_name end#
delimiter ;
You can check id in where clause.
Why not this:
Table: teraz
Create Table: CREATE TABLE `teraz` (
`col` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
//
<?php
$last_name = 77;
$conn = new mysqli('localhost','root','','shopping');
$sql = "INSERT INTO teraz VALUES ('{$last_name}')";
$sql2 = "SELECT * FROM teraz";
$conn->query($sql);
$result = $conn->query($sql2);
$x = $result->fetch_assoc() ;
echo $x['col'];
?>
?
What is the proper way to reference the array components from fetch_assoc() so that they can be inserted into another table?
Here is my current code:
$sql_read = "SELECT id, data1, data2, date FROM `table1`";
$result = $mysqli->query($sql_read);
if ($result !== false) {
$rows = $result->fetch_all();
}
while ($row = $result->fetch_assoc()){
$sql_write = "INSERT INTO `table2`.`load_records` (`id`, `data1`,`data2`,`date`) VALUES ('.$row['id']', '.$row['data1']', '.$row['data2']', '.$row['date']', NULL);";
}
As suggested in my comment, first your select statement should be:
"SELECT id, data1, data2, date FROM `table1`";
Furthermore, the insert statement should be (see the use of concatenation of strings):
"INSERT INTO `table2`.`load_records` (`id`, `data1`,`data2`,`date`) VALUES ('".$row['id']."', '".$row['data1']."', '".$row['data2']."', '".$row['date']."', NULL);";
There are some errors in your script, as already pointed out.
But you might also be interested in the INSERT INTO ... SELECT variant of the INSERT syntax.
<?php
$query = '
INSERT INTO
table2
(`id`, `data1`,`data2`,`date`)
SELECT
`id`, `data1`,`data2`,`date`
FROM
table1
';
$result = $mysqli->query($query);
if ( !$result ) {
trigger_error('error: ' . $mysqli->error, E_USER_ERROR);
}
else {
echo $mysqli->affected_rows, ' rows have been transfered';
}
You have an extra field in the VALUES that is not referenced in the INTO and the concatenation of the row data is incorrect;
$sql_write = "INSERT INTO `table2`.`load_records`
(`id`, `data1`,`data2`,`date`)
VALUES ('.$row['id'].', '.$row['data1']', '.$row['data2']', '.$row['date']', NULL);";
should be:
$sql_write = "INSERT INTO `table2`.`load_records`
(`id`, `data1`,`data2`,`date`)
VALUES ('".$row['id']."', '".$row['data1']."', '".$row['data2']."', '".$row['date']."');";
Or you need to update the INTO to include an extra column that accepts NULL
See also:
The PHP reference on mysqli_result::fetch_assoc
I'm trying to get the last inserted id of multiple inserted rows.
record_id is auto increment
$sql = "INSERT INTO records (record_id, user_id, status, x) values ";
$varray = array();
$rid = $row['record_id'];
$uid = $row['user_name'];
$status = $row['status'];
$x = $row['x'];
$varray[] = "('$rid', '$uid', '$status', '$x')";
$sql .= implode(',', $varray);
mysql_query($sql);
$sql2 = "INSERT INTO status_logs (id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES";
$varray2[] = "(' ', mysql_insert_id(), '$status', '$uid', '$x')";
$sql2 .= implode(',', $varray2);
mysql_query($sql2);
This is the result:
INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', mysql_insert_id(), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active'), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active')
There is no value for mysql_insert_id().
You're mixing php function mysql_insert_id() and SQL INSERT statement syntax.
Either use MySQL function LAST_INSERT_ID() in VALUES clause of INSERT statement
INSERT INTO records (user_id, notes, x) VALUES('1237615', 'this is a note', 'active');
INSERT INTO status_logs (record_id, status_id, date, timestamp, notes, user_id, x)
VALUES(LAST_INSERT_ID(), '1', ...);
^^^^^^^^^^^^^^^^^
or retrieve the last inserted id by making a separate call to mysql_insert_id() right after first mysql_query(). And then use that value when you as a parameter to your second query.
$sql = "INSERT INTO records (user_id, ...)
VALUES(...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
$last_id = mysql_insert_id();
// ^^^^^^^^^^^^^^^^^^
$sql2 = "INSERT INTO status_logs (record_id, ...)
VALUES $last_id, ...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
Note:
You don't need to specify auto_incremented column in column list. Just omit it.
Use at least some sort of error handling in your code
On a side note: Instead of interpolating query strings and leaving it wide open to sql-injections consider to use prepared statements with either mysqli_* or PDO.
Unless I mis-reading your code, you're calling the PHP function mysql_insert_id from within the SQL?
What you need to do is grab that into a PHP variable first, then use the variable in the SQL. Something like this:
// Run the first query
mysql_query($sql);
// Grab the newly created record_id
$recordid= mysql_insert_id();
Then in the second INSERTs just use:
$varray2[] = "(' ', $recordid, '$status', '$uid', '$x')";
$fname = addslashes($fname);
$lname = addslashes($lname);
$dob = addslashes($dob);
$email = $_POST['email'];
$sql =
"INSERT INTO subscriber
(fname, lname, dob)
VALUES
('".$fname."', '".$lname."', '".$dob."')
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");
I am getting error in sql query "insertion error". Query is inserting data into DB after removing WHERE statement. What is the error.
You can't use where in an insert statement. You might be thinking of an update instead?
$sql = "update subscriber set fname='".$fname."', lname = '".$lname."', dob = '".$dob."' WHERE email='".$email."'";
If your email is a unique value, you can also combine an insert with an update like this:
insert into
subscriber (fname, lname, dob, email)
values ('".$fname."', '".$lname."', '".$dob."', '".$email."')
on duplicate key update set fname='".$fname."', lname='".$lname."', dob='".$dob."'
This second syntax will insert a row if there isn't one with a matching email (again, this has to be set to a unique constraint on the table) and if there is one there already, it will update the data to the values you passed it.
Basically INSERT statement cannot have where. The only time INSERT statement can have where is when using INSERT INTO...SELECT is used.
The only syntax for select statement are
INSERT INTO TableName VALUES (val1, val2, ..., colN)
and
INSERT INTO TableName (col1, col2) VALUES (val1, val2)
The other one is the
INSERT INTO tableName (col1, col2)
SELECT col1, col2
FROM tableX
WHERE ....
basically what it does is all the records that were selected will be inserted on another table (can be the same table also).
One more thing, Use PDO or MYSQLI
Example of using PDO extension:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
?>
this will allow you to insert records with single quotes.
Oops !!!! You cannot use a WHERE clause with INSERT statement ..
If you are targeting a particular row then please use UPDATE
$sql = "Update subscriber set fname = '".$fname."' , lname = '".$lname."' , dob = '".$dob."'
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");