我有以下代码连接mysql数据库和android。
$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);
通过上面的代码,我可以从php端接收响应。但是,没有收到以下答复。
$response["found"] = "i am here";
如果从上面的代码中看到,基本上肯定会调用函数recordexists()。但是,当我模拟android应用程序时,响应“我在这里”不是用json编码的。有什么问题吗?
2条答案
按热度按时间9fkzdhlc1#
尝试在所有函数之上声明响应变量。所以加上
$response=array();
在文件的上面。您可以在这里了解php变量的作用域:https://secure.php.net/manual/en/language.variables.scope.php
ikfrs5lh2#
连接变量存在变量范围问题。将连接变量作为参数传递。
还可以使用准备好的语句来防止sql注入攻击。