Jump to content


Photo

quick mysql_insert_id question


  • Please log in to reply
2 replies to this topic

#1 witt

witt
  • Members
  • PipPipPip
  • Advanced Member
  • 36 posts

Posted 28 May 2006 - 08:12 PM


$query = "INSERT INTO table_one (data) VALUES ('$data')";
$result = mysql_query ($query);

$counter = 3; 

    for ($i = 0; $i < $counter; $i++) {
                
        $query = "INSERT INTO table_two (hello, data_id) VALUES ('$hello', '??????')";
        $result = mysql_query ($query);
        
    }


So basically the first query would insert $data into table_one under the data coulmn, and insert an incrementing number under the data_id column.

What I want the second query to do is insert $hello into table_two under the hello column, and also insert the data_id generated by the first query into a column named data_id.

I'm not quite sure how to use mysql_insert_id in this case but it should be simple.

#2 witt

witt
  • Members
  • PipPipPip
  • Advanced Member
  • 36 posts

Posted 28 May 2006 - 08:40 PM

Never mind, I had it right all along. The problem was the I didn't put single quotes on the valuse I wanted to insert.

#3 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 28 May 2006 - 09:02 PM

The quotes are only mandatory with string values.

$query = "INSERT INTO table_one (data) VALUES ('$data')";
$result = mysql_query ($query);

$id = mysql_insert_id();

$counter = 3;

    for ($i = 0; $i < $counter; $i++) {
                
        $query = "INSERT INTO table_two (hello, data_id) VALUES ('$hello', $id)";
        $result = mysql_query ($query);
        
    }

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users