我正在尝试为我的移动后端制作一个php REST API来与MySQL数据库进行交互。我已经写出以下代码来尝试从MySQL查询中检索数据:
<?php include "FILE WITH DB_INFO"; ?>
<html>
<body>
<h1>Testing page</h1>
<?php
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL" . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
if (strlen($username_query)) {
doesUsernameExist($connection, $username_query);
}
doesUsernameExist($connection, $username_query);
$username_query = $_GET['usernameToQuery'];
echo($_GET['usernameToQuery']);
function doesUsernameExist($connection, $username) {
$u = mysqli_real_escape_string($connection, $username);
$query = "SELECT username from users WHERE username = ('$u');";
if (!mysqli_query($connection, $query)) {
$response = array("success" => false, "message" => mysqli_error($connection), "sqlerrno" => mysqli_errno($connection), "sqlstate" => mysqli_sqlstate($connection));
echo json_encode($response);
} else {
$sth = mysqli_query($connection, $query);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
$response = array("success" => true);
echo json_encode($rows);
}
}
?>
这是实际请求的样子:http://my_ec2_instance/DoesUsernameExist.php?usernameToQuery=lmao
。
这是通过POSTMAN发送的。
因为我使用的MySQL数据库包含值为lmao
的用户名,所以php函数应该返回一个非空的数组。但是json_encode($rows);
行返回一个空数组[]
。我究竟做错了什么。
答案 0 :(得分:1)
您似乎在doUsernameExiste()
之前和strlen
之前使用变量$username_query
。但是你只能在之后定义$username_query
。
你应该先做好准备。把它放在你的mysqli_select_db
$username_query = $_GET['usernameToQuery'];