我的php函数不会被调用

时间:2018-08-13 22:01:55

标签: php android mysql string

我有以下代码可以在mysql数据库和android之间建立连接。

Running 1 test case...
123
*** No errors detected

从上面的代码中,我可以接收来自php端的响应。但是未收到以下响应。

$conn = mysqli_connect($servername, $username, $password, $database);

//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error
if ($conn) {
  $response["Connection"] = 1;
}
else {
  $response["Connection"] = 0;
}
$userID= $_POST['user_id'];

function recordExists() {
  $query = "SELECT * FROM user_table";
  $result = mysqli_query($conn, $query);
  $response["found"] = "i am here";

  while($row=mysqli_fetch_array($result)){
    $response["found"] = $row['user_id'];
    if($row['user_id']==$userID){
      return true;
    }
  }
  return false;

  // $result_num_rows = mysqli_num_rows($result);
  //
  // if($result_num_rows>0) {
  //   return true; // The record(s) do exist
  // }
  // return false; // No record found
}
$exists=recordExists();
if ($exists) {
  $query = "SELECT * FROM user_table WHERE $userID";
  $result = mysqli_query($conn, $query);
  $row = mysqli_fetch_array ($result);
  $Nickname = array();
  if ($row['nickname'] == NULL){
    array_push($response["nickname"], "False");
  }else{
    array_push($response["nickname"], $row["nickname"]);
  }
  $response["Sync"] = "Already Added";
  echo (json_encode($response));
} else {
  $UserToBeAdded= $_POST['user_id'];
  $NameToBeAdded= $_POST['name'];
  $EmailToBeAdded= $_POST['email'];
  $UserToBeAdded2 = mysqli_real_escape_string($conn, $UserToBeAdded);
  $NameToBeAdded2 = mysqli_real_escape_string($conn, $NameToBeAdded);
  $EmailToBeAdded2 = mysqli_real_escape_string($conn, $EmailToBeAdded);
  $sql_query = "insert into user_table (user_id, name, email) values ('$UserToBeAdded2', '$NameToBeAdded2', '$EmailToBeAdded2');";
  mysqli_query($conn, $sql_query);
  $response["ID"] = $UserToBeAdded2;
  $response["Name"] = $NameToBeAdded2;
  $response["Email"] = $EmailToBeAdded2;
  $response["Sync"] = "Just Added";
  $response["nickname"] = "False";
  echo (json_encode($response));
}

mysqli_close($conn);

如果您从上面的代码中看到,基本上肯定会调用函数recordExists()。但是,当我模拟android应用时,响应“我在这里”未以JSON编码。有什么问题吗?

2 个答案:

答案 0 :(得分:0)

尝试在所有函数上方声明响应变量。因此,请在文件顶部添加$response=array();

在这里您可以阅读有关php变量范围的信息: https://secure.php.net/manual/en/language.variables.scope.php

答案 1 :(得分:0)

连接变量存在变量范围问题。将连接变量作为参数传递。

recordExists($conn);

还使用准备好的语句来防止sql注入攻击。