I tried to push a new array value to JSON
$var=array("code"=>"100");
$sql = SELECT order as orderID, pub as orderCode from cart
while ($row = mysql_fetch_assoc ($sql) {
$var[] = $row;
}
echo '{"status":'. json_encode($var).'}';
I want push this string to the JSON array above
$string = array("total"=>"3000");
and my script displays like this:
{
"status":{
"code":"100",
"0":{
"total":"3000"
},
"1":{
"orderID":"16",
"orderCode":"14290290685322"
},
"2":{
"total":"3000"
}
}
}
and I want var total inside like this:
**////////blablabla
"1":{
"orderID":"16",
"orderCode":"14290290685322",
"total":"3000"
}
*///blablba
Add $var[] = array("total"=>"3000"); just before you encode to JSON
$var=array("code"=>"100");
$sql = SELECT order as orderID, pub as orderCode from cart
while ($row = mysql_fetch_assoc ($sql) {
$row['total'] = '3000' ;
$var[] = $row;
}
echo '{"status":'. json_encode($var).'}';
Related
I am new to angularJS and has very few knowledge on javascript.
I am trying to retrieve data from database by using the $http.post method. below is what I get from the .php file.
[{
"ticketid": "1484637895",
"categoryid": "1",
"subcategoryid": "2",
"ciphonenum": "01814149028",
"calldescription": "The customer wanted to know all the SKU of Bashundhara Baby Diaper and he requested to inform him through the mail.",
"ccrreply": "CCR sent him all SKU of Diaper including the M.R.P.",
"ccraction": "N\/A",
"output": "N\/A",
"remarks": "N\/A",
"contactinfoname": "MD.Masud",
"ciaddress": "Banani,DOHS\nDhaka."
}]
Here is what my php file looks like
<?php
$data = json_decode(file_get_contents("php://input"));
require 'db-config.php';
$ticketid = $data->id;
$sql = "SELECT t.ticketid, t.categoryid, t.subcategoryid, td.ciphonenum, td.calldescription, td.ccrreply,
td.ccraction, td.output, td.remarks, ci.contactinfoname, ci.ciaddress FROM ticketdetails td
INNER JOIN tickets t on t.ticketid = td.ticketid
INNER JOIN contactinfodetails ci ON ci.ciphonenum = td.ciphonenum WHERE t.ticketid = '$ticketid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($data);
$conn->close();
?>
Below is the function in angularjs which generate the post request
$scope.showTicket = function() {
var id = $routeParams.id;
$http.post('api/showTicket.php',{'id':id}).then(function(response){
$scope.ticket = response.data;
console.log($scope.ticket);
});
};
I want display only the ticketid and calldescription from the array but whenever I assign value like
$scope.ticketid = $scope.ticket.ticketid;
it says undefined variable. Please help....
Your JSON is an array of objects, and not an object.
So instead of doing $scope.ticketid = $scope.ticket.ticketid, try:
$scope.ticketid = $scope.ticket[0].ticketid;
As your array only contains one object, it is probably the solution...
i have an ajax call that gets back json i am trying to send the items returned to specific input text id's.
This is the ajax:
$.ajax({
url: "php/myfirstfile.php",
type: "POST",
data: $("#frameroof").serialize(),
cache: false,
dataType: "json",
success: function (json) {
$.each(json, function () {
$.each(json, function (key, value) {
/// do stuff
$('#' + key ).val(value);
});
});
}
});
This is what is returned: [{"a-frame":"100"}][{"vertical":"350"}]
it looks im getting 2 arrays when i need one to loop over. Im not sure.
Here is the php
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
$results = array();
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
//dump all data from associative array converted from query result
echo (json_encode($results,true));
$result->free();
}
}
}
}
$short_connect->close();
I believe your problem is pretty simple. Inside of your loop you're initializing the results array and you're outputting it. This causes a new results array to be created, serialized to JSON, and outputted for every iteration of the loop. Thus what you're sending the browser is not JSON, but several chunks of JSON all run together.
This is the basic idea of what you need to be doing:
<?php
// Initialize the output data
$results = array();
foreach($something as $a_something) {
$results[] = do_something_to($a_something);
}
//Serialize and send the output data
echo (json_encode($results,true));
Rearranging your code with that pattern in mind produces this (which ought to work for you, and will return an empty array to the browser if your if conditions aren't met or the query doesn't return anything):
<?php
// Initialize the output data
$results = array();
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
//Add to the output data
$results[] = $row;
}
$result->free();
}
}
}
}
$short_connect->close();
//Serialize and send the output data
//dump all data from associative array converted from query result
echo (json_encode($results,true));
I'm trying to loop through my database and output all rows with a match to the joined table.
I have the following two tables:
quest_items stores all data related to an item:
join_questitems stores association between player ID and the items that player has:
JS: pass in all the necessary info to query the table...
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
var item_name = returned_data.item_name;
item_image = returned_data.item_image;
$(".questItems").html(item_name + ", " + item_image);
}
);
PHP:
$statsArray = array();
$qry =
'SELECT qi.*
FROM quest_items qi
LEFT JOIN join_questitems jqi ON (qi.item_id = jqi.item_id)
WHERE jqi.user_id = "' . $playerID . '"';
$result = $mysqli->query($qry) or die(mysqli_error($mysqli));
while ($row = $result->fetch_assoc()) {
$myrow = json_encode($row);
array_push($statsArray, $myrow);
}
$k = 0;
while ($k < count($statsArray)) {
echo $statsArray[$k];
$k++;
}
But if I just do one row, I get output, but only for one row. I need both rows:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit;
}
$(".questItems").html(item_name + ", " + item_image) gives: rice, test/path.png
Why can't I loop through the PHP array full of json_encoded rows and output them? Do I have to set item_name and item_image as arrays and loop through the arrays?
EDIT:
$(".questItems").append(item_name + ", " + item_image) doesn't work either
network output from debugger shows rows are being output, but in the first row, my UTF-8 character, fàn, is being garbled in the client output (as you can see). This is curious, as at the top of my phpscripts.php file, I put mysqli_set_charset($mysqli, "utf8");
You shouldn't encode each row separately. Put all the results in an array, and then call json_encode on that array when you're done:
while ($row = $result->fetch_assoc()) {
$statsArray[] = $row;
}
echo json_encode($statsArray);
Then in Javascript you need to loop over the returned array:
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
$.each(returned_data, function(i, e) {
var item_name = e.item_name;
var item_image = e.item_image;
$(".questItems").append(item_name + ", " + item_image + "<br/>");
});
};
);
rather than this:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit; //<--- this code breaks the while loop;
}
have this:
$quest_items = array();
while ($row = $result->fetch_assoc()) {
$quest_items[] = $row;
}
echo json_encode($quest_items);
exit;
because exit triggers the script to stop(even inside loops) so you will only get the first row.
I'm trying to loop through my database and output all rows with a match to the joined table.
I have the following two tables:
quest_items stores all data related to an item:
join_questitems stores association between player ID and the items that player has:
JS: pass in all the necessary info to query the table...
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
var item_name = returned_data.item_name;
item_image = returned_data.item_image;
$(".questItems").html(item_name + ", " + item_image);
}
);
PHP:
$statsArray = array();
$qry =
'SELECT qi.*
FROM quest_items qi
LEFT JOIN join_questitems jqi ON (qi.item_id = jqi.item_id)
WHERE jqi.user_id = "' . $playerID . '"';
$result = $mysqli->query($qry) or die(mysqli_error($mysqli));
while ($row = $result->fetch_assoc()) {
$myrow = json_encode($row);
array_push($statsArray, $myrow);
}
$k = 0;
while ($k < count($statsArray)) {
echo $statsArray[$k];
$k++;
}
But if I just do one row, I get output, but only for one row. I need both rows:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit;
}
$(".questItems").html(item_name + ", " + item_image) gives: rice, test/path.png
Why can't I loop through the PHP array full of json_encoded rows and output them? Do I have to set item_name and item_image as arrays and loop through the arrays?
EDIT:
$(".questItems").append(item_name + ", " + item_image) doesn't work either
network output from debugger shows rows are being output, but in the first row, my UTF-8 character, fàn, is being garbled in the client output (as you can see). This is curious, as at the top of my phpscripts.php file, I put mysqli_set_charset($mysqli, "utf8");
You shouldn't encode each row separately. Put all the results in an array, and then call json_encode on that array when you're done:
while ($row = $result->fetch_assoc()) {
$statsArray[] = $row;
}
echo json_encode($statsArray);
Then in Javascript you need to loop over the returned array:
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
$.each(returned_data, function(i, e) {
var item_name = e.item_name;
var item_image = e.item_image;
$(".questItems").append(item_name + ", " + item_image + "<br/>");
});
};
);
rather than this:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit; //<--- this code breaks the while loop;
}
have this:
$quest_items = array();
while ($row = $result->fetch_assoc()) {
$quest_items[] = $row;
}
echo json_encode($quest_items);
exit;
because exit triggers the script to stop(even inside loops) so you will only get the first row.
Is there anyway to convert this json data:
[
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
]
to like this:
{
"data": [[1999, 3.0], [2008, 0.9]]
}
Check type of values ("3.0" and 3.0, string and integer).
I am having hard time to figure this out, or is it even possible.
This is how I get the json data:
I have "data" table in my database where are "year" and "value" columns, I get them from database like:
$sql = mysql_query("SELECT * FROM data");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
$encodedJson = json_encode($rows);
$encodedJson = json_encode($rows);
print $encodedJson;
I am trying to create a graph from my data, and json data must be formated properly to work in Flot.
All help is appreciated!
You could map your array of objects into an multidimensional array:
var mapped = originalData.map(function (obj) {
return [ parseInt(obj.year, 10), parseFloat(obj.value) ];
});
var newData = {
data: mapped
};
Possible solution
var a = [
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
];
var b = [];
$.each(a, function(_index, _item){
var c = [_item["year"], _item["value"]];
b.push(c);
});
console.log(b)
try this.
PHP:
$sql = mysql_query("SELECT * FROM data");
$rows = $sql->results_array();
$return_args = array();
foreach($rows as $row){
$tmp[0] = $row['year'];
$tmp[1] = $row['value'];
array_push($return_args,$tmp);
}
$encodedJson = json_encode($return_args);
print $encodedJson;