-1

I have this query which I would like to insert data into two tables.

It inserts into the first but not the second, any ideas why?

$result1 = mysql_query("INSERT INTO entries (UserID, FirstName, LastName, EmailAddress, TelephoneNumber, Image, Status) VALUES ('NULL', '$FirstName', '$LastName', '$EmailAddress', '$TelephoneNumber', '$ran2$ext', '0')") ;

$newid = mysql_insert_id($result1);

$result2 = mysql_query("INSERT INTO voting (id, EntryID, item, vote, nvotes) VALUES ('NULL', $newid, 'vt_img353', '0', '0')") ;
4

3 回答 3

1

If you are trying to insert a null, don't use quotes around it:

INSERT INTO voting 
    (id, EntryID, item, vote, nvotes) 
    VALUES (NULL, $newid, 'vt_img353', '0', '0')

As juergen d correctly points out, if you don't want to insert a column you can just skip it, but this will only work if you name the columns you are inserting first. It won't work in:

INSERT INTO voting 
    VALUES (NULL, $newid, 'vt_img353', '0', '0')
于 2012-09-15T10:43:50.767 回答
1
$result2 = mysql_query("INSERT INTO voting (EntryID, item, vote, nvotes) VALUES ($newid, 'vt_img353', '0', '0')") ;

If you don't want to set a column you can leave it. Your id column is probably an auto-increment column. If you leave it from your insert statement it will be filled automatically.

And if you want to set it explicitly to NULLthen leave the quotes. Otherwise you would set the column to the string NULL

于 2012-09-15T10:44:50.430 回答
0

本身不是答案,但同样非常有用。为了使您的代码更具可读性 - 无论是在您的 IDE 中还是在诸如此类的论坛上 - 请记住您可以缩进它。尝试这个:

$result1 = mysql_query("
    INSERT INTO entries (
        UserID, FirstName, LastName,
        EmailAddress, TelephoneNumber, Image,
        Status
    )
    VALUES (
        NULL, '$FirstName', '$LastName',
        '$EmailAddress', '$TelephoneNumber', '$ran2$ext',
        '0'
    )
");

这有助于保持合理的行长(我使用 120 个字符),并有助于减少隐藏在屏幕右侧的错误。

于 2012-09-15T11:06:10.370 回答