473,598 Members | 3,246 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Perl/mysql: retrieve id and name for record already in the database or create newname

5 New Member
Hi mysql and perl experts,

I am new to both perl and mysql, and I am trying to populate a database that I had previously created in mysql. I am stuck on a step and don't really know how to move on and would REALLY appreciate suggestions...
I need to insert new data on individuals which refers to another table (called "location") through a foreign key, but I first need to check whether this location has already been entered: if it has already been entered then take the location_id and use this to enter the individual data which refers to this location, otherwise create a new location_id. Then, if there is no location_name, then enter an invented one from the last_inserted id (which differentiates the ones that already had a name from the ones that did not).

This is what the mysql tables look like:
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----Table_1-----------
LOCATION_ID (AUTO-INCREMENT) LOCATION SITE NAME

1 1234 4 syd
2 1235 4 brux
3 1236 5 temp_1

-----Table_2-----------
ASSIGN_ID (AUTO-INCREMENT) LOCATION_ID (FOREIGN KEY) ASSIGN
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
And this is where I got stuck and what I am trying to do with the perl script:

I am looping through my data file and creating these variables for the columns in Table 1 and Table 2:
my $location = shift(@fields);
my $site = shift(@fields);
my $name = shift(@fields);
my $assign = shift(@fields);


#see if record exists
my($id, $location_name) = $dbh->selectrow_arra y(qq{SELECT location_id, location_name FROM location WHERE location = $location && site = $site });

## If there is already an entry, then use the location_id and name entered in Table 1 (and if the name is not entered already in the database, then enter this name) --- In this step I do not need to do anything in table_1, but I need to select this location_id (and name if there is one), maybe using a “selectrow_arra y”?

## If there is not an entry, then insert the new data into Table_1 using the “name” if there is one, and if there is no name entering the new data in Table_1 using a temporary name such as “temp_1”.
# I DO NOT KNOW HOW TO DO THIS....MAYBE SOMETHING LIKE THIS? ...
if(!$id){
my $sth = $dbh->do(qq{
INSERT location
SET location = $location, site = $site, location_name = '$location_name ',
});
}
elsif(!$id){
my $sth = $dbh->do(qq{
UPDATE location
SET location_name = '$location_name '
WHERE location_id = $id
});
}

$dbh->do(q{INSERT INTO table_1 (location, site, name) VALUES (?, ?, ?)}, undef, $location, $site, $name);
# get the primary key value of the inserted record of Table 1:
my $location_id = $dbh->selectrow_arra y (qq (select last_insert_id( ) ));

##And if there is no name, then maybe do:
update location where location_id = last_insert location_name = "temp_$id"

## Then enter the new data for Table2, using either the newly entered location_id or the location_id that was fetched in step 3…

$dbh->do (qq (insert into table_2 (location_id, assign) values (?,?) ), undef, $location_id, $assign);


Thank you so much for any help!! I really appreciate any suggestions...
-f
Mar 8 '11 #1
2 2139
code green
1,726 Recognized Expert Top Contributor
Rather than all this code could you make use of
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO table (..) VALUES (..)
  2.   ON DUPLICATE KEY UPDATE ....
Mar 8 '11 #2
Francesca
5 New Member
Hi code green,

Thank you for your reply.
I am not sure about the benefits of using the "on duplicate key update", and since I am quite confused I thought to work an "insert" even if it is not the most practical way...But I will check it out!
I could make the code work by creating the query using "selectrow_arra y" and then repeating all the conditions if there is an entry, and again if there is no entry...

-f
Mar 8 '11 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

1
11722
by: Matt | last post by:
how to get the last record from database without looping? Whenever the user need to insert a new record to the database, it just increment the id field by one from the last record. I tried objRS.MoveLast, but it wont work.
4
4168
by: Mmm_moo_cows | last post by:
Hi, I'm new to the world of mysql and i'm having alot of trouble with it. All i want to do is create a page with a response form, e.g. name etc and some radio buttons (part of a uni project, but i'm a chemist!) and a submit button to save the data in a database. I installed iss microsoft web server and php and the mysql database. Php works fine, i could write to a text file, and using phpinfo(); it
4
3847
by: Jim in Arizona | last post by:
I'm wanting to do a simple controlled voting page. I too our webserver off anonymous and everyone who accesses the website is a domain authenticated user. I've already done some control structure pages based on Request.ServerVariables("AUTH_USER"), which works great. That's also how I would do this page, in my basic thinking. My idea is to have an access database with two tables. One table will have the vote written to it and the other...
4
7355
by: Akinyemi | last post by:
I am currently using Visual Basic 6 to write a Payroll Program. I created a Database with one Table in Microsoft Access that ships with Office 2000. The name of the Database is "Payroll", and the name of the Table is "Emoluments". I then usedcActiveX Data Control (ADO) to connect the Text Box controls on the Form to the Table. I have the following fields in the Table and the Form: Assessment Year, Tax Payer ID, Name, Address, Basic Salary,...
11
3756
by: kennthompson | last post by:
Trouble passing mysql table name in php. If I use an existing table name already defined everything works fine as the following script illustrates. <?php function fms_get_info() { $result = mysql_query("select * from $tableInfo") ; for ($i = 0; $i < mysql_num_rows($result); $i++) {
2
7030
josie23
by: josie23 | last post by:
Egad, I'm not a coder/programmer by nature or occupation but understand things like html and css and a small amount of perl. So, basically, I'm a perl/mysql imbecile. But, I've been trying to find syntax to insert values into a mysql database table. I'm able to use the below syntax to insert hard-coded values like 'josie' and 'smith' but can't find working syntax to insert $scalar data from another file (which is really what perl-mysql is...
1
1459
by: raaaz | last post by:
Hi dears, I am adding a record in Access database using AddNew method of recordset. here is the code of the page .. <% Set RsLibBuild = Server.CreateObject ("ADODB.Recordset") RsLibBuild.ActiveConnection = conn RsLibBuild.LockType = 2 RsLibBuild.CursorType = 1 RsLibBuild.Open "select * from tblbuilding where building_name='" & request.Form ("buildingname") & "' and area_name='" & request.Form ("areaname") & "' and...
3
3350
by: Surya | last post by:
Dear All, I have problem on inserting a record to database..Although it looked easy.. i have caught up with following issue .. please go ahead and help me to find solution I Need to insert records to a data base,for which i am using Typed dataSet.(I used DataSet Designer to create one) Then created a table adapter in which i have written query for INSERT , & set Database Direct property to true.(I didnt use a seperate methods for...
1
9747
by: Carmine [www.thetotalsite.it] | last post by:
Hi, I am using ASP.Net 2.0 with the MySQL Connector .Net 5.1.2.2. I added these lines to the web.config to make the connector.net able to handle the SqlConnection object (and so to bind it to a grinview/formview etc.): <DbProviderFactories> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data,
10
6238
by: puT3 | last post by:
I want to get the value from Product_Price field which it will display it record on a text box based on a product that is selected from a list box. Product Table Product_ID Product_Name Product_Price Product_Quantity Product_Picture
0
7899
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8397
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8264
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6718
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5438
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3897
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2412
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1504
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1250
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.