SQL database values echoing twice - php

Database:
table #1: xx_users (id, name, user_id, location, network)
table #2: xx_questions (id, user_id, time)
Code:
$friends = $facebook->api('/me/friends');
$arr = $friends['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
$friend_ids_arr[] = $friend['id'];
}
$sql = "SELECT q.*, u.location, u.network
FROM xx_questions q
JOIN xx_users u
ON q.user_id = u.user_id
AND (q.user_id = $user) OR
q.user_id IN (".implode(',', $friend_ids_arr).") OR
u.location = (SELECT location FROM xx_users WHERE user_id = $user) OR
u.network = (SELECT network FROM xx_users WHERE user_id = $user)
ORDER BY q.time DESC";
$data = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($data)) {
if ($row['anon'] == 1) {
$asker = "<span style='color: #333;'>Anonymous</span>";
}
else {
$asker_name = json_decode(file_get_contents("http://graph.facebook.com/".$row['user_id']))->name;
$asker = "<a href='user.php?id=".$row['user_id']."'><b>".$asker_name."</b></a>";
}
echo "<div class='question'>";
echo "<a href='q.php?id=".$row[id]."' class='left'>".$row['question']."</a><span style='color: #666'> ";
$sql2 = "SELECT * FROM xx_answers WHERE question_id = '".$row[id]."'";
$result = mysql_query($sql2);
$xxx = mysql_num_rows($result);
echo "($xxx)";
echo "</span>";
echo "<div class='right'><span style='color: #999'>";
$to_time = strtotime("now");
$from_time = strtotime(".$row[time].");
$since = $to_time-$from_time;
time_since($since);
echo " by <a href='user.php?id=".$row['user_id']."'><b>".$asker."</b></a></span></div>";
echo "<div style='clear:both;'></div>";
echo "</div>";
}
I am using this code to echo three sorts of questions from the database:
Where the user is Facebook friends with the poster
Where the user is in the same location as the poster
Where the user shares a network with the poster
This all works fine except all of the values are echoed twice. The weird thing is that when I only echo one of the above 3, the values are only echoe once as intended. Any idea why this is happening?

Related

Display table count in html

I trying to create the backend for a booking system and need to show all booked appointments on each date for each location. My appointments table looks like this:
id, booked_date, location_id, customer_id
and I would like to display this in a html table like this:
Date 1
Date 2
Location 1 Name
Number of booked appointments
Number of booked appointments
Location 2 Name
Number of booked appointments
Number of booked appointments
I have a separate table of Locations that has full details like and and address.
I also have a table of event dates (id, start_date)
Im struggling to comprehend what I need to do here!
EDIT:
I just need some help putting everything together into the example table above.
Database tables : appointments, locations, event_dates
I have this query and the function below - SELECT t1.location_id, t1.start_datetime, t2.name, COUNT(*) AS count FROM appointment t1 INNER JOIN location t2 ON t1.location_id = t2.id GROUP BY t1.location_id, t1.start_datetime
function countAppointment() {
require 'config.php';
$sql = "SELECT t1.location_id, t1.start_datetime, t2.name, COUNT(*) AS count
FROM appointment t1
INNER JOIN location t2
ON t1.location_id = t2.id
GROUP BY t1.location_id, t1.start_datetime";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$a1 = $row['start_datetime'];
$a2 = $row['location_id'];
$a3 = $row['name'];
$a4 = $row['count'];
//echo "$a1 <br> $a2 <br> $a3 <br> $a4 <br><br>";
echo "<tr><th scope='row'>$a3</th>";
echo "<td><a href='#'>$a4</a></td>";
echo "<td>9</td><td>27</td><td>14</td></tr>";
}
} else {
return "0";
}
$conn->close();
}
try this code
<?php
$con = new mysqli("localhost","root","","test");
// Check connection
if ($con -> connect_errno) {
echo "Failed to connect to MySQL: " . $con -> connect_error;
exit();
}
$data = array();
$date_list= array();
$sql_date_list ="SELECT start_datetime from appointment GROUP BY start_datetime";
$result_date_list = mysqli_query($con, $sql_date_list);
$sql_loc_list = "SELECT `name` FROM `location` GROUP BY `name`";
$result_loc_list = mysqli_query($con, $sql_loc_list);
$k=0;
while ($row =mysqli_fetch_assoc($result_loc_list)){
$data +=[$row['name']=>array()];
if($k==0){
while($row2 =mysqli_fetch_assoc($result_date_list)){
array_push($date_list,$row2['start_datetime']);
$data[$row['name']]+=[$row2['start_datetime']=>0];
}
$k++;
}else{
foreach($date_list as $date){
$data[$row['name']]+=[$date=>0];
}
}
}
$sql_getdata = "SELECT t2.name as loc_name, t1.start_datetime, COUNT(t1.location_id) AS count FROM appointment t1 JOIN location t2 ON t1.location_id = t2.id GROUP BY t1.location_id,t1.start_datetime";
$result = mysqli_query($con, $sql_getdata);
while($row =mysqli_fetch_assoc($result)){
$data[$row['loc_name']][$row['start_datetime']]=$row['count'];
}
$table="<table border='1'>";
$table.="<tr>";
$table.="<th>location</th>";
foreach ($date_list as $date) {
$table.="<th>".$date."</th>";
}
$table.="</tr>";
foreach ($data as $key=>$date) {
$table.="<tr>";
$table.="<td>".$key."</td>";
foreach($date as $key2=>$count){
$table.="<td>".$count."</td>";
}
$table.="</tr>";
}
$table.="<table>";
echo $table;
?>
output

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;
}

