How to get two mysql querie results in one JSON array? - php

in my current project I have to create a JSON array, in which for each day a status with a colour is displayed in a calendar (FullCalendar) and additionally a button with a link is to be displayed for all days where an event is planned.
For this I have two SELECT's which both work on their own. I have already tried some things how to put the results of both SELECT's into one JSON array, but I keep getting the error 'Undefinded Variable'.
How do I have to pack the results of the two SELEC T's put together that all results are displayed correctly?
header('Content-Type: application/json');
include "../../../includes/db.php";
if(isset($_GET['team_id'])) {
$team_id = $_GET['team_id'];
}
$stmt = $connection->prepare("SELECT date FROM date");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$date = $row['date'];
$team_planner_user_status_present = 1;
$team_planner_user_status_absent = 2;
$team_planner_user_status_reservation = 3;
$stmt1 = $connection->prepare("SELECT
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS present,
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS absent,
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS reservation
");
$stmt1->bind_param("sssssssss", $team_id, $date, $team_planner_user_status_present,
$team_id, $date, $team_planner_user_status_absent,
$team_id, $date, $team_planner_user_status_reservation);
$stmt1->execute();
$result1 = $stmt1->get_result();
while($row1 = $result1->fetch_array()) {
$present = $row1['present'];
$absent = $row1['absent'];
$reservation = $row1['reservation'];
if($present >= 5) {
$color = '#a1ff9e';
} else if($present + $reservation >= 5) {
$color = '#fcff9e';
} else {
$color = '#ff9e9e';
}
}
$stmt1->close();
$stmt2 =$connection->prepare("SELECT * FROM game_planned INNER JOIN game_role ON game_planned.match_role_id = game_role.match_role_id WHERE team_id = ? AND game_planned_date = ?");
$stmt2->bind_param("ss", $team_id, $date);
$stmt2->execute();
$result2 = $stmt2->get_result();
while($row2 = $result2->fetch_array()) {
$match_role_name = $row2['match_role_name'];
$game_planned_id = $row2['game_planned_id'];
}
$data[] = array(
'start' => $date,
'display' => 'background',
'color' => $color,
);
if($result->num_rows === 0) {
echo "";
} else {
$data[] = array(
'title' => $match_role_name,
'url' => 'http://localhost/r6team-redesign/team/team.php?team=details-match-plan&match_planned_id='.$game_planned_id,
'start' => $date,
);
}
}
$stmt->close();
echo json_encode($data);

Related

Can't insert data in payment table

