我想为Android创建API。我正在使用php中的表单将数据插入MySQL,但是在插入数据之前,必须先在另一个表中检查该字段,然后再插入。如果该值存在于另一个表中,则将数据插入到主表中;如果不存在,则不插入数据。
这是我的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);
}
?>
如何解决代码?
答案 0 :(得分:0)
尝试下面的代码,您需要设置条件以检查另一个表中是否存在该值。检查mysqli_num_rows是否有其他表,如果num_rows> 0,则插入主表:
<?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);
}
?>