【问题标题】:Check and Return Value in Mysqli_query在 Mysqli_query 中检查并返回值
【发布时间】:2017-09-28 18:14:41
【问题描述】:

我是一名 Android 开发人员,正在尝试使用 PHP 和 Mysqli 为注册用户制作一个 API。我制作了如下 API

<?php 
    include("dbconnection.php");
    $email= $_GET['email'];
    $query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
    if (!$query){
       die('Error: ' . mysqli_error($con));
    }
    if(mysqli_num_rows($query) > 0){
       $response='success';
    }else{
       $sql = "INSERT INTO tbl_user(email)VALUES ('".$email."')";
       if (mysqli_query($conn, $sql)) {
          $response='success';
       }else {
          $response='error';
       }
    } 
    echo json_encode($response);
?>

基本上我将电子邮件作为参数传递,例如 example.com/login?=abc@gmail.com 我想检查电子邮件是否已经在数据库表中。如果电子邮件存在于数据库中,我想返回 user_id 作为响应,如果电子邮件不在数据库中,我想将该电子邮件添加到数据库中并返回 user_id。我已经按照我的要求使 API 工作正常,但我不知道如何返回位于该电子邮件中的 user_id。让我知道是否有人可以给我解决我的难题的想法。谢谢

【问题讨论】:

标签: php android mysql mysqli


【解决方案1】:

下面的代码将创建一个包含 message 和 user_id 的数组。

 include("dbconnection.php");
    $email= $_GET['email'];
    $query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
    if (!$query){
       die('Error: ' . mysqli_error($con));
    }
    if(mysqli_num_rows($query) > 0){
       // assign message to response array
       $response['message']='success';
       // Get the results data
       while($row = mysqli_fetch_assoc($query)) {
          // assign user_id to response array
          $response['user_id'] = $row['user_id'];
       }
    }else{
       $sql = "INSERT INTO tbl_user(email) VALUES ('".$email."')";
       if (mysqli_query($conn, $sql)) {
          $response['message']='success';
          // assign last inserted id to response array
          $response['user_id'] = mysqli_insert_id($conn);
       }else {
          $response['message']='error';
       }
    } 
    echo json_encode($response);

Prepared statements 可帮助您保护您的 SQL 语句免受 SQL 注入攻击。

【讨论】:

  • 嗨!谢谢....它可以正常添加新记录。但是如果电子邮件存在,它会给我一个名为警告的错误:mysqli_fetch_assoc() 期望参数 1 为 mysqli_result,在“while($row = mysqli_fetch_assoc($result)) {”中给出 null。谢谢
  • 这些查询不安全。
【解决方案2】:

首先,你应该使用PreparedStatement来避免sql注入。

然后,第二个你可以使用 PDO::lastInsertId()

【讨论】:

  • 这个答案开始提供很好的建议,但并没有真正慷慨地贯彻到底。可惜我不能紫外线。
猜你喜欢
  • 2013-06-04
  • 1970-01-01
  • 2015-05-09
  • 2015-07-12
  • 2014-10-29
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多