Re: inset data to multiple tables

From: Date: Mon, 16 Feb 2009 20:22:16 +0000
Subject: Re: inset data to multiple tables
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-288370@lists.php.net to get a copy of this message
'Twas brillig, and PJ at 16/02/09 19:57 did gyre and gimble:
Questions: 1. Do we really need the statements - $result1 = mysql_query($sql1, $db); ? Why? What purpose do they serve?
These statements send your SQL to the server. Without them you are just assigning and SQL command to a variable.... so they are really rather important :p
2. How can one use "mysql_insert_id()" to insert data into multiple tables? Why would you need to insert an id - especially since there are only 2 fields in the pulblishers table (above) - id (auto-increment) and publishers? As I ;understand it, when the id field is auto-increment, a simple INSERT INTO publishers (publisher) VALUES ('$publisherIN') works fine (but not above) Can somebody suggest anything? TIA
Short answer, you can't! It's not what it's for! You have to do your insert first (with mysql_query() as you did above), and then call $my_generated_id = mysql_insert_id(); This will fill the variable $my_generated_id with the value of the auto_increment field in your table from the last call to mysql_query with an INSERT statement. Also, you are possibly running risks above if you do not properly escape your variables: e.g. You have: $sql1 = "INSERT INTO authors (first_name, last_name) VALUES ('$first_nameIN', '$last_nameIN')"; Your examples do not show where the values came from but if it's directly from a form post or similar, if I put the value: 'blah','blah'); DELETE FROM authors; The query generated could be: INSERT INTO authors(firstname,lastname) VALUES ('blah','blah'); DELETE FROM authors;..... Obviously this is a massive security risk and is generally referred to as "SQL Injection Attacks". You should look into using the function mysql_real_escape_string() to escape all your inputs. Col -- Colin Guthrie gmane(at)colin.guthr.ie http://colin.guthr.ie/ Day Job: Tribalogic Limited [http://www.tribalogic.net/] Open Source: Mandriva Linux Contributor [http://www.mandriva.com/] PulseAudio Hacker [http://www.pulseaudio.org/] Trac Hacker [http://trac.edgewall.org/]

« previous php.general (#288370) next »