Does anyone here know why I can't insert my data in my payment table? I just want to insert it but I'm getting this error:
Uncaught Error: Cannot use object of type stdClass as array in C:\xampp\htdocs\acz-thesis\app\models\account.php:565
Line 565: $total_amount = $row['sales_net_amount'];
Controller
public function InsertPaymentSales() {
if(isset($_SESSION['token']) == $this->input->post('token')) {
$data = array(
'payment_amount' => $this->input->post('payment_amount'),
'payment_date' => $this->input->post('payment_date'),
'payment_remark' => $this->input->post('payment_remark'),
'payment_balance' => $this->input->post('payment_balance'),
'payment_sales_id' => $this->input->post('payment_sales_id')
);
$this->model('account')->sales_payment($data);
}
}
Model
public function sales_payment($data) {
$payment_amount = $data['payment_amount'];
$payment_date = $data['payment_date'];
$payment_remark = $data['payment_remark'];
$payment_balance = $data['payment_balance'];
$payment_sales_id = $data['payment_sales_id'];
$query = $this->db->query("SELECT sales_net_amount, sales_balance FROM tbl_sales_details WHERE sales_id = $payment_sales_id");
$row = $query->fetch_object();
$total_amount = $row['sales_net_amount'];
$balance = $row['sales_balance'];
if($payment_amount >= $payment_balance && $balance > 0) {
$query = $this->db->query("INSERT INTO tbl_sales_payments (payment_amount, payment_date, sales_id, payment_remarks)
VALUES($payment_amount, '$payment_date', $payment_sales_id, '$payment_remark')");
if($query) {
$query = $this->db->query("SELECT SUM(payment_amount) as total_payments FROM tbl_sales_payments WHERE sales_id = $payment_sales_id");
$row = $query->fetch_object();
$total_payments = $row['total_payments'];
$total_balance = $total_amount - $total_payments;
$query = $this->db->query("UPDATE tbl_sales_details SET sales_balance = $total_balance WHERE sales_id = $payment_sales_id");
$message = 'Success';
$query ? notify('success', $message, true) : null;
}
} else {
$message = 'Error';
notify_amaran([false,'#4caf50','#fff',$message]);
}
}
You can try this :
$row = $query->fetch(); $total_amount = $row['sales_net_amount'];
I think that using fetch_object() on $query returns an object instead of an associative array that you want to use with $row['sales_net_amount'].
As #Definitely not Rafal has already commented you cannot access attributes as array
These lines are wrong
$total_amount = $row['sales_net_amount'];
$balance = $row['sales_balance'];
[..]
$total_payments = $row['total_payments'];
change those to
$total_amount = $row->sales_net_amount;
$balance = $row->sales_balance;
[..]
$total_payments = $row->total_payments;

UPDATE record serialized - php mysql

I have this problem, I have to update a record of a table that has the values of a serialized column. the call to the function works and passes the data correctly. I can enter the record, but I can not update. This is my code:
public function update($user_id, $array_check)
{
$arrayB = array();
$array_check = unserialize($array_check);
foreach ($array_check $key => $value) {
if($value["id"] == $array_check){
$idRow = $value["id"];
if($value["value"] == "0"){
$valueRow = "1";
}else{
$valueRow = "0";
}
}else{
$idRow = $value["id"];
$valueRow = $value["value"];
}
$row = array("id" => $idRow, "value" => $valueRow);
$arrayB[] = $row;
}
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id');
$row = $stmt->execute(array(':user_id' => $user_id, ':docs_selected' => serialize($arrayB) ) );
return $arrayB;
}
edit.
Replace this:
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id);
with:
$deseralized = serialize($arrayB);
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = '$deseralized ' WHERE user_id = '$user_id');

Categories Multi Level display using php and mysql in json format

I need to display categories and its sub categories in json format, here problem is each category has unlimited levels, some categories has 4 levels and some 2 and some 3 levels. I have tried one solution it is showing only one under level, but I need to show all levels.
Table schema:
Code Example:
function categories() {
header('Content-Type: application/json');
$sql = "select id,name,parent_id from categories where parent_id = 0";
$q = $this->db->conn_id->prepare($sql);
$q->execute();
$main_cat = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$sql2 = "select id,name,parent_id from categories where parent_id = ?";
$sub_cat = array();
$r = $this->db->conn_id->prepare($sql2);
$r->bindParam(1, $row['id']);
$r->execute();
while ($row1 = $r->fetch(PDO::FETCH_ASSOC)) {
array_push($sub_cat, array_filter($row1));
}
$row['subcategories'] = $sub_cat;
array_push($main_cat, array_filter($row));
}
echo json_encode(array("categories" => $main_cat));
}
Above Code Json Response Example:
{"categories":[{"id":"1","name":"Development","subcategories":[{"id":"2","name":"All Development","parent_id":"1"},{"id":"3","name":"Web Development","parent_id":"1"},{"id":"12","name":"Mobile Apps","parent_id":"1"}]},{"id":"4","name":"Design","subcategories":[{"id":"5","name":"All Design","parent_id":"4"}]},{"id":"11","name":"IT & Software"}]}
Any one can help me how to solve this issue.
I have tried this solution works for me.
function categories() {
$sql = "SELECT * FROM categories where parent_id = 0";
$results = $this->db->conn_id->prepare($sql);
$results->execute();
while ($result = $results->fetch(PDO::FETCH_ASSOC)) {
$subcat = array();
$id = $result['id'];
$childs = $this->hasChilds($id);
$categories[] = array("id" => $result['id'], "name" => $result['name'], "parent_id" => $result['parent_id'], "subcats" => array_filter($childs));
}
echo json_encode($categories);
}
function hasChilds($id) {
$sql = "SELECT * FROM categories where parent_id = ? ";
$results = $this->db->conn_id->prepare($sql);
$results->bindParam(1, $id);
$results->execute();
$count = $results->rowCount();
$array = array();
if ($count > 0) {
while ($result = $results->fetch(PDO::FETCH_ASSOC)) {
$array[] = array("id" => $result['id'], "name" => $result['name'], "parent_id" => $result['parent_id'], "subcats" => array_filter($this->hasChilds($result['id'])));
}
} else {
$array[] = null;
}
return $array;
}

