开发者

About a simple MySQL records

I want to make two MySQL records in two different tables and the goal is when I make the first record to take the "id" which is A_I and to use it for the second record as a VALUE. Right now I'm just trying some things so this code is def. not working but maybe is good enough for a starting point:

mysql_select_db("chat", $db_connect);
   if($u!='null' && !empty($u)){
    $sql = "INSERT INTO users (name)  VALUES ('%s')";
    $sql = sprintf($sql,mysql_real_escape_string($u));
    mysql_query($sql);
    $result = mysql_query("SELECT id FROM users DESC LIMIT 1");
    $row = mysql_fetch_array($result);
    $uf = $row[0];
    mysql开发者_运维问答_query("INSERT INTO activeusers (au_id, login_time)  VALUES ('$uf', '1234')");
    $_SESSION['UserName']=$u;
             }
else //some other code

For some reason in the "au_id" field I alwyas get "0" as a record.


Replace:

mysql_query($sql);
$result = mysql_query("SELECT id FROM users DESC LIMIT 1");
$row = mysql_fetch_array($result);
$uf = $row[0];

With:

if(mysql_query($sql)){
   $uf = mysql_insert_id();
} else {
   //something has gone wrong, do NOT continue...
}

Your solution would've worked if you had an ORDER BY id before your DESC, but results in errors/race conditions when more people are using your code simultaneously.

Actually, you can just do this:

if(mysql_query($sql)){
    mysql_query("INSERT INTO activeusers (au_id, login_time)  VALUES (LAST_INSERT_ID(), '1234')");
}


You should use $row['id'] instead of $row[0].

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