I have a query (below) that will check for a match in 3 tables. All 3 tables have the columns UID and IPADDRESS; the third table also has USERNAME. How can I change the query below to populate the variable $username with a unique list of usernames that matched the ipaddress?
So in each of the tables UID where the ipaddress matched could be say 2, 3, 6, 6, 23, 2, 6 because there are multiple entries and someone may have spoofed others ip’s. What i’d like is the query to populate $username with the usernames that match the UIDs 2, 3, 6, 23 (unique list). I have to tell you I’m completely new to MySQL and queries. Here’s the query:
error_reporting(E_ALL & ~E_NOTICE & ~8192);
$UAM = strtoupper($_SERVER['HTTP_USER_AGENT']);
$ips = strtoupper($_SERVER['REMOTE_ADDR']);
$myquery= "select sum(total)
FROM (SELECT count(*) as total,userid
FROM " .TABLE_PREFIX."memberviews v
where v.ipaddress = '$ips'
union all
SELECT count(*) as total,userid
FROM " .TABLE_PREFIX."membervisits v1
where v1.ipaddress = '$ips'
union all
SELECT count(*) as total,userid
FROM " .TABLE_PREFIX."user v3
where v3.ipaddress = '$ips'
)src";
$result = mysql_query($myquery);
$rowCount = mysql_num_rows($myquery);
$row = mysql_fetch_array($myquery);
$username = $row['userid'];
If($rowCount !=0){
$fp = fopen("logtext.txt", "a");
$DateOfRequest = date('m-d-Y H:i:s');
fwrite($fp, "Registration Attempt\n\nDate: . $DateOfRequest . \nMatched Member: . $username . \nWith User Agent: . $UAM . \nIP: . $ips . \n\n");
}
mysql_free_result($myquery);
Currently the query works in as much as it writes the file. All help appreciated 🙂
If I’m understanding your question correctly, this will get you the list of usernames associated with the IP address:
I’ve un-PHP’d the SQL, for the most part —
$ipsmarks where the IP address would be needed. The UNION (without ALL) eliminates duplicate user ID values; the list of unique user IDs is joined with the User table to generate the corresponding user names.Note that this will generate multiple rows, one per user name. Your question is ambiguous between user ID and user name in the output; if you only need the number, you only need the UNION sub-query as the main query. There are MySQL mechanisms such as GROUP_CONCAT that can create a single value from a list. Read the manual.