jaja
jaja

Reputation: 1

Insert and update at the same time

I have problem need to solve: I have 2 table in MySQL named Bata and Tranport.

For table Bata I have: id (PK, AI), phone, qty, price and grandtotal.

For table Tranport I have: id(PK, AI), phone, name, address and so on.

When the user clicks submit on Bata page the data will save into the database but the phone field will be left blank. When the user clicks submit on the Tranport page it will save data into database.

The question is how can I insert phone number from Tranport field into Bata phone field where the ID is the same? I have to do this because at the end user can review their order.

This is my code for transport

<?php
error_reporting(0);
ini_set('display_errors', false);


$tranport = $_POST['Tranport'];
$name = $_POST['billName'];
$phone = $_POST['billPhone'];
$company = $_POST['billCompany'];
$address = $_POST['billAdd1']; 
$negeri = $_POST['negeri']; 
$label = $_POST['mylabel']; 
$date = $_POST['inputField'];

$input = "INSERT INTO tranport (deliverTyper , name , phone , company ,
   address , state    ,   rate , date )";

$input .= " VALUES ('$tranport', '$name', '$phone', '$company', '$address',
    '$negeri',   '    $label', '$date') "; 

require_once("connection.php");
mysqli_query($conn,$input);


$query = "INSERT INTO bata (phone) VALUES ('$phone')"; 

mysqli_query($conn,$query);


if(mysqli_affected_rows($conn) <= 0)
{
print "Unable to create account.Please <a href='tranport.php'>click here</a>to try           gain.";
}
else
{
mysqli_close($conn);
header("Location:try.php?sebab=pengguna baru");
exit();
}

 mysqli_close($conn);


  ?>    

Upvotes: 0

Views: 486

Answers (2)

Padmanathan J
Padmanathan J

Reputation: 4620

You can get the ID generated for an AUTO_INCREMENT column of the last inserted entry using mysqli_insert_id($conn).

Here is the sample code for get last insert id

<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("test_db",$con);

$sql = "INSERT INTO person VALUES ('Børge','Refsnes','Sandnes','17')";
$result = mysql_query($sql,$con);
echo "ID of last inserted record is: " . mysql_insert_id();

mysql_close($con);
?> 

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191819

You can get the ID generated for an AUTO_INCREMENT column of the last inserted entry using mysqli_insert_id($conn).


Your code is vulnerable to injection. You should use properly parameterized queries with PDO / mysqli

Upvotes: 1

Related Questions