【发布时间】:2020-03-13 03:28:51
【问题描述】:
+----+--------+----------+---------------+---------+
| id | userId | friendId | friendRequest | friends |
+----+--------+----------+---------------+---------+
| 1 | 1 | 3 | true | false |
+----+--------+----------+---------------+---------+
这就是我想要的。但是,在页面刷新时,似乎如果您请求 ANYONE 作为朋友,它会以某种方式将每个用户返回为 '$friendRequest' = true 和 '$friends' = false,尽管数据库根本没有列出这些用户......
朋友.php
// Connect to USERS table
$userId = $_SESSION['id'];
$con = mysqli_connect("localhost", "root", "admin123", "master");
$sql = "SELECT * FROM users ORDER BY id DESC";
$result = mysqli_query($con, $sql);
// Connect to FRIENDS table
$sqli = $con->query("SELECT * FROM friends");
$data = $sqli->fetch_array();
$friendRequest = $data['friendRequest'];
$friends = $data['friends'];
// Build USERS table
while ($row = mysqli_fetch_array($result)) {
$profile = $row['profile'];
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$city = $row['city'];
$state = $row['state'];
$bio = $row['bio'];
// Exclude user profile, current friends, and active friend requests
if ($id !== $userId && $friends !== "true" && $friendRequest !== "true") {
echo "
<div class='card m-0'>
<div class='text-center align-middle bg-white pt-3 pb-3'>
<img class='circle border mx-auto' style='width: 100px; height: 100px; object-fit: cover;' src='profile_pics/" . $profile . "'>
<h4 class='text-black font-weight-bolder'>" . $firstName . " " . $lastName . "</h4>
<div class='h7'><i class='fas fa-map-marker-alt text-danger'></i> " . $city . ", " . $state . "</div>
<form action='friends.php' method='post'>
<a href='request.php?id=" . $id . "' class='btn btn-primary mx-auto mt-3'>Send Friend Request</a>
</form>
</div>
</div>";
} else {
echo "Friend request: " . $friendRequest . "<br>Friends? " . $friends . "<br>";
}
}
request.php
<?php
require "functions.php";
require "logincheck.php";
$userId = $_SESSION['id'];
$friendId = $_GET['id'];
$con = mysqli_connect("localhost", "root", "", "master");
$sqli = ("INSERT INTO friends (userId, friendId, friendRequest, friends) VALUES ('$userId', '$friendId', 'true', 'false')");
mysqli_query($con, $sqli);
header("Location: friends.php");
?>
【问题讨论】:
-
为什么使用两种不同的方法连接数据库?这很令人困惑,两种 me 方法都不安全。
-
好吧——即便如此,我还是很困惑。应该是什么输出?实际输出是多少?
-
警告:您对SQL Injections 持开放态度,应该使用参数化的prepared statements,而不是手动构建查询。它们由PDO 或MySQLi 提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data。 Escaping is not enough!