$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: contact@email.com';
$to = $email;
$subject = "Confirmation";
$message = "Hi, $username. You're registred in Site. Link for confirmation: http://site.com/confirm/**".mysql_insert_id()."**";
mail($to, $subject, $message, $headers);
$query = mysql_query("insert into usr_users(username, password, email, avator, pin) values('$username', '$password', '$email', '$img', '$pin')");
$query2 = mysql_query("insert into usr_confirm(user_name, user_id, active, data) values('$username', '".mysql_insert_id()."', '$active', '$senha')");
echo"Success!</br>";
The second mysql_insert_id() (line 9) is correct! But the first mysql_insert_id() (line 6) return 0 in e-mail box.
Per the manual,
mysql_insert_id()will return0if the last statement doesn’t generate anAUTO_INCREMENTvalue:You’re first using the
mysql_insert_id()call before you’ve inserted any records, so the result has to be0(unless there’s a call before this somewhere else in your code -t hen you’d actually be getting skewed results). Try moving your mail-related calls to below your insert statements, giving you:If you still receive the error after this change, you will need to confirm that your primary-key field on the
usr_confirmtable is correctly configured withauto_increment. Also, if it is setup properly, try passing the connection-variable to the function, such asmysql_insert_id($conn);where$connis the result of yourmysql_connect()call.Site note (not answer specific)
Your code is extremely prone to SQL Injection; you’re not escaping any of the values. Rather than go into what SQL Injection is, I would much rather direct you to use Prepared Statements.
In addition, PHP is deprecating the
mysql_methods in favor for themysqli_andPDOmethods. Both of these support prepared statements and I would recommend for you to look into these.In the interim, please consider wrapping your variables with
mysql_real_escape_string(), such as: