How to put the output query from mySQL to php int variable


I want to do a query to get the last id (int) in a table to create a new row with that last id + 1 but actually this just put all rows with the same id

my code:

$servername = "localhost";
$user = "root";
$pass = "dbpass";
$dbname = "site";
$mail = $_POST['mail'];
$password = $_POST['password'];

// Create connection
$conn = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());

$sqlID = "SELECT MAX(id) FROM `login`;";

if ($result = mysqli_query($conn, $sqlID)) {
    $id = mysqli_fetch_row($result);

settype($id, "int");
$id = $id + 1;

$sql = "INSERT INTO login (`id`,`mail`,`password`)
             VALUES ('".$id."','".$mail."','".$password."');";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);






mysqli_fetch_row returns always an array, also if there is only 1 element. So the MAX(id) in in $row[0].

Fixing this, you also don't need to use settype.




If yourid is autoincrement, change this:

$sql = "INSERT INTO login (`id`,`mail`,`password`)
         VALUES ('".$id."','".$mail."','".$password."');";


$sql = "INSERT INTO login (`mail`,`password`)
         VALUES ('".$mail."','".$password."');";

Then get rid of all code from$sqlID to$id + 1; (for tidyness)

People are also looking for solutions to the problem: php - Cookie value issue on Chrome


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.