error when I add break to foreach loop

Okay, this is really frustrating me and I don't know why. I have been scouring the internet for at least two days trying to figure out the problem. I am trying to pull xp amount for a certain skill for all the names stored in the database. It echoed the specified xp for all the users in the database, but was repeating the values with an undefined index. Even though that error is there it still prints the values. I researched the internet and found that break will stop the repeating, but when I add the break it then wont print the values and just gives me the undefined index. THe index does exist.
$sql = "SELECT rsn FROM users";
$qry = $conn->prepare($sql);
$qry->execute();
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$rsn = $row['rsn'];
$hs = file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=". $rsn);
$hs = explode("\n",$hs);
$skills = array("Overall","Attack","Defence","Strength","Constitution","Ranged","Prayer","Magic","Cooking","Woodcutting","Fletching","Fishing","Firemaking","Crafting","Smithing","Mining","Herblore","Agility","Thieving","Slayer","Farming","Runecrafting","Hunter","Construction","Summoning","Dungeoneering", "Divination", "Invention");
$i = 0;
foreach(array_unique($skills) as $value){
$hs[$i] = explode(",",$hs[$i]);
$stats[$value]["rank"] = number_format($hs[$i][0]);
$stats[$value]["level"] = number_format($hs[$i][1]);
$stats[$value]["xp"] = number_format($hs[$i][2]);
$i++;
/*require_once 'tourny_config_include.php';
$sql = "UPDATE active_tourny SET xp = :xp AND from_date = :from AND to_date = :to WHERE rsn = :rsn";
$qry = $conn->prepare($sql);
$qry->execute(array(':xp' => $xp, ':rsn' => $rsn, ':to' => $tournyTo, ':from' => $tournyFrom));*/
echo $stats["Attack"]["xp"] . '<br>';
break;
}
}
$qry = $conn->prepare($sql);
$qry->execute();
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$rsn = $row['rsn'];
$hs = file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=". $rsn);
$hs = explode("\n",$hs);
$skills = array("Overall","Attack","Defence","Strength","Constitution","Ranged","Prayer","Magic","Cooking","Woodcutting","Fletching","Fishing","Firemaking","Crafting","Smithing","Mining","Herblore","Agility","Thieving","Slayer","Farming","Runecrafting","Hunter","Construction","Summoning","Dungeoneering", "Divination", "Invention");
$i = 0;
foreach($skills as $skill){
$hs[$i] = explode(",",$hs[$i]);
$stats[$skill]["rank"] = number_format($hs[$i][0]);
$stats[$skill]["level"] = number_format($hs[$i][1]);
$stats[$skill]["xp"] = number_format($hs[$i][2]);
$i++;
/*require_once 'tourny_config_include.php';
$sql = "UPDATE active_tourny SET xp = :xp AND from_date = :from AND to_date = :to WHERE rsn = :rsn";
$qry = $conn->prepare($sql);
$qry->execute(array(':xp' => $xp, ':rsn' => $rsn, ':to' => $tournyTo, ':from' => $tournyFrom));*/
// display Attack xp if available
if isset($stats["Attack"]["xp"])
echo $stats["Attack"]["xp"] . '<br>';
}
}
Wow I cannot believe that it was this simple. All I had to do is move
echo $stats["Attack"]["xp"] . '<br>';
outside the foreach loop

Joomfish migration script returns error

