I have two MySql tables, one called users and the other one posts.
There are two rows in the "users" table, each containing a user ID and a username. There's also a row in the "posts" table and in one of the cells called "contributors" there are two IDs from the users in the "users table." separated with a comma, so it looks something like this: 0000000000,1111111111
(not the actual IDs, these are just for reference.).
I want to to a "foreach" for all the IDs in the "contributors" cell, basically loop through all of them and for each of them IDs display the corresponding usernames.
I tried many things including this:
function post_contributors()
{
$contributor_ids = get_post()[8];
$contributor_array = explode(",", $contributor_ids);
$contributors = array_values($contributor_array);
foreach ($contributors as $contributor) :
$conn = include '../includes/dbh.inc.php';
$sql = "SELECT * FROM users WHERE user_id=$contributor";
$result = mysqli_query($conn, $sql);
if ($row = $result->fetch_row()) {
return $row ?? null;
}
return null;
echo '<h3 class="post-contributor-username">' . $result['user_username'] . '</h3>';
endforeach;
}
This doesn't work. I think it's because of the way I get the user ID (I'm left with an improper array).
Hope this all makes sense and someone can help.
1条答案
按热度按时间qzwqbdag1#
You can rewrite your function like this.
A few explanations.
global $conn
assumes that you have included yourdbh.inc.php
file in such a way that the script in which you call yourpost_contributors
function has access / knowledge of it.$contributor_info
is there to store what you would normallyecho
out where needed, once you call your function.The
if / else
doesn't need to return anything, because it would end your loop, and you would only get the info on the first contributor (if they exist in yourcontributors
table.Also, I've added
$postID
as an argument for your function, since you'd need to know that in order to be able to get the contributors.