Ok guys I am trying to access a php/mysql db via a nested query.
eg. I have 2 tables 1) persons and 2) registration. I have a refferal id tab in registrations. So when a user logs in he should be able to see 4 levels of registrations done below his id.
Table structure
Registration
id | Registration ID | regtype | Upline ID | uid |FirstName |MiddleName | LastName Last etc
personal
id| uid | upline | fname | miname | lname | etc and lot of other details
Now i am doing it like this to get to the first level.
$tid=$_GET['tid'];
$con = mysql_connect("localhost","db","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
mysql_select_db("db", $con);
$resulta = mysql_query("SELECT * FROM personal WHERE id=$tid ");
$counta = mysql_num_rows($resulta);
while ($rowa = mysql_fetch_assoc($resulta)) {
$selid=$rowa['uid'];
$amount=$rowa['amountf'];
$plan=$rowa['planname'];
$resultfulla[] = $rowa;
}
$resultb = mysql_query("SELECT * FROM regtab WHERE regtab.upline=$selid " );
$countb = mysql_num_rows($resultb);
$rowz=array();
while ($rowb = mysql_fetch_assoc($resultb)) {
$rowz[] = $rowb;
}
Now i am able to get to one level but how do i cycle the second array and the arrays that will be produced later to get a tree structure. Or so....any help....
With the array rowz i am able to store the results of the 1st line regstration that i have done. Now using this array i need to find out how to get the second line registrations that have been done below array rowz.....
Join your queries and get the result.
$sql = "SELECT * FROM personal
LEFT JOIN regtab ON regtab.upline = personal.uid
WHERE personal .id=".$tid;
Get all the results in php.
Related
I have been scratching my head for a very long time about this PHP code. I am trying to achieve something like
->Get each status
->Get each user in user's friends list
->Display status' from each user that is in the user's friends list
and repeat until there is no more. I have been looking for a solution for more a few days and it is really bugging me. Here is the code I tried:
EDIT: posted schema as requested
https://kjf-tech.net/files/schema.png
<?php
$connect = new MySQLi($DBhost,$DBuser,$DBpass,$DBname);
$querya = "SELECT * FROM statuses ORDER BY `id` DESC";
$result = mysqli_query($connect, $querya);
$ALLDATA = array();
$DBcon2 = new MySQLi($DBhost,$DBuser,$DBpass,$DBname);
if ($DBcon2->connect_errno) {
die("ERROR : -> ".$DBcon2->connect_error);
}
while ($record = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
array_push($ALLDATA, $record);
$queryb = "SELECT * FROM friendslist WHERE idOfPerson1='".$record['idOfUser']."' OR idOfPerson2='".$record['idOfUser']."' OR idOfPerson2='".$userRow['user_id']."' OR idOfPerson1='".$userRow['user_id']."' ORDER BY `id` DESC";
$result2 = mysqli_query($connect, $queryb);
$ALLDATA2 = array();
while ($record2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
array_push($ALLDATA2, $record2);
if($record['idOfUser'] == $userRow['user_id']) {
echo '<div>You Posted on '.$record['whenPosted'].'<br />'.$record['content'].'</div>';
}
elseif($record2['idOfPerson1'] == $userRow['user_id']) {
$query2 = $DBcon2->query("SELECT * FROM tbl_users WHERE user_id='".$record2['idOfPerson2']."'");
$userRow2=$query2->fetch_array();
echo '<div>'.$userRow2['username'].' Posted on '.$record['whenPosted'].'<br />'.$record['content'].'</div>';
}
elseif($record2['idOfPerson2'] == $userRow['user_id']) {
$query2 = $DBcon2->query("SELECT * FROM tbl_users WHERE user_id='".$record2['idOfPerson1']."'");
$userRow2=$query2->fetch_array();
echo '<div>'.$userRow2['username'].' Posted on '.$record['whenPosted'].'<br />'.$record['content'].'</div>';
}
}
mysqli_free_result($result2);
}
$DBcon2->close();
mysqli_free_result($result);
?>
Your schema looks good, but let's take another look at the relations. I'm going to rename some of the columns for convenience.
Users:
+- user_id
| user_name
|
|
| Friendships:
| fid
+- user_id
| friend_id --------+
| friendship_start |
| |
| |
| Statuses: |
| sid |
+- user_id ----------+
post_date
content
If you just wanted to find statuses of your friends, the query would look thus:
SELECT statuses.content
FROM friendships, statuses
WHERE friendship.user_id=? AND
friendships.friend_id = statuses.user_id
You would, of course, bind the appropriate user_id value when you ->prepare() the statement.
(See http://php.net/manual/en/mysqli.prepare.php for the proper way to do sql. You don't ever want to do something like mysql_query("select * from table where id=".$_POST['id']) because it's open to SQL injection)
Unfortunately, though, this does not include your own status in the query results. We'll have to do a little more work on the query...
SELECT statuses.content
FROM friendships, statuses
WHERE
( friends.user_id = ? AND
friends.friend_id = stuatuses.user_id )
OR
statuses.user_id = ?
ORDER BY statuses.post_date DESC
So far, so good... but we don't have the names nor the post date. The post date is easy, just add that to the select:
SELECT statuses.content, statuses.post_date
To add the name, we have to get data from Users also.
SELECT users.user_name, statuses.content, statuses.post_date
FROM users, friendships, statuses
WHERE
users.user_id = ? AND
(
( users.user_id = friendships.user_id AND
friendships.friend_id = statuses.user_id )
OR
statuses.user_id = users.user_id
)
ORDER BY statuses.post_date DESC
And there you have it; the database does all the work for you. No need for nested queries and such. This will just give you the simple list to print on your page. Please keep in mind that this is off the top of my head, so you may have to tweak it if I overlooked something.
I have two tables and i want to echo the total call count once each user logins:
Login
Firstname | Lastname | Login ID
------------------------------
Tyler | Durden | 3
Call Count
Name | Call Count | Open | GrandTotal
------------------------------
Tyler Durden| 100 | 33 | 133
i tried:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name=".$_SESSION['firstname']. ' ' .$_SESSION['lastname']." ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
But its not working, i think i have to join the the two tables to get it to work. What do you think?
Assuming your Call Count table is actually called csvdata, you'll want to format your SQL request string a bit by adding single quotes around the WHERE name = part.
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name='".$_SESSION['firstname']. ' ' .$_SESSION['lastname']."' ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Call Count'].' Call Count';
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
Good practice would require that you use primary keys to facilitate joins between tables and make sure two users with the same name can be differenciated.
In that case you may want to consider replacing the Name column in your Call Count table for your loginID. This way you could get your name from the Login table (as shown below). Also, as bad as it is to have duplicated data like your user's name in both tables, you do not need your GrandTotal column since you can easily get the sum of CallCount and Open to get the exact same number. In the end, your query should look more like this (assuming your tables are called Login and CallCount).
<?php
$result = mysqli_query($mysqli, "SELECT l.FirstName, l.LastName, cc.CallCount, cc.Open, (cc.CallCount + cc.Open) AS GrandTotal FROM Login AS l JOIN CallCount AS cc ON l.LoginID = cc.LoginID WHERE l.FirstName LIKE \"".$_SESSION['firstname']."\" AND l.LastName LIKE \"".$_SESSION['lastname']."\"");
// ...
?>
I have built a Twitter like following system using PHP and Mysql and I would like to list the followers a user has in order in which they followed the user. There are two relational tables that pertain to this action: USERS and FOLLOW.
user_id the one that is being followed.
follow_id the one that is following.
created date in which the following happened.
FOLLOW
--------------------------------------------------
|user_id |follow_id | created |
--------------------------------------------------
| 23 | 5 |2016-08-09 |
--------------------------------------------------
USERS
--------------------------------------------------
|user_id | name |
-------------------------------------------------
| 5 |John Doe|
--------------------------------------------------
This the php Mysql function to get the followers for a certain user.
<?php
public static function find_followers($user_id){
global $database;
$followers_ids = array();
$sql = "SELECT user_id
FROM follow
WHERE followed_id = '{$user_id}'
ORDER BY created";
$result = $database->query($sql);
while($follower = $database->fetch_array($result)){
array_push($followers_ids, $follower['user_id']);
}
if(count($followers_ids)){
$id_strings = join(',', $followers_ids);
$sql = "SELECT * FROM users WHERE id IN ($id_strings)";
$followers = self::find_by_sql($sql);
return $followers;
}
}
?>
Code to dislay followers
<?php
$followers = find_followers($id);
foreach($followers as $follower){
echo $follower->full_name() . "followed you.<br/>";
?>
Currently the list of followers is being ordered by the creation on which users were created, and I would like to display them based upon when the order in which they followed the user. How can this be done?
Thanks in advance!
You could use a join on the two table rather then having multiple calls to the DB. The SQL would be:
SELECT user.user_id, user.name /*The user that is followings details*/
FROM users
JOIN follow ON user.user_id = follow.follow_id /*You want the info for follower*/
WHERE follow.user_id = '{$user_id}' /*Only where the user is this user*/
ORDER BY follow.created /*Based on question this is the date a follow happened*/
Now the PHP can become (assuming that the $database is mysqli but not sure):
<?php
public static function find_followers($user_id){
global $database;
$followers_ids = array();
$sql = "SELECT user.user_id, user.name
FROM users
JOIN follow ON user.user_id = follow.follow_id
WHERE follow.user_id = '{$user_id}'
ORDER BY follow.created";
//If $user_id is user input you should do a prepared statement.
$result = $database->query($sql);
$followers = $database->mysqli_fetch_all($result);
return $followers;
}
}
?>
Your view can stay the same:
<?php
$followers = find_followers($id);
foreach($followers as $follower){
echo $follower->full_name() . "followed you.<br/>";
}
?>
i am new to php, i have a idea of what i want to do but i am not sure how i can execute them
i have 2 table in mysql
table 1 contains:
ID|Name|AboutMe|Specialisation
Example:
101|Andrew|handsome|drawing
102|Jane|pretty|drawing
103|Daniel|cute|swimming
table 2 contains
ID|Link|Title
101|//image1.jpg|Drawing in the dark
102|//image2.jpg|Drawing in me
103|//image3.jpg|Fish swimming
I want to display some images that are link to a Specialisation only once my website run.
A flow of what i have
1)
// get all the ID with drawing as specialisation // will return 2 rows
select ID FROM table1 WHERE Specialisation = "Drawing";
id = ID
2) from each row that matches, take the ID to get the link from table 2 like so
// get row of the links from the userid
Select * FROM userdatafiles WHERE ID = id
store the links into a variable and send to my jquery to display.
So basically get the id of each row that matches drawing, and take the id to find the same id from table 2 and get the link, and send it out to jquery as a result.
As there are many rows that i have to send out and i need to use arrays & loops, i'm not sure how i can do that. Can someone guide me along to what i'm doing? Thanks!
UPDATE:
jquery:
$.ajax({
type: "POST",
//dataType: "json",
url: "CMS/PHP/displayFeatThumbs.php",
success: function(data) {
alert(data[0]);
}
});
PHP:
<?php
include 'dbAuthen.php';
$sql = 'SELECT * FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Specialisation = "Interactive Art & Technology"';
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $links[] = $row["Link"];
}
} else {
echo "0 results";
}
?>
no idea how to display the array index on jquery, tried both alert(data[0]), alert(data.links[0]);
You can use a natural join to connect 2 tables or more.
The query should look like this :
SELECT * FROM userdatafiles JOIN table1 ON userdatafiles.id = table1.id WHERE Specialisation = "Drawing"
The result will be a new table like this example:
table1: id | name | date
table2: id | city | country
result :
id | name | date | city | country
You can work with the data like this:
$result = mysql_query("Your Query");
while($row = mysql_fetch_object($result)){
//Access values with $row->ColumnName
}
I have built 2 queries that compares the $project_id variable to the 2 tables MEETING & MEETING_AGENDA shown in the flow diagram below:
+---------------------+
+------------+ | MEETING_AGENDA |
| MEETING | +---------------------+
+------------+ | meeting_agenda_id |
| meeting_id |----->| meeting_id |
$project_id --->| project_id | | meeting_agenda_name |
+------------+ +---------------------+
The logic behind this flow diagram is, I have stored a variable called $project_id which acts as the input. If the $project_id = MEETING.project_id then I need to store a list of the MEETING.meeting_id's. There are multiple duplicates of project_id's in MEETING resulting in an array of meeting_id's (just for clarification). If any of the MEETING.meeting_id's = MEETING_AGENDA.meeting_id then print meeting_agenda_name.
My messy attempt (which works) looks like this:
$project_id = $_SESSION['PROJECT_ID'];
$query1 =
"
SELECT meeting_id, meeting_project_id
FROM MEETING
WHERE project_id = $project_id
";
$result1 = mysqli_query($con, $query1) or die("Query error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result1)){
$meeting_ids = $row['meeting_id'];
$query2 =
"
SELECT *
FROM MEEITNG_AGENDA
WHERE meeting_id = $meeting_ids
";
$result2 = mysqli_query($con, $query2) or die("Query error: " . mysqli_error($con));
while($row2 = mysqli_fetch_array($result2)){
echo $row2['meeting_agenda_name'] . "<br>"
}
}
I use 2 query's, I would like to clean this up into 1 query if possible. I have tried varies attempts at a single query but nothing has worked for me. Here is my latest attempt.
NEW QUERY:
$query =
"
SELECT MEETING.project_id, MEETING.meeting_id, MEETING_AGENDA.*
FROM MEETING
WHERE MEETING.project_id = $project_id
INNER JOIN MEETING.project_id
ON $project_id = MEETING.project_id
";
I apologize for my lack of mysql knowledge, but any help is appreciated.
You can get that information in a single query with the following:
SELECT m.project_id, m.meeting_id, ma.*
FROM MEETING m
INNER JOIN MEETING_AGENDA ma ON ma.meeting_id = m.meeting_id
WHERE m.project_id = $project_id