Search code examples
phpmysqlsubmitechoauto-increment

after submit, echo mysql id of user


I have a bit of a problem and i'm really sorry to bug you but i've looked a lot and can't find a good answer. When a user submits on my page the data goes to me mysql server and gets stored and mysql gives it an auto_increment id. When the user submits, i want the id that mysql assigns to their submission to be echoed. Can anyone help?

Here is my code:

<?php $con=mysqli_connect('host','username','pass','db');
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO subusers (username, date, ip)
VALUES
('$_POST[username]','$_POST[date]','$_POST[ip]')";
if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added", mysql_insert_id();
mysqli_close($con);
?>

thats the code that send their data to the server, when it does and gets an id from the server i want it to echo the id.


Solution

  • The problem is that you are mixing mysql and mysqli syntax.

    You should replace mysql_insert_id() in your code with mysqli_insert_id($con).

    Now you should have the correct count.

    Apart from that you have an sql injection problem. You should switch to prepared statements with bound variables instead of injecting your $_POST variables directly in your query.