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).
Related
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;
}
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*
I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}
I'm trying to fetch a list of values from MySQL table using query1 and then use them in query2 to fetch values. Query1 gives 4 values however Query2 gives output matching the last value of Query1.
Following is my controller code
public function example_ctl(){
$data['result'] = $this->some_model->example();
}
Following is my model code
public function example() {
$query = "select m.queue_id from agent_queue_mapping_table as m, user_table as u where u.id=m.user_id and m.company_id = ".$this->session->userdata('user_comp_id')." and u.id = ".$this->session->userdata('user_id');
$res = $this->db->query($query);
foreach ($res->result_array() as $value) {
$queue_ids = implode(',', $value);
}
$query_ticket = "select * from tickets_table where company_id = ".$this->session->userdata('user_comp_id')." and ticket_status = 'New' and queue_id IN (".$queue_ids.") ORDER BY id DESC LIMIT 3";
$res_ticket = $this->db->query($query_ticket);
return $res_ticket->result_array();
}
I'm not able to understand where I'm going wrong. Please help.
try changing your code into this
<?php
$queue_id = array();
foreach ($res->result_array() as $value) {
$queue_id[] = $value;
}
$queue_id = implode(",",$value);
?>
$queue_id is overridden inside the loop each time loop executes that is why you get last value
This is how I fixed this issue.
$query = "select m.queue_id from agent_queue_mapping_table as m, user_table as u where u.id=m.user_id and m.company_id = ".$this->session->userdata('user_comp_id')." and u.id = ".$this->session->userdata('user_id');
$res = $this->db->query($query);
foreach ($res->result_array() as $value) {
$queue_ids[] = $value['queue_id'];
}
$queue_id = implode(',', $queue_ids);
$query_ticket = "select * from tickets_table where company_id = ".$this->session->userdata('user_comp_id')." and ticket_status = 'New' and queue_id IN (".$queue_id.") ORDER BY id DESC LIMIT 3";
$res_ticket = $this->db->query($query_ticket);
return $res_ticket->result_array();
i have a table with staff_id and subjects, i want to display all staffs according to their subjects.
my table
result i want
Physics
-001
-004
-006
Chemistry
-002
-009
Biology
-003
-008
Mathematics
-005
My code
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
echo $subject .'</br>';
echo $staff_id.'</br>';
}
but this doesn't give the result i want.
any help?
What you need is ORDER BY.
Change your query to:
SELECT STAFF_ID, SUBJECT FROM my_table ORDER BY SUBJECT, STAFF_ID
So you get the records in the right order to work with them.
Something like this?
$q = mysql_query("SELECT `staff_id`, `subject` FROM `my_table`;");
$data = array();
while($row = mysql_fetch_array($q)){
$data[$row['subject']][] = '-'.$row['staff_id'];
}
print_r($data);
Or to echo out the rows
foreach($data as $heading => $rows){
echo $heading.'<br>';
foreach($rows as $row){
echo $row.'<br>';
}
}
You can write your code like this below:
$q = mysql_query("SELECT * FROM my_table ORDER BY SUBJECT, STAFF_ID");
while($row = mysql_fetch_array($q)){
//Do staff
}
The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.
$subjects = array();
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
if ($subjects[$row['SUBJECT']] == nil) {
$subjects[$row['SUBJECT']] = array();
}
array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']);
}
foreach ($subjects as $key=>$value) {
echo $key . '<br>;
foreach ($vaue as &$staff) {
echo $staff . '<br>';
}
}
$result=mysql_query("SELECT * from table GROUP BY subject");
while($ext=mysql_fetch_object($result)) {
$query=mysql_query(" SELECT * from table WHERE subject='".$ext->subject."'");
echo $ext->subject;
while($res=mysql_fetch_object($query)) {
echo $res->staff_id;
}
}