开发者

mysql use fields value while insert a record

A simple question!:

Can I use my field value in an insert query?

For example, I've a field named id, it is an auto_increment field. i want to add this field value to another 开发者_JS百科field. while I'm inserting it.

A simple php code of my need:

$query_1 = mysql_query("INSERT INTO table (name) VALUES ('abcd')"); // id automatically increment
$query_2 = mysql_query("SELECT id FROM table WHERE name = 'abcd'"); // selects previous id
// fetches result //
$query_3 = mysql_query("UPDATE table SET code = '" . $id + 1000 . "' WHERE id = '" . $id . "');

Can you convert it to just 1 query?

Thanks ...


I don't think you can do it in one query but you can do it in 2 for sure:

mysql_query("INSERT INTO table (name) VALUES ('abcd')"); 
$id = mysql_insert_id();
mysql_query("UPDATE table SET code = '" . $id + 1000 . "' WHERE id = '" . $id . "');


Here's how you do it with one query:

$query_1 = "INSERT INTO table (note) VALUES ('abcd'); UPDATE table SET code = LAST_INSERT_ID() + 1000 where id = LAST_INSERT_ID()";

I can't remember if mysql allows multiple queries in one command - I think maybe not, so try this:

$query_1 = "INSERT INTO table (note) VALUES ('abcd')";
$query_2 = "UPDATE table SET code = id + 1000 where id = LAST_INSERT_ID()";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