select * that match user postcode in mysql table? - php

I'm trying to display a list of users who live locally to the user who is logged in. so if the logged in session user has a postcode of 'm3 4' and 5 other users have a postcode beginning with 'm3 4' then these users will be shown to the user.
My table is laid out like this:
id | user_id | user_postcode
1 2 M3 4
2 3 SM2 7
3 4 M3 4
so in this scenario user 2 will be shown to user 4 who is logged in because their post codes match.
I'm trying to do this in mysql and it works when i put the postcode in manually like so:
AND ptb_stats.user_postcode='M3 4'
but I'm trying to make it user session specific, so if the logged in user / $_SESSION[user_id'] has the same post code as other users.
i'm trying to do it this way, but it's showing all the users without postcodes where as it should be showing the users that have matching postcodes, shouldn't it?
function get_local_users() {
global $connection;
global $_SESSION;
$query = "
SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode='".$_SESSION['user_postcode']."'";
$local_set = mysql_query($query, $connection);
confirm_query($local_set);
return $local_set;
}

With this answer, I assume that the $_SESSION['user_postcode'] is filled from some type of input box and the value is a valid zipCode (like "M3 4").
You can use preg_match to split the zipcode from the number and try to select zipcodes form the db. Take a look at this example:
$matches = array();
$zipCode = preg_match('/^([a-z0-9]+)/i', $_SESSION['user_postcode'], $matches);
The zipcode is now in the $matches variable at the second place ($matches[1]).
Now use this value to create a query and check if it is the same as others..
$query = "SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode REGEX '^" . $matches[1] . "'";

