Inner Join & show data by id user API - php

How to display student value data?
so for access parents can only see value data from their children.
Please help
scheme
for the header I have put it in the conn.php file
<?php
require_once "conn.php";
$query = "SELECT student, name, payment FROM payment INNER JOIN parent ON payment. student_id = student. student_id WHERE student. parent_id = id login parent" ;
$sql = mysqli_query ($link,$query);
$ray = array();
while ($row = mysqli_fetch_array($sql)) {
array_push($ray, array(
"id" => $row['id'],
"student_id" => $row['student_id'],
"date" => $row['date'],
"grade" => $row['grade']
));
}
echo json_encode($ray);
mysqli_close($link);
?>
function.php
<?php
function escape($data){
global $link;
return mysqli_real_escape_string($link, $data);
}
function username_check($username){
global $link;
$query = "SELECT * FROM parent WHERE username='$username'";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) == 0 ) return true;
else return false;
}
function email_check($email){
global $link;
$query = "SELECT * FROM parent WHERE email='$email'";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) == 0 ) return true;
else return false;
}
?>
I'm confused because I just learned about this and the error results;D

I guess you need something like this
SELECT
m.grade,
m.subject,
m.date,
s.name
FROM mark m
INNER JOIN student s ON m.student_id = s.id
INNER JOIN parent p on s.parent_id = p.id
WHERE
p.id = *parent id*

Related

Mysql/PHP Json nested array

I got issue with nested array which seems are not Json object for some reason. When i try for e.g access jsonData["user"] it works, but when i try go deeper such as jsonData["user"]["photo_url"] then it's treated like a string and i cant access the value.
Current code:
<?php
require_once("db_connection.php");
$userId = $_GET["user_id"];
$query = "WITH user AS (SELECT id, JSON_OBJECT('display_name', u.display_name, 'photo_url', u.photo_url) AS user FROM users u WHERE id = :userId), info AS (SELECT id, JSON_ARRAYAGG(JSON_OBJECT('text', text, 'start_at', start_at, 'end_at', end_at, 'status', status)) AS information FROM report GROUP BY id), img AS (SELECT report_id, JSON_ARRAYAGG(JSON_OBJECT('name', name)) AS images FROM report_images GROUP BY report_id), cmt AS (SELECT report_id, COUNT(*) AS totalcomments FROM report_comments rc JOIN users u ON rc.user_id = u.id GROUP BY report_id) SELECT u.user, info.information, img.images, cmt.totalcomments FROM report r JOIN user u ON u.id = r.user_id LEFT JOIN info ON info.id = r.id LEFT JOIN img ON img.report_id = r.id LEFT JOIN cmt ON cmt.report_id = r.id";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Old code which worked:
<?php
require_once("db_connection.php");
require_once("functions.php");
$userId = $_GET["user_id"];
$query = "SELECT * FROM report WHERE `user_id` = :userId";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
foreach ($result as $key => $value) {
$result[$key]["user"] = getUserById($db, $value["user_id"]);
}
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Because you are aggregating some of the values as JSON in your query, you need to decode those first before attempting to use the values and then JSON encode the whole result set. You need to do that as you fetch the data, so replace:
$result = $stmt->fetchAll();
with:
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['user'] = json_decode($row['user']);
$row['images'] = json_decode($row['images']);
$row['comments'] = json_decode($row['comments']);
$result[] = $row;
}

Looping a query from previous result in mysql

I have two tables, user and leads. My goal is to find users with leads having status 'completed' and 'idle', after that use that result to get all the leads for that user. Here is my query
$sql = "SELECT u.id FROM users u LEFT JOIN leads l ON u.id = l.user_id WHERE l.status IN('completed', 'idle')";
...
$result = $stmt->fetchAll();
...
$usersleads = array();
foreach ($result as $userId) {
$sql = "SELECT * FROM leads where user_id = ". $userId;
...
$results = $stmt->fetchAll();
foreach ($results as $ul) {
array_push($usersleads, $row);
}
}
This works for small results. But if data gets bigger this just crashed and I can understand it. I am looking for a more efficient way to query the db.
UPDATE
I think I have found a solution. Now only has two queries over all.
$sql = "SELECT u.id FROM users u LEFT JOIN leads l ON u.id = l.user_id WHERE l.status IN('completed', 'idle')";
...
$userResult = $stmt->fetchAll();
...
$userIds = [];
foreach ($userResult as $user) {
$userIds[] = $user['id'];
}
$sql = "SELECT * FROM leads where user_id IN('" . implode("','", $userIds) ."')";
...
$leadsResult = $stmt->fetchAll();
...
foreach ($userResult as &$lead) {
$lead['date'] = $this->getDateForLead($lead['id'], $leadsResult);
// add other fields to $userResult
}
...
public function getDateForLead($leadId, $leads)
{
foreach($leads as $lead) {
if ($leadId = $lead['id']) {
return $lead['date'];
}
}
return null;
}

Select from two tables where company_id=$company->id

