dtwxmn8741 2019-05-07 08:39
浏览 52

如何使API PHP检查该值是否存在于另一个表中然后插入?

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?

  • 写回答

1条回答 默认 最新

  • dongteng0748 2019-05-07 09:20
    关注

    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);
    }
    
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算