When Inserting data into SQL it inserts two into rows, and I don't know why.
most probably of the if statement I added after the results you can find it as my comment:
// id_no update
And I used the select query two times to fetch the id and make it an auto-increment thing.
my table:
<?PHP
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
?>
<?PHP
if(isset($_POST['add_id']))
{
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if(mysqli_query($con,$sql))
{
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
}
else
{
echo "Record Faileddd";
}
if($result)
{
$success="Post has been added successfully";
} else
{
$error="Something went wrong!";
}
$id_no = '';
}
?>
CodePudding user response:
You should check if $result
is truthy to see if the insertion succeded (without running another query):
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if($result)
{
...
}