I am trying to make a php REST API for my mobile backend to interact with a MySQL database. I have written out the following code to try and retrieve data from a MySQL query:
我正在尝试为我的移动后端制作一个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);
}
}
?>
This is what the actual request looks like: http://my_ec2_instance/DoesUsernameExist.php?usernameToQuery=lmao
. This is sent through POSTMAN.
这是实际请求的样子:http://my_ec2_instance/DoesUsernameExist.php?usernameToQuery = lmao。这是通过POSTMAN发送的。
Because the MySQL database that I am using contains usernames with the value lmao
, the php function should return an array that is not empty. But the json_encode($rows);
line returns an empty array []
. What am I doing wrong.
因为我使用的MySQL数据库包含值为lmao的用户名,所以php函数应该返回一个非空的数组。但是json_encode($ rows); line返回一个空数组[]。我究竟做错了什么。
1 个解决方案
#1
1
It seems you call doUsernameExiste()
and just before strlen
with a variable $username_query
. But you define $username_query
only after.
看来你在strlen之前使用变量$ username_query调用doUsernameExiste()。但是你只能在之后定义$ username_query。
You should first do your affectation. Put this after your line with the mysqli_select_db
你应该先做好准备。把它放在你的mysqli_select_db之后
$username_query = $_GET['usernameToQuery'];
$ username_query = $ _GET ['usernameToQuery'];
#1
1
It seems you call doUsernameExiste()
and just before strlen
with a variable $username_query
. But you define $username_query
only after.
看来你在strlen之前使用变量$ username_query调用doUsernameExiste()。但是你只能在之后定义$ username_query。
You should first do your affectation. Put this after your line with the mysqli_select_db
你应该先做好准备。把它放在你的mysqli_select_db之后
$username_query = $_GET['usernameToQuery'];
$ username_query = $ _GET ['usernameToQuery'];