I am trying to select everything from two different mysql tables. I imploded an array called friends so that I can select everything about the user's friends from both tables. Originally I wanted to perform one query on one table and then in a while loop a query on the other. But that didn't work. If you know I way I can nest while loops then please be sure to comment/answer this question.
Here's my code:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
echo '<br><br>';
}
Note: $row['last_name'] is from the users table and $row['body'] is from the text_post table. I am receiving this error whenever I run my code Column 'username' in where clause is ambiguous
Please help me.
UPDATE:
I changed my query to: $sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con)); but now it echo's every match twice:
parker hello
parker hello
simms what is up
simms what is up
simms it's raining
simms it's raining
jorge potato
jorge potato
Why is it doing that?
The only thing that is the same in both tables is the username.
Thanks for your question. The issue here is the error that you are receiving of:
Column 'username' in where clause is ambiguous.
What this means is that the statement that you are running is too obscure.
What you need to do to avoid this is to explicitly define the tables and columns that you are attempting to access and thus be implicit in your statements.
As a rule of thumb try and always define your columns in the following format:
{table_name}.{column_name}
With that being said the following should work:
$friends = implode("','", $friends);
/* implode the friends array for sql query. */
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends') AND text_post.username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Also I would also recommend that you use PHP's PDO Object as appose to the mysqli_query method.
I trust this helps.
both tables have a username. specify it using table.username
apparently both tables have the same column, and you are not prefixing the username column with either table name.
Maybe what you want is a union?
Use table prefix users in where block i.e. users.username
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con));
Try this:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT users.last_name,text_post.body FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Your logic would work were it not for username being present in both tables. Because it is, you need to alias your table names so that you can uniquely identify which column you're trying to use in the where clause:
SELECT * from users AS u, text_post as tp
WHERE u.username IN(....)
or shorter:
SELECT * from users u, text_post tp
WHERE u.username IN(....)
As a side note, it's bad practice to SELECT *, you should always explicitly select the columns you want, otherwise your code may crash if you add a column to a table later and forget to update your for loop to include/ignore any changed columns.
Related
I am building a friends list of logged in user verified by session id. I have code that query's, results, and loops perfectly. BUT, it is posting an integer (maybe the id#?), (as this is my unique identifying condition of the select query) AND what I want is to output the (users) table rows of "firstname" and "lastname" instead of the user-id!
Sounds simple enough, yet, I lack the knowledge to make it work! So, here I am inquiry from the world of coders for help! Any assistance would be greatly appreciated!
Here is my code:
// Get Friend Array
$sql = "SELECT * FROM users
INNER JOIN friends
ON users.id = friends.id
WHERE (friends.user1='$u' OR friends.user2='$u' AND friends.accepted='1')";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
array_push($my_friends, $row["user2"]);
array_push($my_friends, $row["user1"]);
}
//remove your id from array
$my_friends = array_diff($my_friends, array($u));
//reset the key values
$my_friends = array_values($my_friends);
mysqli_free_result($query);
// Loop through $my_friends array and build results
foreach($my_friends as $friends => $v2);
$friends .= ' ';
}
Here is my html code:
<ul data-role="listview" data-autodividers="true">
<?php
echo "<li>$friends</li>";
?>
</ul>
It is the last line of code
$friends .= ' ';that I'm trying to workout. How the syntax of that line should be to add ($row["users.firstname"] and $row["users.lastname"]) and somehow not list the user "$id #" that is joining the two tables of (users) and (friends) in the select query!
It may be that I need a different array altogether for what I want, and If you know of the right way to do this, please inform me of how to do it...Thank you all!
What I understood that you are missing User's id in row. This issue is because php array can not have two keys with same name.
Change you query little bit like below
$sql = "SELECT *, friends.id as friendsID FROM users
INNER JOIN friends
ON users.id = friends.id
WHERE (friends.user1='$u' OR friends.user2='$u' AND friends.accepted='1')";
Now you will have id' as User Id andfriendsID` as Friend's ID
I have two tables, one is a user log which stores the user by number
timestamp / user_id / transaction_id / amount
the other is a user table which has the users number and their full name
user_id / fullname
I want to select the entire user log and display it, but instead of displaying their number, display their full name from the other table, but I can't get it working. I keep modifying the sql and breaking it. Is there a way to accomplish this with php postgresql or should I use a function?
I keep getting an error that user_id is integer and the fullname is not
Please assist.
$query = "SELECT * FROM user_log
INNER JOIN user_staff
ON user_log.user_id=user_staff.user_name
ORDER BY user_log_id DESC LIMIT 200;";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['timestamp'], htmlspecialchars($myrow['user_id']), htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['amount']));
}
?>
Use this query:
SELECT "timestamp", fullname, transaction_id, amount
FROM user_log
JOIN users USING (user_id)
Note that "timestamp" is a SQL reserved word and you should not use it for a column name. If you must use it, put it in double quotes.
Perhaps something like:
SELECT user_log.timestamp, users.fullname, user_log.transaction_id, user_log.amount
FROM user_log
INNER JOIN users
ON users.user_id=user_log.user_id
ORDER BY user_log_id
DESC LIMIT 200;
You can read up on SQL Joins here: http://www.w3schools.com/sql/sql_join.asp
I'm building a followers list for a user. I have two tables the first shows the relationships between users and the second table holds every users profile info. In the following code, I first select from the user relationships table to get a variable {$userid1} which is the value of all the user ids that follow the current user. When I echo out {$userid1} I get all the ids of the users who follow the current user but it is one giant connected string. I want to take the variable {$userid1} and use it to pull every one of those follower's user data from the profile table. I want every user's data to show up from the profile table that follows the current user. The code works however only the newest follower's profile data is pulled from the profile table. I was thinking putting the variable {$userid1} into an array and using foreach, but I'm not sure how the syntax would be. Anybody know how it could work? The problem is a variable can only hold one value at a time.
Output of the first query are the iduser numbers from the users following the current user.
e.g. when echoed echo $userid1 . " "; the results are the ids look like this: 45 56 67
I added a space between numbers in the echo statement.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers from relations table
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
echo $userid1 . " ";
}
$sql = mysql_query("SELECT * FROM profile where iduser=$userid1 ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
You might be looking for subqueries:
SELECT username
FROM user_table
WHERE id IN( SELECT user_id WHERE linked_user_id = 123 )
This is simplefied to be a better example. This will select the username of all users from the user_table, where the ID exist in the subquery.
In turn, the subquery selects all user_id where the linked user has id=123.
The subquery is quite similar to making an array in PHP and use that info for the next query.
Small note: Be carefull with subqueries. They're perfect in my example above, but eg not all servers support a limit in the subquery. This might effect performance. The more complecated functions don't work in a subquery. Try to keep those simple.
You can use something like the following to execute this in a single query:
$id = mysql_real_escape_string($uid);
$sql = <<<SQL
SELECT
p.*
FROM profile as p
INNER JOIN followrelations as fl
ON fl.iduser1 = p.userid
WHERE fl.iduser2 = $id
ORDER BY username
SQL;
$stmt = mysql_query($sql);
while($row = mysql_fetch_array($stmt)){
// Rest of the logic here
}
This will return all the fields in your profile table. Note that the mysql_ extension is deprecated and unsafe - you should not be using it in new code. Take a look at How to replace MySQL functions with PDO? and How can I prevent SQL injection in PHP? for some good practices regarding this.
Found my mistake, the second $sql should be another name (I named it $sql1), and the second half should all be within the first while.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers session uid
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
$sql1 = mysql_query("SELECT * FROM profile where iduser='$userid1' ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql1)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
}
I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.
basically this is on the end of a dynamic form where the user can add multiple users of however many they want to a group, so i storte all the inputs in an array user[].
I want to query the array values and gain the userid for each then run another query with the user ids, inserting the userids into another table.
I am a beginner so I am getting lost in this. I looked at trying to use a for each method but couldnt get that working so now im trying a while.
here is my code ive been playing around with, i imagine its completely wrong :(
$query = 'SELECT * FROM users_tb WHERE student_number IN('.implode(',', $array).')';
mysql_query($query) or die(mysql_error());
$result=mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$sql = "INSERT INTO group_assocation_tb (group_id, user_id) VALUES('$group','$row['user_id']')";
mysql_query($sql) or die(mysql_error());
mysql_close();
}
please help? :D
regards
You want to use INSERT SELECT:
INSERT INTO group_association (group_id, user_id)
SELECT ' . $group_id . ', user_id
FROM users_tb WHERE student_number IN('.implode(',', $array).')
You have some extra quotes in the INSERT query, it should look like this:
$sql = "INSERT INTO group_assocation_tb (group_id, user_id) ".
"VALUES('$group','$row[user_id]')";
Other than that, it looks like it should work if $group is a group id.