Im having trouble getting explode to work I have a table field named Attending with multiple user Ids separated with commas 73,1,5 right now i can easily get user 73 to echo out but need explode for the rest, I want it to echo out each username of those 3 users or however many it ends up being. I was thinking it might be something like what i commented out with the //
Attending Field is list of users
http://imageshack.us/a/img38/1425/eventsne.jpg
Trying to Echo out like this once i get username working ill do the avatar and in a table
http://imageshack.us/a/img819/8210/events2d.jpg
$Attending1 = array();
$Attending1 = mysql_query("SELECT * FROM Events, Users WHERE Events.Attending = Users.UserId");
//$AttendingUserIds = $Attending1['Attending'];
//$AttendingExploded = explode(",", $AttendingUserIds);
//$Attending3 = array();
//$Attending3 = mysql_query("SELECT * FROM Events, Users WHERE $AttendingExploded = Users.UserId");
while ($Attending2 = mysql_fetch_array($Attending1)) {
echo $Attending2['username'];
}
Just tryed KyleK 3rd suggestion
$Attending1 = array();
$Attending1 = mysql_query("SELECT * FROM Events, Users WHERE Events.Attending = Users.UserId");
$AttendingUserIds = $Attending1['Attending'];
//$AttendingExploded = explode(",", $AttendingUserIds);
$Attending3 = array();
$Attending3 = mysql_query("SELECT * FROM Events, Users WHERE Users.UserId IN ($AttendingUserIds)");
It gives me Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource where the While starts.
You can do it all in just one SELECT, by joining Events and Users tables thru the find_in_set() function. That way, you will get all users which attended each event, because find_in_set() will look up the first parameter in the CSV string supplied as the second parameter. You may also want to add a WHERE to filter a specific event. And don't forget to replace the * with only the fields you need, to avoid unnecessary data traffic:
$Attending = array();
$Attending = mysql_query("
SELECT *
FROM Events e
INNER JOIN Users u ON find_in_set(u.UserId, e.Attending)
");
$Attending1 = mysql_query("SELECT * FROM Events, Users WHERE Events.Attending = Users.UserId");
while ($Attending2 = mysql_fetch_assoc($Attending1)) {
$arr[] = $Attending2['username'];
}
mysql_query doesn't give you an array, fetch_array (or fetch_assoc) does.
Its result will be similar to this: $arr[0]['username'], $arr[1]['username'], $arr[2]['username'], etc. I don't know how you want to "explode" so I can't answer, but after fetch_assoc you should get an array.
So if I understand you correctly you have values in a string that are comma seperated "73, 3, 5".
So then just use WHERE IN
Your string of values from the database, however you gonna get it...
$stringofids = "73,3,3";//You will obviously retrieve these from database
Then just pass that string into another query, with a WHERE IN statement...
That will return an array of all the users attending.
$AttendingUsers = mysql_query("SELECT * FROM Events, Users WHERE Users.UserId IN ($stringofids)");
while ($Attending = mysql_fetch_array($AttendingUsers)) {
echo $Attending['username'];
}
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 Am having trouble with this, i have table from mysql named person with fields id, name, and person_room. I also have this table called room with fields of roomid, name and capacity. i want to call a data from field capacity of table room. but it shows Resource id #7
here is my code:
$check_room_capacity = "SELECT capacity from room WHERE roomid = '".$oroom."'";
$check_user_capacity = mysql_query($check_room_capacity);
$rows = mysql_fetch_array($check_user_capacity);
$check_room = "SELECT id from person WHERE person_room = '".$oroom."'";
$check_user_room = mysql_query($check_room);
if(mysql_num_rows($check_user_room) => $check_user_capacity){
echo "room is loaded please try another room";
}
//then code here to insert it if the number of person
//is less than the room capacity
I tried to echo this thing $check_user_capacity to know its value but it shows resource id#7. Do you guys have any idea?
The other thing is, why my php don't accept this operation '=>' and '<=' it always underlined in color red?
mysql_query() statement returns a resource pointer to the result set, not the data itself. You'll need to use mysql_fetch_array() in order to retrieve the actual data in the table.
$old_ip = mysql_query("SELECT current_ip FROM members WHERE id='$id'");
$row = mysql_fetch_array($old_ip);
$result_old_ip = $row['current_ip'];
Try this one:
$check_room_capacity = "SELECT capacity from room WHERE roomid = '".$oroom."'";
$check_user_capacity = mysql_query($check_room_capacity);
$rows = mysql_fetch_array($check_user_capacity);
$check_room = "SELECT id from person WHERE person_room = '".$oroom."'";
$check_user_room = mysql_query($check_room);
if(mysql_num_rows($check_user_room) >= $rows['capacity']){
echo "room is loaded please try another room";
}
I have 2 tables, one is called post and one is called followers. Both tables have one row that is called userID. I want to show only posts from people that the person follows. I tried to use one MySQL query for that but it was not working at all.
Right now, I'm using a workaround like this:
$getFollowing = mysqli_query($db, "SELECT * FROM followers WHERE userID = '$myuserID'");
while($row = mysqli_fetch_object($getFollowing))
{
$FollowingArray[] = $row->followsID;
}
if (is_null($FollowingArray)) {
// not following someone
}
else {
$following = implode(',', $FollowingArray);
}
$getPosts = mysqli_query($db, "SELECT * FROM posts WHERE userID IN($following) ORDER BY postDate DESC");
As you might imagine im trying to make only one call to the database. So instead of making a call to receive $following as an array, I want to put it all in one query. Is that possible?
Use an SQL JOIN query to accomplish this.
Assuming $myuserID is an supposed to be an integer, we can escape it simply by casting it to an integer to avoid SQL-injection.
Try reading this wikipedia article and make sure you understand it. SQL-injections can be used to delete databases, for example, and a lot of other nasty stuff.
Something like this:
PHP code:
$escapedmyuserID = (int)$myuserID; // make sure we don't get any nasty SQL-injections
and then, the sql query:
SELECT *
FROM followers
LEFT JOIN posts ON followers.someColumn = posts.someColumn
WHERE followers.userID = '$escapedmyuserID'
ORDER BY posts.postDate DESC
Im having difficulties trying to figure out an elegant solution to sorting the results of a mysql query based on a delimited string. Ill explain in more detail below
I am creating a database of contacts where individual users can add/remove people from a list. When the user adds a new contact I append the added contact id to a delimited string and store that data in a database column associated with that user (named contacts):
$userID = ?? //YOUR ID
$contactID = ?? //WHATEVER THE ADDED USER ID IS
$confirm = 0 //has the user been confirmed
$sql = "SELECT contacts FROM user WHERE id = '$userID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$contact = $row['contacts'];
$contact .= '|'.$contactID.':'.$confirm;
$update = mysql_query("UPDATE user SET contacts = '$contact' WHERE id = '$userID'");
//contact column data might be: |10:0|18:0|36:0|5:0
When the user searches their contacts I grab the data from the contacts column, explode/split the string and return the individual users names:
$userID = ?? //YOUR ID
$sql = "SELECT contacts FROM user WHERE id = '$userID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$contacts = explode("|", $row['contacts']);
foreach($contacts as $item)
{
list($contactID,$confirm) = split(":", $item);
$sql = "SELECT name FROM ".user." WHERE id = '$contactID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
echo($row['name'].'<BR>');
}
This indeed does return all the names, but it returns them in the order of the delimited string. I cant seem to find an elegant way to sort by name alphabetically.
Should I not store the contacts list in a delimited string? How would you solve this?
You're right, you should not store the contacts in a string. Instead use another table which contains the user information. The new table should look something like the following:
Table: user_contacts
| user_id | contact_id | confirm |
-------------------------------------------
| your data here... |
Then when you need your contact list you can simply perform another query:
SELECT * FROM `user_contacts`
JOIN `users` ON `users`.`id` = `user_contatcs`.`user_id`
WHERE `users`.`id` = $id
ORDER BY `users`.`name`;
Or however you need to order it.
There are two obvious approaches:
Sort the results once you've fetched them
Fetch them all in one query and have the DB sort them
For #1, use usort():
$rows = array();
foreach ($contacts as $item){
list($contactID,$confirm) = split(":", $item);
$query = mysql_query("SELECT name FROM user WHERE id = '$contactID'");
$rows[] = mysql_fetch_array($query);
}
usort($rows, 'sort_by_name');
function sort_by_name($a, $b){
return strcmp($a['name'], $b['name']);
}
foreach ($rows as $row){
echo($row['name'].'<BR>');
}
For #2, build a list of IDs and use IN:
$ids = array();
foreach ($contacts as $item){
list($contactID,$confirm) = split(":", $item);
$ids[] = $contactID;
}
$ids = implode(',', $ids);
$query = mysql_query("SELECT name FROM user WHERE id IN ($ids) ORDER BY name ASC");
while ($row = mysql_fetch_array($query)){
echo($row['name'].'<BR>');
}
If you're using a relational database, then what you want is a separate table that stores person-contact relationships. Then you would modify your sql query to select based on a join across two tables
SELECT * FROM person, contact
JOIN contact ON person.id = contact.personid
JOIN person ON contact.contactid = person.id
WHERE person.id = $id
ORDER BY person.lastname
(That code is probably not quite correct.)
If you're using a no-sql type implementation, the way you're doing it is fine, except that you will either have to programmatically sort after the fact, or sort-on-insert. Sort on insert means you'd have to query the current list of contacts on inserting one, then sort through to find the right position and insert the id into the delimited string. Then save that back to the db. The downside to this is you'll only be able to sort one way.
Generally, people use relational databases and 'normalize' them as described above.
I'm currently using the following PHP code:
// Get all subordinates
$subords = array();
$supervisorID = $this->session->userdata('supervisor_id');
$result = $this->db->query(sprintf("SELECT * FROM users WHERE supervisor_id=%d AND id!=%d",$supervisorID, $supervisorID));
$user_list_query = 'user_id='.$supervisorID;
foreach($result->result() as $user){
$user_list_query .= ' OR user_id='.$user->id;
$subords[$user->id] = $user;
}
// Get Submissions
$submissionsResult = $this->db->query(sprintf("SELECT * FROM submissions WHERE %s", $user_list_query));
$submissions = array();
foreach($submissionsResult->result() as $submission){
$entriesResult = $this->db->query(sprintf("SELECT * FROM submittedentries WHERE timestamp=%d", $submission->timestamp));
$entries = array();
foreach($entriesResult->result() as $entries) $entries[] = $entry;
$submissions[] = array(
'user' => $subords[$submission->user_id],
'entries' => $entries
);
$entriesResult->free_result();
}
Basically I'm getting a list of users that are subordinates of a given supervisor_id (every user entry has a supervisor_id field), then grabbing entries belonging to any of those users.
I can't help but think there is a more elegant way of doing this, like SELECT FROM tablename where user->supervisor_id=2222
Is there something like this with PHP/MySQL?
Should probably learn relational databases properly sometime. :(
EDIT:
here is the relevant schema
submissions
===============================
id, user_id, timestamp
submittedentries
===============================
id, user_id, timestamp
users
===============================
id, supervisor_id, email
one submission has many submittedentries, and currently I'm referencing this by using the timestamp. I'd be more than willing to alter this if someone can suggest a more efficient way. (and yes, there are more fields that I'm omitting)
This should, if I got the column names correct, get a list of submissions from users who have the specified supervisor.
SELECT * FROM users, submissions
WHERE users.supervisor_id = $supervisorID
AND submissions.user_id = users.id
This version attempts to combine the timestamp checking as well.
SELECT * FROM users, submissions, submittedentries
WHERE users.supervisor_id = $supervisorID
AND submissions.user_id = users.id
AND submittedentries.timestamp = submissions.timestamp
Edit: Updated to match the additional table info. I'm still not 100% sure that the second version is correct, will need to be tested against the database to find out :)
Oh, and in practice you should probably replace the asterisk with the names of the actual columns you want to retrieve.