1

Well I found something that works perfectly but it looks ugly Is it possible to do this in one query?

    $query = "INSERT INTO page(page_name, page_weight)
              VALUES('".mysql_real_escape_string($_POST['name'])."', '".mysql_real_escape_string($_POST['weight'])."')";
    $result = mysql_query($query);

    $query2 = "SELECT page_id FROM page WHERE page_id = (SELECT MAX(page_id)  FROM page)";
    $result2 = mysql_query($query2);
    while($row = mysql_fetch_assoc($result2))
    {
        $query3 = "INSERT INTO content(page_id, content_type)
                   VALUES('".$row['page_id']."', '".mysql_real_escape_string($_POST['type'])."')";
        $result3 = mysql_query($query3);
    }

The page_id from page is auto incremented but page_id from content isn't, is it possible to link them in any way?

Edit:

Thanks PLB now I've got this instead now

    $query = "INSERT INTO page(page_name, page_weight)
                VALUES('".mysql_real_escape_string($_POST['name'])."', '".mysql_real_escape_string($_POST['weight'])."')";
    $result = mysql_query($query);

    $query3 = "INSERT INTO content(page_id, content_type)
                VALUES('".mysql_insert_id()."', '".mysql_real_escape_string($_POST['type'])."')";
    $result3 = mysql_query($query3);

Is it possible to make 1 query of though?

j0k
  • 22,600
  • 28
  • 79
  • 90
Sinan Samet
  • 6,432
  • 12
  • 50
  • 93

1 Answers1

0

mysql_insert_id(); returns last inserted id. Using it you can remove select query like this:

    $query = "INSERT INTO page(page_name, page_weight)
                VALUES('".mysql_real_escape_string($_POST['name'])."', '".mysql_real_escape_string($_POST['weight'])."')";
    $result = mysql_query($query);

        $query3 = "INSERT INTO content(page_id, content_type)
                    VALUES('".mysql_insert_id()."', '".mysql_real_escape_string($_POST['type'])."')";
        $result3 = mysql_query($query3);

But I suggest stop using mysql_* functions and try mysqli_* or PDO

Leri
  • 12,367
  • 7
  • 43
  • 60
  • That helped but is it possible to make just one query of it? Like selecting 2 tables in one insert. Or does this look fine? And for the msqli thing. This is a schoolproject and our teacher does not want to start using mysqli yet. – Sinan Samet May 28 '12 at 13:28
  • @SinanSamet MySql does not support multi-table insertion in a single [INSERT statement](http://dev.mysql.com/doc/refman/5.1/en/insert.html) – Leri May 28 '12 at 13:30
  • Okay thanks a lot this was useful! And @jugnu I will take a look at the relation thing I suppose that would be more functional, thank you! – Sinan Samet May 28 '12 at 13:31