Here is a script that upgrades joomfish (joomla translation component) from joomla 1.5 to 2.5:
$db = new PDO("mysql:host=localhost;dbname=db;charset=UTF8", "root", "pass");
$stmt = $db->prepare("select distinct(jfc.reference_id),c.catid,jfc.language_id,c.modified,c.modified_by,c.version,c.modified_by ,c.ordering,c.created_by,c.metadesc ,c.created_by_alias from jos_jf_content jfc ,jos_content c where jfc.reference_id = c.id and jfc.reference_table = 'content' ");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$count_row = $db->prepare("select * from jos_jf_content where reference_id = ? and language_id = ?");
$count_row->bindValue(1, $row['reference_id']);
$count_row->bindValue(2, $row['language_id']);
$lang_code = $db->prepare("select lang_code from j25_languages where lang_id = ?");
$lang_code->bindValue(1, $row['language_id']);
$lang_code->execute();
$l_code = $lang_code->fetch(PDO::FETCH_OBJ);
$language_code = $l_code->lang_code;
$count_row->execute();
$title ="";
$fulltext ="";
$introtext ="";
$alias ="";
$published ="";
while($col = $count_row->fetch(PDO :: FETCH_ASSOC))
{
if($col['reference_field'] == "title")
{
$title = $col['value'];
}
if($col['reference_field'] == "fulltext")
{
$fulltext = $col['value'];
}
if($col['reference_field'] == "introtext")
{
$introtext = $col['value'];
}
if($col['reference_field'] == "alias")
{
$alias = $col['value'];
}
$published = $col['published'];
}
$exe = $db->prepare("insert into j25_content (`title`,`alias`,`introtext`,`fulltext`,`published`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`version`,`ordering`,`metadesc`,`language`) values(:title,:alias,:introtext,:fulltext,:published,:categoryid,:created,:created_by,:created_by_alias,:modified,:modified_by,:version,:ordering,:metadesc,:language_code)");
$exe->execute(array(':title' => $title,':alias' => $alias,':introtext' => addslashes($introtext),':fulltext' => addslashes($fulltext),':published' => ".$published.",':categoryid' => $row['catid'],':created' => date("Y-m-d H:i:s"),':created_by' => $row['created_by'],':created_by_alias' => "".$row['created_by_alias']."",':modified' => date("Y-m-d H:i:s"),':modified_by' =>$row['modified_by'],':version' => $row['version'],':ordering' => $row['ordering'],':metadesc' => $row['metadesc'],':language_code' => $language_code));
$i = $db->lastInsertId('id');
$asst = $db->prepare("select asset_id from j25_categories where id = ? ");
$asst->bindValue(1, $row['catid']);
$asst->execute();
$asst_id = $asst->fetch(PDO::FETCH_OBJ);
$cassetid = $asst_id->asset_id;
$sel = $db->prepare("select lft,rgt FROM `j25_assets` where id = (SELECT max(id) FROM `j25_assets`)");
$sel->execute();
$select = $sel->fetch(PDO::FETCH_OBJ);
$left = $select->lft;
$right = $select->rgt;
$left=$left+1;
$right = $right+1;
$stmt = $db->prepare("insert into j25_assets (`parent_id`,`lft`,`rgt`,`level`,`name`,`title`) values(:cassetid,:left,:right,:level,:name,:title)");
$stmt->execute(array(':cassetid' => $cassetid,':left' => $left,':right' => $right,':level' => 4,':name' => "com_content.article.".$i,':title' => $title));
$insertedId = $db->lastInsertId('id');
$update = $db->prepare("update j25_content set asset_id = ? where id = ?");
$update->bindValue(1, $insertedId);
$update->bindValue(2, $i);
$update->execute();
$stmt = $db->prepare("insert into j25_jf_translationmap (language,reference_id,translation_id,reference_table) values (:language_code,:reference_id,:translation_id,:content)");
$stmt->execute(array(':language_code' => $language_code,':reference_id' => $row['reference_id'],':translation_id' => $i,':content' => 'content'));
}
Line of code:
$language_code = $l_code->lang_code;
Returns:
Trying to get property of non-object
I'm not an author of the script and not good in PHP, but I've tried to print_r($l_code->lang_code); and I got expected result en-GB from [lang_code] => en-GB. What I need to change in this code? Thanks.
The line $language_code = $l_code->lang_code > 0; sets $language_code to boolean value. Try var_dump($l_code); and var_dump($language_code); to debug your results. You should also check if $l_code actually is an object, or perhaps null was returned. Hope that helps.

Categories