Not sure that this is even possible. I am inserting values into two tables at the same time using multi_query. That works fine. One of the tables has an auto increment column and I need to take the last auto incremented number and insert it into the second table so like this: insert into table 1 then take the last inserted number from column X and insert it along with other data into table 2. I have played around with using SELECT LAST and INSERT INTO but so far its just doing my head in. The insert statements looks like this:
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate) VALUES ('$riskclient2', '$facility2', '$riskdate2');";
$sql .="SELECT LAST(riskId) FROM tbleClients;";$sql .="INSERT INTO tblRiskRegister (riskId) SELECT riskId FROM tbleClients ;";
$sql .= "INSERT INTO tblRiskRegister (riskAudDate, riskClientId, riskSessionId, RiskNewId) VALUES ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";
Individually they all produce results but I need it to happen simultaneously. I did toy with the idea of doing them all separately but figure thats not very efficient. Any pointers would be appreciated.
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate) VALUES ('$riskclient2', '$facility2', '$riskdate2');";
After executing the above query, using mysqli_insert_id(), which gives you the last insert id.
So below query is useless.
$sql .="SELECT LAST(riskId) FROM tbleClients;";
$sql .="INSERT INTO tblRiskRegister (riskId) SELECT riskId FROM tbleClients ;";
You can insert last_insert_id in above query.
Unable to find the relation between above & below query.
$sql .= "INSERT INTO tblRiskRegister (riskAudDate, riskClientId, riskSessionId, RiskNewId) VALUES ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";
Related
I have 17 columns in my DB
I'm inserting values from different sources. Somewhere I haven't, for example, company/company_info values (I'm setting in PHP FALSE values for relevant variables).
So, I need some kind of PHP INSERT query to insert only not empty variables and columns of certain list.
For example, I could do:
$q = "INSERT INTO `$tname` (`phone`,`location`, `pagelang`, `company`, `company_url`, `phone_no_cc`, `phone_type`, `operator`, `pageviews`, `rating`, `comments_number`, `activity_by_days`, `activity_by_hours`) VALUES (
'$main_number', '$number_advanced_info[location]', '$pagelang', '$company[name]', '$company[site]', '$number_advanced_info[number_no_countrycode]', '$number_advanced_info[phone_type]', '$number_advanced_info[operator]', '$searches_comments[searches]', '$rating', '$searches_comments[comments]', '$history_search', '$daily_history'
);";
With insert of 14 columns and their values.
But sometimes I need to insert less columns/values and let MYSQL set default values for not listed columns. For Example, I want to insert only 5 columns.
$q = "INSERT INTO `$tname` (`phone`,`location`, `pageviews`, `rating`) VALUES (
'$main_number', '$number_advanced_info[location]', '$searches_comments[searches]', '$rating'
);";
Is there some CLASS or any solution like binding values which will automatically build query depending which values are not NULL?
I need some kind of code:
if (!$phone) {
$columns .= "`column_name`," ;
$values .= "value";
}
Hi I am trying to add records from one table to another, once i have added a 'user' record, the table that is being selected contains rows of available security options, and the table that is being inserted to is the child table for the user, detailing security options.
I cam across this code in an earlier post, which i am sure works nicely, however i am trying to modify it so that the values from statement, includes two parts, one from the select query and one which is the key from the master record.#
This is the original code I found from this site:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
And this is what I am trying to do with it:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('".$keys["UserPk"]."', SELECT ModulePk from Global_Modules)";
CustomQuery($sql);
And this is the error I am getting:
INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('4', SELECT
ModulePk from Global_Modules)
See screenshot for further detail
Obviously I am not concating the from statement properly, but would appreciate any help?
You can insert the $keys["UserPk"] variable as if it were a constant in the SQL:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Do note that $keys["UserPk"] must be escaped before adding it into the query. In PDO, it would look like this:
$keys["UserPk"] = $pdo->quote($keys["UserPk"]);
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Could be a problem related to the double quotes sequence
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
values ('". $keys['UserPk']. "', SELECT ModulePk from Global_Modules)";
but you could use also a select insert
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
SELECT '" . $keys['UserPk']. "' , ModulePk from Global_Modules)";
Adding only new and unique records from one table to another. Limiting is a good idea to prevent it from timeout. It can be run several times until all the records copied.
First, select the latest record ID from the table to be copied:
SET #lastcopied =
(SELECT
IF(MAX(a.exp_inotech_id)>0, MAX(a.exp_inotech_id), 0) AS lastcopied
FROM
kll_export_to a
WHERE exp_tezgah = 'A2015-0056');
Then, select and add the records to the destination table:
INSERT INTO kll_export_to
(SELECT * FROM
kll_export_from f
GROUP BY f.exp_inotech_id
HAVING COUNT(f.exp_inotech_id) = 1 AND exp_tezgah = 'A2015-0056' AND f.exp_inotech_id > #lastcopied
ORDER BY exp_inotech_id
LIMIT 1000);
I have three tables in database:
trips(trip_id(pk), trip_name(unique), user_id(fk))
places(place_id(pk), place_name(unique))
trips_places_asc(trip_id(fk), place_id(fk))
Since, many trips can have many places, I have one junction table as above.
Now, if user insert places to the trip, the places will be added to places table and the trip will be associated with the places in trips_places_asc table.
So, if i write query like:
INSERT INTO places (place_name)
VALUES ('XYZ')
INSERT INTO trips (trip_name)
VALUES ('MyTrip')
Then, How to store trip_id and place_id in Junction or Association table trips_places_asc?
will I have to fire two queries? plz help.
Note: There are many questions on SO like this one and this one. but, none of them have accepted answer or not even an answer. so, plz do not mark as duplicate.
Since you have place_name and trip_name as unique just do as:
insert into trips_places_asc ( trip_id, place_id )
values ( (select trip_id from trips where trip_name = 'MyTrip'),
(select place_id from places where place_name = 'XYZ') );
Or depending what comand you are using to insert (php command I mean) you can return the ids after the inserts and use it to run an insert command with it.
It will be like: (using mysqli* functions )
$query = "INSERT INTO trips (trip_name) values ('MyTrip')";
$mysqli->query($query);
$trip_id = $mysqli->insert_id;
$query2 = "INSERT INTO places (place_name) values ('XYZ')";
$mysqli->query($query2);
$place_id = $mysqli->insert_id;
$query3 = "insert into trips_places_asc ( trip_id, place_id ) ";
$query3 .= " values ($trip_id, $place_id)";
Note, I'm doing this directly from my mind, so maybe you have to adjust some syntax error or be concerned about prepared statements.
EDIT
Though I should add the proper documentation link about this command: http://php.net/manual/en/mysqli.insert-id.php
I have the following insert statements:
$sql ="INSERT INTO `firm`(name, VAT, active) VALUES ('$name', '$VAT', '$active')";
$sql = "INSERT INTO `area`(name, hub_name, fk_hub_id) VALUES ('$areaname',(SELECT `name` from hub WHERE name = '$hub_name'), (SELECT `id` from hub WHERE name = '$hub_name'))";
$sql ="INSERT INTO 'contactdetails'
(fk_firm_id,
address_physical_line_1,
address_physical_line_2,
address_physical_line_3,
address_physical_line_4,
address_physical_line_5,
address_physical_line_6,
address_physical_line_7,
address_physical_code,
address_postal_line_1,
address_postal_line_2,
address_postal_line_3,
address_postal_line_4,
address_postal_line_5,
address_postal_line_6,
address_postal_line_7,
address_postal_code,
fax_1,
fax_2,
phone_1,
phone_2,
phone_3,
phone_4)
VALUES ( (SELECT `id`
FROM firm
WHERE name = '$name'),
'$address_physical_line_1',
'$address_physical_line_2',
'$address_physical_line_3',
'$address_physical_line_4',
'$address_physical_line_5',
'$address_physical_line_6',
'$address_physical_line_7',
'$address_physical_code',
'$address_postal_line_1',
'$address_postal_line_2',
'$address_postal_line_3',
'$address_postal_line_4',
'$address_postal_line_5',
'$address_postal_line_6',
'$address_postal_line_7',
'$address_postal_code',
'$fax_1',
'$fax_2',
'$phone_1',
'$phone_2',
'$phone_3',
'$phone_4') ";
Do i have to use transactional statement to run these three queries. I have never worked with transactional statements. The one statement is depending on values of the other ones.
MySQL has AUTO_COMMIT set to true by default. This means that every query in your script will be executed before the one right after.
This allows you to do something like :
// Here I admit that the table is empty, with an auto-incremented id.
INSERT INTO test VALUES ('', 'First');
INSERT INTO test ('', SELECT value FROM test WHERE id = "1");
Here, you will insert a first row with id=1, value="First" and then id=2, value="First".
I'm not sure to really understand your question but if you need to perform several SQL requests guaranteeing they are either all done or none done, you have to explicitly create and commit a transaction:
START TRANSACTION
INSERT ...
INSERT ...
INSERT ...
-- All is ready, apply "all at once"
COMMIT
http://dev.mysql.com/doc/refman/5.0/en/commit.html
Just to be clear (?), from inside your transaction, all the SQL statements appear to be executed "one by one as usual". But from outside world (other transactions/connections to you SQL server) no change would appear until you COMMIT your transaction -- and then all changes will appear "all at once".
I'm pulling data from a calendar feed and each event in the calendar has a unique $EventID string. I'm using PHP.
I have a SQL database with an Event_ID column. These IDs are strings. I need to be able to compare my $EventID against the Event_ID column and put in in the database if it's not there.
I have a primary key set up to auto increment in the database, and I was thinking I can set up a loop to increment through those and compare each to the $EventID, but I'm wondering if there is a better way-maybe a PHP function I don't know about?
I've got a whole lot of code, but basically I've got:
<?php
$EventID = $event->id; //This is the event ID
mysql_query("INSERT INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
?>
So how do I set up a conditional to check all the Event_IDs that are already in the database against the $EventID?
$query = "SELECT * FROM `myTable` WHERE `Event_ID`='$EventID' ";
$result = mysql_query($query);
if (!mysql_num_rows($result))
// INSERT QUERY
Check if the Event ID is present, If not insert it
You could just skip the "Select" query and do an "INSERT IGNORE" instead:
mysql_query("INSERT IGNORE INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
this will leave existing Event_id's, and just add new records if required.