我试图只在特定的用户名表中放置一个用户名。
现在它将所有用户名放在表格中。
代码:
$top_user_array = array('user1', 'user2', 'user3', 'user4');
$top_user_array = join("', '", $top_user_array);
$query = "SELECT * FROM users WHERE username IN ('{$top_user_array}')";
$send_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($send_query)) {
$author = $row['username'];
if(isset($_POST['create_sub'])) {
$username = $_SESSION['username'];
$query = "UPDATE users SET user_subs = CONCAT(IFNULL(user_subs,''), '{$username}' ',') WHERE username = '{$author}' ";
$create_user_sub = mysqli_query($connection, $query);
confirmQuery($create_user_sub);
$query = "UPDATE users SET user_subscriptions = CONCAT(IFNULL(user_subscriptions,''), '{$author}' ',') WHERE username = '{$username}' ";
$create_user_subscription = mysqli_query($connection, $query);
confirmQuery($create_user_subscription);
echo "Subscribed";
}
echo '<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<button type="submit" name="create_sub" class="btn btn-primary">Subscribe To '. $author; echo ' <i class="fa fa-users" aria-hidden="true"></i></button>
</div>
</form>';
}
基本示例:
如果&#34;主要用户&#34;订阅user1它会将所有用户放入&#34;主要用户&#34; user_subscriptions行而不只是将特定的用户名放在那里。
主用户订阅user1后数据库的外观
使用@Kodoyosa后
这是得到我想要的结果的代码:
$top_user_array = array('user1', 'user2', 'user3', 'user4');
$top_user_array = join("', '", $top_user_array);
$query = "SELECT * FROM users WHERE username IN ('{$top_user_array}')";
$send_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($send_query)) {
$author = $row['username'];
$author_u = str_replace(' ', '_', $author);
if(isset($_POST["create_sub_{$author_u}"])) {
$username = $_SESSION['username'];
$query = "UPDATE users SET user_subs = CONCAT(IFNULL(user_subs,''), '{$username}' ',') WHERE username = '{$author}' ";
$create_user_sub = mysqli_query($connection, $query);
confirmQuery($create_user_sub);
$query = "UPDATE users SET user_subscriptions = CONCAT(IFNULL(user_subscriptions,''), '{$author}' ',') WHERE username = '{$username}' ";
$create_user_subscription = mysqli_query($connection, $query);
confirmQuery($create_user_subscription);
echo "Subscribed";
}
echo '<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<button type="submit" name="create_sub_'.$author.'" class="btn btn-primary">Subscribe To '. $author; echo ' <i class="fa fa-users" aria-hidden="true"></i></button>
</div>
</form>';
}
答案 0 :(得分:0)
如果我说这种模式是个坏主意并且将User
表和Subscription
表
User
只有用户(id,username ...)Subscription
会有subscriber
和subscribed_to
因此,您可以轻松获取用户的订阅或订阅,而无需创建重复的信息
但也许你真的必须走这条路,所以不要接受这个建议,试试吧
所以你的问题可能来自if(isset($_POST['create_sub']))
,这对每个用户都是如此(对于每个用户都是相同的验证)。
解决方案可以是:
name="create_sub_'.$author.'"
添加到您的提交按钮isset($_POST["create_sub_{$author}"]
而非if(isset($_POST['create_sub']))
编辑:必须使用isset($_POST["create_sub_{$author}"]
的双引号将$ author用作php变量