0

I want to make API for android. I'm working on a form in php that inserts data to MySQL, but before the data is inserted there is a field that must be checked in another table before inserting. If this value exist in the other table, then the data is inserted in the main table, if not, then data is not inserted.

This Is my php

<?php

if($_SERVER['REQUEST_METHOD']=='POST') {

$response = array();

$username = $_POST['username'];
$SN = $_POST['SN'];


require_once('dbConnect.php');

$sql = "SELECT * FROM produk WHERE SN ='$SN'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
 $response["value"] = 0;
 $sql = "INSERT INTO farm (username,SN) VALUES('$username','$SN')";
 $response["message"] = "Successful";
 echo json_encode($response);
} else {
   $response["value"] = 1;
   $response["message"] = "oops! Try Again";
   echo json_encode($response);

}

mysqli_close($con);
} else {
$response["value"] = 0;
$response["message"] = "oops! Try Again";
echo json_encode($response);
}

?>

How solve the code?

  • checking table first get all data of that table in for loop after check your new value in this loop if exists then perform your code if not then also perform you code – Full Stop May 07 '19 at 08:45
  • You should also look into how to prevent sql injections. Your code can be exploited. See here: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – FMK May 07 '19 at 08:46
  • i want insert username and serial number into farm table if serial number is exist on product table – Faadhilah Faridh May 07 '19 at 08:59

1 Answers1

0

Try with below code, you need to put a condition to check the value exists in another table. Check mysqli_num_rows for the other table, if num_rows > 0 then insert into main table:

<?php

if($_SERVER['REQUEST_METHOD']=='POST') {

$response = array();

$username = $_POST['username'];
$SN = $_POST['SN'];


require_once('dbConnect.php');

$sql = "SELECT * FROM produk WHERE SN ='$SN'";
$check = mysqli_num_rows(mysqli_query($con,$sql));
if($check > 0){
 $response["value"] = 0;
 $sql = "INSERT INTO farm (username,SN) VALUES('$username','$SN')";
 $response["message"] = "Successful";
 echo json_encode($response);
} else {
   $response["value"] = 1;
   $response["message"] = "oops! Try Again";
   echo json_encode($response);

}

mysqli_close($con);
} else {
$response["value"] = 0;
$response["message"] = "oops! Try Again";
echo json_encode($response);
}

?>