我需要在数组中存储列'following'的值。但是,我无法弄清楚这段代码有什么问题。
session_start();
$connect = mysqli_connect("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysql_query("SELECT * FROM Followers WHERE user='$user'");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row['following'];
}
答案 0 :(得分:0)
使用关节更容易,效率更高:
Select * from message left join followers on followers.following=Messages.user where Follower.user=...
HTH 此致
答案 1 :(得分:0)
如果您忘记忘记“'”或“”“甚至”\“之类的字符,您的解决方案将遇到问题。
如果我是你,我会以这种方式合并到子查询中:
$sql = "SELECT * FROM Messages WHERE user IN
(SELECT * FROM Followers WHERE user='$user')"
$result = mysqli_query($connect, $sql );
喝彩!
答案 2 :(得分:0)
替换下面的内容
mysql_fetch_array($result)
与mysqli_fetch_array($result)
希望它有效!
答案 3 :(得分:0)
试试这个
session_start();
$connect = new mysqli("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysqli_query($connect,"SELECT * FROM Followers WHERE user='$user'");
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[] = $row['following'];
}
答案 4 :(得分:0)
正如所指出的,你应该使用prepared statement
来避免令人讨厌的SQL注入。由于唯一使用的字段是follower
限制返回的列(使用下面的表示法更容易使用 - 尤其是bind_result
)
session_start();
$data = array();
$db = new mysqli("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$sql='select `following` from `followers` where user=?';
$stmt=$db->prepare($sql);
if( $stmt ){
$stmt->bind_param('s',$user);
$res=$stmt->execute();
if( $res ){
$stmt->bind_result($follower);
while( $stmt->fetch() ){
$data[]=$follower;
}
$stmt->free_result();
$stmt->close();
}
}
$db->close();
答案 5 :(得分:0)
代码中有3个错误:
1.mysql_query()已被弃用,可能会出错,因此请使用mysqli_query(),它需要2个参数连接和查询。
2.您的查询因为字符串而没有收到用户变量值
3.你的行不是一个可以获得以下值的关联数组,所以请改用mysqli_fetch_assoc()。
您可以使用以下代码:
$connect = mysqli_connect("localhost", "root", "root", "user1");
$user = $_SESSION['username'];
$result = mysqli_query($connect,"SELECT * FROM followers WHERE user='".$user."'");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row['following'];
}