我试图使用Slim Framework获取json文件。我尝试的代码如下所述
$app->get('/forum/:id', function ($id) {
$user_name = "abc";
$password = "123";
$database = "test";
$server = "localhost";
$db_handle = mysqli_connect($server, $user_name, $password);
mysqli_set_charset($db_handle, "utf8");
mysqli_select_db($db_handle, $database);
$arr = array();
$SQL = "Select y123_forum.post_id, y123_forum.posttext FROM y123_forum INNER JOIN y123_users ON y123_forum.user_id = y123_users.id WHERE type = 1 AND y123_users.email = 'id'";
$result = mysqli_query($db_handle, $SQL);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
mysqli_close($db_handle);
echo json_encode($arr);
});
浏览器上显示的输出为[]
当我在不传递参数的情况下尝试上述代码时,即
$app->get('/faqs/', function () {
$user_name = "abc";
$password = "123";
$database = "test";
$server = "localhost";
$db_handle = mysqli_connect($server, $user_name, $password);
mysqli_set_charset($db_handle, "utf8");
mysqli_select_db($db_handle, $database);
$arr = array();
$SQL = Select y123_forum.post_id, y123_forum.posttext FROM y123_forum INNER JOIN y123_users ON y123_forum.user_id = y123_users.id WHERE type = 1 AND y123_users.email = 'abc@gmail.com'"
$result = mysqli_query($db_handle, $SQL);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
mysqli_close($db_handle);
echo json_encode($arr);
});
然后它工作正常
我如何解决这个问题,我需要通过传递数据库中的任何电子邮件ID来获取json文件
答案 0 :(得分:1)
您忘记参数中的$,它认为您正在寻找'id'的电子邮件地址,而不是$ id的内容。
SELECT * FROM y123_forum WHERE email = '$id';
请注意,这是将参数传递给SQL查询的一种可怕,糟糕,不安全的方法。正确的方法是参数化您的查询并以这种方式执行:
$SQL = 'SELECT * FROM y123_forum WHERE email = ?';
$stmt = mysqli_stmt_init($db_handle);
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, 's', $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
}
mysql_stmt_bind_param
中的's'告诉驱动程序你的$ id变量应该被视为一个字符串,并适当地转义它。