I have two MySQL tables. One is called members and has a column called users. The other is called sex and has two columns: user_s and sex.
I am trying to create an array comprised of all users from the members table who are
1) in the sex table and 2) have "men" selected in the sex column.
When I print_r this array nothing is displayed even though I can see that there are users who met these criteria. Any thoughts?
<?php
// test.php
include_once("header.php");
$iaminterestedin = "men";
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` IN(SELECT `user_s` FROM `sex` WHERE sex='$iaminterestedin')");
$combination = array();
while(($row = mysql_fetch_assoc($result)))
{
$combination = $row['user'];
}
print_r($combination);
?>
You should add values to combination using $combination[] = $row['user'] or you will always overwrite value on each loop iteration
You also ought to read something about JOIN tables, this will help you a lot with queries like that. For example you will use:
SELECT user FROM members INNER JOIN sex ON sex.user_s = members.user
WHERE sex '$iamintererstedin'
If you add a foreign key (http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html) from sex to users this will improve query performance when it gets bigger and time becomes a problem
Try replacing the line
$combination = array();
With
$combination[] = $row['user'];
This is the way to insert into an array:
I replaced $combination = $row['user'];
with
$combination[] = $row['user'];
That did the trick.
Related
I have a table named users and has a user_id, and a table named groups and has a group_id and also have user_id that is a foreign key reference from users's user_id.The situation is here: if the user joined a group, his/her user_id is inserted into table groups. So if the user joined two different groups, the column 'user_id' in table 'groups' will insert two or more same user_id's. Well, I just want to bring the user_id once, either he/she joined two or more groups..
I have no idea how to loop it properly without getting user_id that is the same.... I just want it to loop once...
$query_groups = mysql_query("SELECT * FROM groups");
while ($rows_g = mysql_fetch_assoc($query_groups)) {
$g_user_id = $rows_g['user_id'];
$query_users = mysql_query("SELECT * FROM users WHERE user_id='$g_user_id'");
while ($rows_u = mysql_fetch_assoc($query_users)) {
echo $rows_u['user_id'];
}
}
change your code as follows:
$query_groups = mysql_query("SELECT user_id FROM groups LEFT JOIN users ON users.user_id = groups.user_id GROUP BY groups.user_id");
while($rows = mysql_fetch_assoc($query_groups))
{
echo $rows['user_id'];
}
You are using $rows_g but the variable is namend $rows in the first while loop.
Wrong:
$g_user_id = $rows_g['user_id'];
Correct:
$g_user_id = $rows['user_id'];
But try to use joining tables, because this is an inefficient way to get the wanted data.
In your case you should use LEFT JOIN.
I have two different tables
And:
First i have used $timeapp_id which is the current user_id of the logged in user.
I want to display only the rows in user_info where $timeapp_id appears in timesheet_approver_1
So if my $timeapp_id is currently 8 then i should only get three rows displayed from user_info.
I have managed to get this part working with this code:
$data2b = "select * from user_info where timesheet_approver_1 = $timeapp_id";
$result2b = mysql_query($data2b);
while ($row2b = mysql_fetch_assoc($result2b)) {
$timesheet_approver_1 = $row2b['timesheet_approver_1'];
$timesheet_approver_2 = $row2b['timesheet_approver_2'];
$user_id2 = $row2b['user_id'];
//echo "( $timesheet_approver_1 / ";
//echo "$timesheet_approver_2 )";
echo "(($user_id2))";
So running this code gives me three rows from the table user_info where user_id is 5, 7 and 34.
This is where i am now stuck. What i want to do is only display the rows in time_data if the user_id in time_data matches the user_id in user_info
If this worked i should only see the rows in time_data where the user_id is 8, so only one row would be displayed.
How would i do this?
Thanks
David
For the variable $data2b you can JOIN the table user_info with table time_data ON user_info.user_id = time_data.user_id first, and then you can give the parameter WHERE the user_info.timesheet_approver_1 = $timeapp_id
What i did was pass the data through an array. I had got the code close to working but fatally wrong and so was not working through the array this is the correct working code i have used as corrected by Barmar on this site:
PHP array displaying last row values from table
$array = array();
while ($row2b = mysql_fetch_assoc($result2b)) {
$timesheet_approver_1 = $row2b['timesheet_approver_1'];
$timesheet_approver_2 = $row2b['timesheet_approver_2'];
$array[] = $row2b['user_id'];
}
$withComma = implode(", ", $array);
I have create a database Mysql and I am using in php. I want for each user to be checked if there is data.
I have three tables. In the table User has a unique value called ID_u and isn't auto_increment, the table Application has a unique value called ID(auto_increment) and table InformationUser has a unique value called ID(auto_increment). The tables Users and InformationUser joins with table Application.
ID_u = a user with id_u-> 1234
I'am try this:
if( ID_u exists data){
location1.php ->data
}else{
location2.php -> input information
}
I would be thankful for any help!!
I'm not sure I understand the structure of your database, but you may take a look at this:
$query = "
SELECT * FROM users u
LEFT JOIN application a
ON u.ID_u = a.ID_u
LEFT JOIN informationuser i
ON a.ID = i.ID
//Here you can specify 'WHERE u.ID_u IN (1,2,3,4)'
GROUP BY i.ID
" ;
$users = array() ; //Create storage for users. Use their ID as indeces
$result = $mysqli->query($query) ;
if ($result && $result->num_rows >= 1){
while ($row = $result->fetch_assoc()){
if (!isset($users[$row['ID_u'])){
$users[$row['ID_u']] = array() ; //Create array for a new user
}
$users[$row['ID_u']][] = array( //Fill array in with data and add it to user.
"email" => $row["email"],
"phone" => $row["phone"]
) ;
}
}
Afterwards, let's check if data exists for a user with ID = 3 (if 3 is an int):
if (!empty($users[3])){
echo "Yeah, data exists for user with ID 3" ;
}
First of all, if the user can only have one set of phone and email, it's better to save that data in the user table so that is has the following structure:
Users
ID_u
name
surename
email
phone
If you are set to keep the structure you have, my first tip is to take away the auto-increment on the table Application. That table is just meant to save the correlation between Users and InformationUser. Furthermore, the code you're looking for would be something like:
$sql = "SELECT * FROM Application WHERE ID_u = '1234'";
$result = mysql_query($sql) or die("Woops!");
if ($data = mysql_fetch_array($result)) {
include("location1.php");
}
else {
include("location2.php");
}
So you have users and you have applications. On each application there might be a different e-mail and name behind it. So you need to join and see if something exists. Something of this style
select count(*)
from Application
join InformationUser on (InformationUser.ID = Application.ID)
where
Application.ID_U = ?
The above gives you a count = 0 if both does not exist. If you want to know if both does not exists you can use an outer join.
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 have query that selects goes something like this:
$query = "SELECT members.*
FROM members
JOIN $nombre
ON members.member_ID=$nombre.friends";
$result = mysql_query($query) or die(mysql_error());
$number = mysql_num_rows($result);
$i = 0;
while($msg = mysql_fetch_assoc($result))
{
//store data in arrays
$peer_id[$i] = $msg['member_ID'];
$peer_state[$i] = $msg['home_state'];
$pro_political_views[$i] = $msg['political_views'];
$peer_district[$i] = $msg['district'];
$peer_first[$i] = $msg['first_name'];
$peer_last[$i] = $msg['last_name'];
$peer_issue[$i] = $msg['first_issue'];
$peer_second[$i] = $msg['second_issue'];
$peer_third[$i] = $msg['third_issue'];
$peer_stand[$i] = $msg['iStand'];
$peer_mail[$i] = $msg['email'];
$peer_pic[$i] = $msg['photo'];
++$i;
}
What this essentially does is get all the values from columns in the rows in the members from the members table where the member_ID is present in the $nombre table.
In the members table, there are two columns called "state" and "district". I want to make it so that php could tell me how many different values there are in the state and district columns for this query.
So, how could I go about writing a query or use php to tell how many how many peers are from a given state. I don't want to have to query the db once for each of the fifty states because that would take way too much time for the page to load. So, is there an efficient way to do this?
Thanks
...to tell how many how many peers are
from a given state
For states:
SELECT state, COUNT(m.member_ID) cnt
FROM members m
JOIN $nombre n ON m.member_ID=n.friends
GROUP BY state
and for districts:
SELECT 'district', COUNT(m.member_ID) cnt
FROM members m
JOIN $nombre n ON m.member_ID=n.friends
GROUP BY 'district'
This queries returns distinct values for states and districts and count of peers from them
You could use two queries, like so:
SELECT DISTINCT members.state
FROM members
JOIN $nombre
ON members.member_ID=$nombre.friends
and
SELECT DISTINCT members.district
FROM members
JOIN $nombre
ON members.member_ID=$nombre.friends
This will give you all of the unique states and districts back, which you can use or count or whatever.
Alternatively, add this somewhere in your while loop:
$all_states[$msg['state']] = 1;
$all_districts[$msg['district']] = 1;
Then, after the loop you can:
$state_count = count($all_states);
$district_count = count($all_districts);
The query approach would be faster by itself (assuming an index on the state and district columns), but the latter approach will be faster if you are already executing this loop anyway.
EDIT: To count unique districts in each state, replace
$all_districts[$msg['district']] = 1;
with something like
$all_districts[$msg['state'] . '--' . $msg['district']] = 1;
This will include the state in the array key too, and the count() call later will return all of the unique district-state combinations.
you can save the district in additional array like
$district[] = $msg['district'];
after the loop print_r using a function array_count_values
print_r(array_count_values($district));