hello I have this variable $company->id
and I have function like this
<?php
function GetEmploees(){
$db = JFactory::getDBO();
$query = 'SELECT * FROM #__jbusinessdirectory_attribute_options AS c JOIN #__jbusinessdirectory_company_attributes AS cp
on c.id = cp.option_id';
$db->setQuery($query);
if( $rows = $db->loadObjectList() ) {
foreach( $rows as $row ){
echo $row->name;
}
}
}
echo GetEmploees($company->id);
?>
I want select $row->name as $company->id
how can I insert code WHERE company_id = '.$company->id.' in query?
company_id is in table #__jbusinessdirectory_company_attributes
Try
$sql = "SELECT * FROM #__jbusinessdirectory_attribute_options AS c INNER JOIN #__jbusinessdirectory_company_attributes AS cp (on c.id = cp.option_id) WHERE c.company_id = '.$company->id.'";
Should do the trick

How to shuffle posts in two tables?

I was working on a post system..
So, I have to show posts by friends of the user and the groups in which user has participated..
Here is my code to show posts..
<?php
$sql = "SELECT * FROM posts WHERE uploader_id=:friend_id ORDER BY id DESC";
$query = $db->prepare($sql);
$query->execute(array(
":friend_id" => $friend_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$name = $row['name'];
echo "POST BY $name";
}
$sql = "SELECT * FROM group_posts WHERE id=:member_group ORDER BY id DESC";
$query = $db->prepare($sql);
$query->execute(array(
":member_group" => $group_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$name = $row['name'];
echo "POST BY $name";
}
?>
Now, I want all these posts to be shuffled in a way that all the posts of the post table and group_posts table are shown in the descending order.
UPDATE
I edited my code to this..
I figured out that first I'll have to code this before coding my post system..
<?php
$sql = "SELECT * FROM friends WHERE user_one=:me OR user_two=:me2 UNION SELECT * FROM group_members WHERE member_id=:me3";
$query = $db->prepare($sql);
$query->execute(array(
":me" => $my_id,
":me2" => $my_id,
":me3" => $my_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$user_one = $row['user_one'];
$user_two = $row['user_two'];
$group_id = $row['group_id'];
if ($user_one == $my_id) {
$friend_id = $user_two;
} else {
$friend_id = $user_one;
}
echo $friend_id . "<BR>" . $group_id;
}
?>
Now, here's the problem..
This is successfully printing the $friend_id but, it shows an undefined index 'group_id' while printing $group_id.
I have checked all the fields are correct.
Try using just one query with UNION
SELECT *
FROM (
SELECT name, id FROM posts WHERE uploader_id=:friend_id
UNION
SELECT name, id FROM group_posts WHERE id=:member_group
) p
ORDER BY p.id DESC
Note, your inner queries must return the same number of columns in the same order (and I think with the same name/alias, too).

How would I get values from 2 rows into one

I need to access data from 2 different rows returned in the same array
Here is a picture
I need to access first_name and last_name
Here is my script
<?php
ini_set('display_errors', 1);
include_once('db.php'); // database class
$dbase['host'] = 'asdf';
$dbase['user'] = 'asdf';
$dbase['pass'] = 'asdf';
$dbase['name'] = 'asdf';
$db = new DB($dbase);
// SELECT `meta_value` FROM `wp_usermeta` WHERE `meta_key`='password'
$result = $db->query("SELECT * FROM `wp_usermeta` WHERE `meta_key`='user_email'");
while ($row = $result->fetch_array()) {
echo $row['meta_value'];
}
?>
Any help on this issue would be appreciated greatly!
Try this query..
SELECT
wp1.meta_value AS first_name,
wp2.meta_value AS last_name
FROM
wp_usermeta wp1
INNER JOIN
wp_usermeta wp2
ON ( wp1.user_id = wp2.user_id )
WHERE 1
AND wp1.meta_key = "first_name"
AND wp2.meta_key = "last_name";
GROUP BY wp1.user_id;
You're already looping over these rows, just inspect the meta_key.
$fname="";
$lname="";
while ($row = $result->fetch_array())
{
if ($row['meta_key'] == "first_name")
{
$fname = $row['meta_value'];
}
else if ($row['meta_key'] == "last_name")
{
$lname = $row['meta_value'];
}
}
echo $fname . " " . $lname;
lastly, your sql is incorrect:
SELECT * FROM `wp_usermeta` WHERE `user_id` IN (SELECT `user_id` FROM `wp_usermeta` WHERE `meta_key` = 'user_email' AND `meta_value` = "$user_email_passed_in")
In this case the MySQL query that you're doing is wrong.
It might be
$result = $db->query("SELECT * FROM `wp_usermeta` WHERE (`meta_key`='first_name' OR `meta_key`='last_name')");
In this case all rows matching 'first_name' OR 'last_name' in 'meta_key' field will be returned.
I think you'll have to distinguish these fields using also user_id field as discriminant.
Best regards

Categories