Fetch assoc error

Hello
i'm trying to make a table with this query but i cant get it to work. the thing is that it cant select 2 query's at a time but i dont know another way for it..
$active_ids = '1, 3, 4';
$query = "SELECT * FROM users WHERE id IN ({$active_ids})";
$result = $mysqli->query($query);
$query = "SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj";
$result = $mysqli->query($query);
while($row = $result->fetch_assoc()){
echo $row['username'], "<br/>";
echo $row['n'], "<br/>";
}
Try this:
$active_ids = '1, 3, 4';
$result = $mysqli->query("
(SELECT * FROM users WHERE id IN ({$active_ids}))
UNION
(SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj)
") ;
if (!$rec = mysqli_fetch_array($result)) {
echo ("Sorry, no records found");
}
else {
do {
echo ($rec["username"]);
echo "<br />";
echo ($rec["n"]);
echo "<br />";
}
while ($rec = mysqli_fetch_array($result));
}
$active_ids = '1, 3, 4';
$query = "SELECT users.* from users
LEFT JOIN timetable ON users.id=timetable.dj
WHERE users.id IN ({$active_ids})
UNION
SELECT timetable.dj,timetable.count(*) as n from timetable
RIGHT JOIN users ON timetable.dj=users.id
WHERE timetable.dj IN ({$active_ids}) GROUP BY timetable.dj
";
$result = $mysqli->query($query);
while($row = $result->fetch_assoc()){
echo $row['username'], "<br/>";
echo $row['n'], "<br/>";
}
I don't know it is certainly true but can you try this code ?

i have difficulties with the sql part

I posted a code below about my website. In this code i want to update rows in my database, if the user changed the name of the topic on the website's form. Everything is working except the sql part. I mean the part where:"LIMIT 1 OFFSET '$x'" this part of the sql code is not good for some reason, but i don't know why. I tested it in xampp phpmyadmin and it works but here something just wrong.
<?php
$sql = "SELECT topicname, username, created, COUNT(commentid)
FROM user, topic, comment
WHERE topic.topicid = comment.whichtopic
AND user.userid = topic.owner
AND user.username = '" . $_SESSION['user_name '] . "'
GROUP BY topicname ";
$lekerdezes = mysql_query($sql);
$num_rows = mysql_num_rows($lekerdezes); ?>
<?php
if (isset($_POST['delete']))
{
if (!empty($_POST['forumnev']))
{
for ($x = 0; $x < $num_rows; $x++)
{
foreach ($_POST['forumnev'] as $selected)
{
$seged = mysql_query("SELECT created FROM topic WHERE
created IN (SELECT created FROM user, topic, comment WHERE topic.topicid = comment.whichtopic
AND user.userid = topic.owner AND user.username = '" . $_SESSION['user_name '] . "'
GROUP BY topicname ORDER BY created)
LIMIT 1 OFFSET '$x'");
if (!$seged)
{
echo mysql_error();
}
$seged2 = mysql_fetch_array($seged);
$seged2 = $seged2[0];
if (!$seged2)
{
echo mysql_error();
}
$sql = mysql_query("UPDATE topic SET topicname = '$selected' WHERE created = '$seged2'");
}
}
header("Location: topicedit.php");
}
}
?>
Try updating as follows:(Hope your limit: 1 and offset: $x)
$seged = mysql_query("SELECT created FROM topic WHERE created IN (SELECT created
FROM user,topic,comment
WHERE topic.topicid = comment.whichtopic
AND user.userid = topic.owner
AND user.username = '". $_SESSION['user_name'] ."'
GROUP BY topicname
ORDER BY created)
LIMIT $x, 1");

parametr's from mysql_fetch_assoc() don't want to displays ;

i can't understand why echo don't displays value. Query return values in phpmyadmin sow query is fine. Please help
$query="SELECT `doctor_name` , `doctor_secondname`
FROM `doctors`
INNER JOIN `patients` ON `patients`.doctor_id = `doctors`.doctor_id
WHERE `patients`.patient_id = '{.$patient_id.}'" ;
$result = mysql_query($query) or die(mysql_error());
print_r($row);
if(mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
echo "Your doctor is :";
echo $row['doctor_name'];
echo $row['doctor_secondname'];
}
Try This:
$query="SELECT doctor_name , doctor_secondname
FROM doctors
INNER JOIN patients ON patients.doctor_id = doctors.doctor_id
WHERE patients.patient_id = '".$patient_id."'" ;

Categories