According to what you describe, I will go onto something like that.
I used prepared statement from PDO to handle the query.
function get_local_users() {
// given that it was created like this: $connection = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
global $connection;
$stmt = $connection->prepare(
"SELECT ptb_stats.*
FROM ptb_stats, ptb_users
WHERE ptb_stats.user_id = ptb_users.id
AND ptb_stats.user_id != ?
AND ptb_stats.user_postcode = (
SELECT user_postcode
FROM ptb_stats
WHERE user_id = ?
)");
$stmt->execute(array($_SESSION['user_id'], $_SESSION['user_id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}

If the user id is stored in $_SESSION['user_id'], you can get the local users with
select u.id, u.name
from ptb_users u
join ptb_stats s1 on s1.user_id = $_SESSION['user_id']
join ptb_stats s2 on s2.user_id = u.id and s2.user_postcode = s1.user_postcode
where u.id <> $_SESSION['user_id']
SQLFiddle
If you have the postcode in $_SESSION['user_postcode'], it is even easier
select u.id, u.name
from ptb_users u
join ptb_stats s on s.user_id = u.id
and s.user_postcode = $_SESSION['user_postcode']
where u.id <> $_SESSION['user_id']
SQLFiddle

Related

Select a fixed number of records from a particular user in a sql result

I have 2 tables - users and articles.
users:
user_id (int)
name (varchar)
articles:
article_id (int)
user_id (int)
title (varchar)
description (text)
In my application I need to display 20 RANDOM articles on a page.
My query is like this:
SELECT a.title
, a.description
, u.name
FROM articles a
JOIN users u
USING (user_id)
ORDER
BY RAND()
LIMIT 20
A user can have any number of articles in the database.
Now the problem is sometimes out of 20 results, there are like 9-10 articles from one single user.
I want those 20 records on the page to not contain more than 3 (or say 4) articles from a particular user.
Can I achieve this through SQL query. I am using PHP and MySQL.
Thanks for your help.
You could try this?
SELECT * FROM
(
SELECT B.* FROM
(
SELECT A.*, ROW_NUMBER() OVER (PARTITION BY A.USER_ID ORDER BY A.R) USER_ROW_NUMBER
FROM
(
SELECT a.title, a.description, u.name, RND() r FROM articles a
INNER JOIN users u USING (user_id)
) A
) B
WHERE B.USER_ROW_NUMBER<=4
) C
ORDER BY RAND() LIMIT 20
Mmm, intresting I don't think this is possible through a pure sql query.
My best idea would be to have an array of the articles that you'll eventually display query the database and use the standard SELECT * FROM Articles ORDER BY RAND() LIMIT 20
The go through them, making sure that you have indeed got 20 articles and no one has breached the rules of 3/4 per user.
Have another array of users to exclude, perhaps using their user id as an index and value of a count.
As you go through add them to your final array, if you find any user that hits you rule add them to the array.
Keep running the random query, excluding users and articles until you hit your desired amount.
Let me try some code (it's been a while since I did php)
$finalArray = [];
$userArray = [];
while(count($finalArray) < 20) {
$query = "SELECT * FROM Articles ";
if(count($finalArray) > 0) {
$query = $query . " WHERE articleID NOT IN(".$finalArray.")";
$query = $query . " AND userID NOT IN (".$userArray.filter(>4).")";
}
$query = $query . " ORDER BY Rand()";
$result = mysql_query($query);
foreach($row = mysql_fetch_array($result)) {
if(in_array($finalArray,$row) == false) {
$finalArray[] = $row;
}
if(in_array($userArray,$row[userId]) == false) {
$userArray[$row[userId]] = 1;
}
else {
$userArray[$row[userId]] = $userArray[$row[userId]] + 1;
}
}

Get userID from database

I have a simple blog where I'm practicing some php and mysql. I'm trying to display the username of the post author (you know where it says posted by Author).
I have two tables blog_members and blog_posts which are related 1 to many so I got a memberID field into the blog_posts. I'm trying to get the username of the member who's the author of the post.
I was thinking to do a join or something but I can't figure this out.
Here's what I was trying to do but it's not working because I'm sure I'm not using it properly.
$query1 = "SELECT username from blog_members JOIN blog_posts ON memberID = memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
PS: I got it working one way by using SESSION to get the userID but that works only if the user is logged is which is not the case, I want to display the name in any case.
Thanks!
Use inner join this way
And with a proper sanitize use $your_user_id for match
$query1 = "SELECT username
from blog_members
INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID
WHERE blog_posts.memberID = '" .$your_user_id . "';";
JOIN syntax is wrong in your query.
Use following query:
$query1 = "SELECT username from blog_members JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
Try something like this, usng INNER JOIN :
$query1 = "SELECT blog_members.username FROM blog_members INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
reference : http://www.w3schools.com/sql/sql_join.asp
Here is a solution using a simple WHERE condition (same performance Explicit vs implicit SQL joins) :
SELECT a.username FROM blog_members a, blog_posts b WHERE a.memberID = b.memberID
But if you need more information about MySQL Join : https://www.sitepoint.com/understanding-sql-joins-mysql-database/
Hope this helps !

Get friends profile picture(s) from user table

I have 2 table's:
Users (id, username, email, avatar, etc...);
Friends (id, user1, user2, status);
Now I want to build on my profile page an list of my friends with there avatar(s). I'm trying for like 4 hours by myself but i don't get it... :(
BTW: this is an error i got!
Notice: Array to string conversion in /home/reduaqi158/domains/reduankurtaj.eu/public_html/snapfriends/vrienden.php on line 26
This is what i have right now:
<?php
error_reporting(E_ALL);
session_start();
$username = $_SESSION['username'];
$status = 2;
include "includes/conn.php";
$vrienden=mysqli_query($server,"SELECT * FROM vrienden WHERE status='$status' && vriend1='$username' || vriend2='$username' ");
$vriend_list = array();
while($row = mysqli_fetch_array($vrienden))
{
if ($row['vriend1'] == $username) {
$vriend_list[] = $row['vriend2'];
}
else {
$vriend_list[] = $row['vriend1'];
}
}
echo json_encode($vriend_list);
$foto=mysqli_query($server,"SELECT prof_pic FROM users WHERE username='$vriend_list['vriend1''vriend2']' ");
while($row2 = mysqli_fetch_array($foto)) {
echo "<img class='img-rounded' src=assets/profiel/".$row2['prof_pic']." alt='Card image cap'>";
}
?>
json_encode output:
["ja","amando"]
Someone who can help me pls :)
Your initial approach is very confusing.
Almost everything in your code can be substituted by single SQL query.
You can use JOIN to get all your friends with their avatars in one go:
SELECT u.username as username, u.avatar as avatar,.... <== all columns which you need
FROM `friends_table` f <== your friends table
JOIN `users_table` u <== your users table
ON (f.user1 = u.id) <== notice that i join on user1 column
WHERE u.username = '$username' && f.status = '$status'
UNION
SELECT u.username as username, u.avatar as avatar,.... <== same columns
FROM `friends_table` f <== your friends table
JOIN `users_table` u <== your users table
ON (f.user2 = u.id) <== notice that i join on user2 column
WHERE u.username = '$username' && f.status = '$status'
By this query you select all users who are in a friendship with your $username. You need union because you don't know in which field (user1 or user2) your $username is located.
NOTE: I strongly suggest using prepared statements instead of just putting '$var' inside SQL query to prevent SQL Injection.
After executing this query you can parse results and display avatars in such a way:
while($row = mysqli_fetch_array($vrienden, MYSQLI_ASSOC))
{
echo "<img class='img-rounded' src=assets/profiel/".$row['avatar']." alt='Card image cap'>";
}
I hope you got the idea.
in your while statement you have to declare a value for the array. like array[0] = value. so that you know that array position 0 has a certain value. Like what I did here below. Don't know if it's in PHP like this but certain in .net you have to declare the location of a value in an array.
while($row = mysqli_fetch_array($vrienden))
{
if ($row['vriend1'] == $username) {
$vriend_list[0] = $row['vriend2'];
}
else {
$vriend_list[1] = $row['vriend1'];
}
}
and the following
$foto=mysqli_query($server,"SELECT prof_pic FROM users WHERE username='$vriend_list['vriend1''vriend2']' ");
shouldn't it be $vriend_list['vriend1'] . $vriend_list['vriend2']'
you have to use a connect character (the . in PHP)

Mysql with if condition

My Question is I need to get two conditions first one if a user is admin I need to display all transactions but if a users is not admin I need to display his own transaction only.
hers is the code that I tried but does not work.
Tables I have
Users(Id, username, password, category ...etc)
Transaction (Id, name, description, username, …etc)
SELECT IF ( (select category from users where username = ‘ali’ )==’A’) THEN
Select * from transaction
ELSE
Select * from transaction where username = ‘ali’
I also tried with this one but still no solution
SELECT IF(
SELECT category FROM users where username= 'ali' AND category ='A',
SELECT * FROM Transaction ,
SELECT * FROM Transaction where username= 'ali'
)
Thanks
try this
$where_text = ""; // initially blank
// here $user variable contains the current username
if($user!='admin') // check $user is admin or not if not
{
$where_text = " WHERE username='$user' "; // update $where_text
}
$query = "SELECT * FROM `transaction` ".$where_text; // apply in the query
Now you can user your query by $query variable
I would prefer to do this logic in the code but you can check using an OR in the where clause:
SELECT * FROM Transaction t
WHERE t.username = 'ali'
OR EXISTS (SELECT category FROM users where username= 'ali' AND category ='A')
This should work:
SELECT * FROM Transactions WHERE username = 'username' OR (SELECT 1 FROM users WHERE username = 'username' AND category = 'A')

How to get information from 2 tables at once in PHP and MySQL?

<?php
include('includes/config.php');
$topi = $_GET['id']; //id of url
mysql_select_db("ban", $con);
$query = "SELECT * FROM `basic` WHERE id = '$topi' LIMIT 0, 30";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$aa = $row['item'];
$cc = $row['moreinfo'];
$dd = $row['contactinfo'];
$ff = $row['id'];
In this script, I get information from the table basic, but I want to retrieve data from another table named users. How can I retrieve data from two tables at once?
users table consists of following columns:
email
username
ID
You need to JOIN the two tables on a common value, called a foreign key. Once you've posted the structure of the users table as requested in the comments, I can provide a more complete example.
EDIT: See example. This calls explicit column names instead of SELECT *.
$query = "SELECT
basic.id,
basic.item,
basic.moreinfo,
basic.contactinfo,
users.email,
users.username
FROM basic JOIN users ON basic.id = users.id
WHERE id = '$topi'
LIMIT 0 , 30";
You would use a JOIN onto the other table.
$query = "SELECT *
FROM basic b
JOIN users u ON b.user_id = u.user_id
WHERE id = '$topi'
LIMIT 0, 30";
Something like that, but based on your fields.
Please Note: the ON clause specifies what you will be looking for a match on.

Categories