Removing double qoute in json_encode / PHP - php

I need some help with JSON and PHP. Here's my code in PHP:
include 'class.Connection.php';
$branch = $_GET["b"];
$records = array();
$sqlNailDisplay = "SELECT NAD_ID FROM tbl_NailArtDesign WHERE NAD_Available = 1";
$query0 = mysql_query($sqlNailDisplay) or die(mysql_error());
while($rSet0 = mysql_fetch_array($query0, MYSQL_BOTH)) {
$actualPrice = 0.00;
$nailart = $rSet0["NAD_ID"];
//please note, { is the ascii code for '{', } is the ascii code for '}', while " is the ascii code for '"'
$mergedData = "{"NAD_ID":"".$nailart."","";
//individual nail art details
$sqlNailArt = "SELECT * FROM tbl_NailArtDesign WHERE NAD_ID = '".$nailart."' AND NAD_Available = 1";
$query1 = mysql_query($sqlNailArt) or die(mysql_error());
while($rSet1 = mysql_fetch_array($query1, MYSQL_BOTH)) {
$NAD_Ext = $rSet1["NAD_Ext"];
$CC_ID = $rSet1["CC_ID"];
$CT_ID = $rSet1["CT_ID"];
$CST_ID = $rSet1["CST_ID"];
if(empty($CST_ID)) {
$CST_ID = "null";
}
$NAD_Descrip = $rSet1["NAD_Descrip"];
$mergedData = $mergedData."NAD_Ext":"".$NAD_Ext."","CC_ID":"".$CC_ID."","CT_ID":"".$CT_ID."","CST_ID":"".$CST_ID."","NAD_Descrip":"".$NAD_Descrip."","";
}
//product used and price details
$sqlProductsUsed = "SELECT PL_ID FROM tbl_ProductUsed WHERE NAD_ID = '".$nailart."'";
$query2 = mysql_query($sqlProductsUsed) or die(mysql_error());
while($rSet2 = mysql_fetch_array($query2, MYSQL_BOTH)) {
$PL_ID = $rSet2["PL_ID"];
$sqlProductPrice = "SELECT PP_Amount FROM tbl_ProductPrice WHERE PL_ID = ".$PL_ID." AND BL_ID = '".$branch."'";
$query3 = mysql_query($sqlProductPrice) or die(mysql_error());
while($rSet3 = mysql_fetch_array($query3, MYSQL_BOTH)) {
$price = number_format($rSet3["PP_Amount"],2);
$actualPrice = number_format($actualPrice + $price,2);
}
$mergedData = $mergedData."PL_ID":"".$PL_ID."","PP_Amount":"".$price."","";
}
$mergedData = $mergedData."NAD_Price":"".$actualPrice.""}";
$records[] = $mergedData;
} mysql_free_result($query0);
echo json_encode($records);
And this is the result I'm getting:
["{"NAD_ID":"ND0001","NAD_Ext":"jpg","CC_ID":"1","CT_ID":"1","CST_ID":"null","NAD_Descrip":"Giving you the aquatic feeling with Turquoise Marble","PL_ID":"1","PP_Amount":"9.00","PL_ID":"2","PP_Amount":"9.10","PL_ID":"3","PP_Amount":"9.00","NAD_Price":"27.10"}","{"NAD_ID":"ND0002","NAD_Ext":"jpg","CC_ID":"1","CT_ID":"1","CST_ID":"null","NAD_Descrip":"Add a twirl in your life with Lavender Twirl","PL_ID":"1","PP_Amount":"9.00","PL_ID":"2","PP_Amount":"9.10","PL_ID":"3","PP_Amount":"9.00","NAD_Price":"27.10"}"]
I need my result to look like this:
[{"NAD_ID":"ND0001","NAD_Ext":"jpg","CC_ID":"1","CT_ID":"1","CST_ID":"null","NAD_Descrip":"Giving you the aquatic feeling with Turquoise Marble","PL_ID":"1","PP_Amount":"9.00","PL_ID":"2","PP_Amount":"9.10","PL_ID":"3","PP_Amount":"9.00","NAD_Price":"27.10"},{"NAD_ID":"ND0002","NAD_Ext":"jpg","CC_ID":"1","CT_ID":"1","CST_ID":"null","NAD_Descrip":"Add a twirl in your life with Lavender Twirl","PL_ID":"1","PP_Amount":"9.00","PL_ID":"2","PP_Amount":"9.10","PL_ID":"3","PP_Amount":"9.00","NAD_Price":"27.10"}]
There an extra double quotes that I need to remove from my output.
["{" , ",*"* , }"]
Please help, I'm already at my limit and I already did searching for this, and I can't seem to get any resolution for this...

Hardcoded method:
$result = "[".substr(json_encode($records), 2, -2)."]";
$result = str_replace('","', ',', $result);

Related

How to make json like this from database mysql using php

{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
}
i try this
<?php
include 'koneksi.php';
$idbarang = $_GET['id'];
if($idbarang == !null){
$query = mysqli_query($conn, "SELECT * FROM data_barang WHERE id_barang = '$idbarang'");
$result = array();
$i= 0;
while($row = mysqli_fetch_array($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
} else {
$query = mysqli_query($conn, "SELECT * FROM data_barang");
$result = array();
$i= 0;
while($row = mysqli_fetch_assoc($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
}
?>
and this the result
[
{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
},
{
"idbarang": "ID-96037284",
"namabarang": "Sampoerna",
"jenisbarang": "Rokok",
"hargabarang": "12000"
}
]
I think you are asking why you are always going through the ELSE and never the IF. Thats because of this IF test
if($idbarang == !null){
Instead try
<?php
include 'koneksi.php';
if(!empty($_GET['id'])){
$idbarang = $_GET['id'];
You could also simplify that code quite a lot, and protect it from SQL Injection.
// Do the renaming of column names as part of the query
$sql = 'SELECT id_barang as idbarang, nama_barang as namabarang,
jenis_barang as jenisberang, jenis_barang as hargabarang
FROM data_barang';
if(!empty($_GET['id'])){
// add the WHERE clause on to the base query
$sql .= ' WHERE id_barang = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$res = $stmt->get_result();
} else {
$res = $conn->query($sql);
}
// as the renaming is done we can just fetch all the results and convert to a JSON document
$result = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);

PHP - mysqli_fetch_assoc, 2 results then into an array

$caballoganador = rand(1,9);
$selectganadores3 = array();
$arrayresultados = array();
$selectGanadores ="SELECT `usuario` from `jugadacaballo` WHERE `caballo` =' $caballoganador'";
$selectGanadores1 = mysqli_query($conn, $selectGanadores);
while($selectganadores2 = mysqli_fetch_assoc($selectGanadores1)){
$selectganadores3 = $selectganadores2['usuario'];
array_push($arrayresultados,$selectganadores3);
}
Why the results are not pushing into the array? I'm new with Programming, sorry for my errors.
Try it with $arrayresultados[]
$caballoganador = rand(1,9);
$selectganadores3 = array();
$arrayresultados = array();
$selectGanadores ="SELECT `usuario` from `jugadacaballo` WHERE `caballo` ='$caballoganador'";
$selectGanadores1 = mysqli_query($conn, $selectGanadores);
while($selectganadores2 = mysqli_fetch_assoc($selectGanadores1)){
$arrayresultados[] = $selectganadores2['usuario'];
}

Problematic url query

I have this php script that gives me a json response.
<?php
include("init.php");
$string="";
$newString="";
$get_posts = "select * from books_table";
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
And the json I get
[{"title":"Clean Code","author":"Robert Martin","bookUrl":"http:\/\/amzn.to\/1DJybxH","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/clean_code.jpg\"","displayDate":"August 11, 2008","numberOfPages":"464"},{"title":"Effective Java","author":"Joshua Bloch","bookUrl":"http:\/\/amzn.to\/1Ku8Xel","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/effective_java.jpg","displayDate":"May 28, 2008","numberOfPages":"346"},{"title":"Working Effectively with Legacy Code","author":"Michael Feathers","bookUrl":"http:\/\/amzn.to\/1Jqe1PA","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/legacy_code.jpg","displayDate":"October 2, 2004","numberOfPages":"456"},{"title":"Refactoring: Improving the Design of Existing Code","author":"Martin Fowler","bookUrl":"http:\/\/amzn.to\/1Lx4cjR","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/refactoring.jpg","displayDate":"July 8, 1999","numberOfPages":"464"}]
I want to perform a query that will return the object whose title contains the word clean.
So I am using this url
[http://www.theo-android.co.uk/books/sample_data.php/q=clean][1]
Hoewever,I get the same json response as before. The object or objects are not filtered out. Why is this happening?
Thanks,
Theo.
If I understand correctly, you want sample_data.php to be able to return filtered data?
first of all, you'll need to update sample_data.php to handle the q param (I would use it as GET since it's simpler: http://www.theo-android.co.uk/books/sample_data.php?q=clean
<?php
include("init.php");
$string="";
$newString="";
$query = mysqli_real_escape_string($con,$_GET['q']); // get and escape the q param
$get_posts = "select * from books_table";
if($query != '') $get_posts .= " WHERE title LIKE '%{$query}%'"; // if $query is not empty string - query using a wild card
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
this way $posts_row will only have the relevant books
--ADDITION----
show book json by id
http://www.theo-android.co.uk/books/sample_data.php?id=1
<?php
include("init.php");
$string="";
$newString="";
$query = mysqli_real_escape_string($con,$_GET['q']); // get and escape the q param
$id = (int)$_GET['id']; // get and cast to int the id var from GET
$where_cond = array();
$get_posts = "select * from books_table";
if($query != '') $where_cond[] = " title LIKE '%{$query}%'"; // if $query is not empty string - query using a wild card
if($id > 0) $where_cond[] = " id = {$id}"; // if $id is a number
if(!empty($where_cond)) $get_posts .= " WHERE " . implode(" AND ",$where_cond);
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
because you want it to work for both id and q (and just one of them) I'm inserting each condition to an array and then implode it with AND separator
it's untested.

PHP Fusing two arrays

How to connect 2 arrays? I want that $new[$code]=$color, how can I do this? Below is my code:
$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
$code[] = $row['user_id'];
$color[] = $row['user_color'];
}
Declare the variable outside the while loop
$new = array();
Then inside while loop
$new[$row['user_id']] = $row['user_color'];
In the while loop...
$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
$new[$row['user_id']] = $row['user_color'];
}
If you need the arrays seperate for some reason you can do it later using array_combine, http://php.net/manual/en/function.array-combine.php.
$sql = "SELECT user_id, user_color FROM dotp_users";
$result = mysql_query($sql) or die(mysql_error());
$code = $color = array();
while($row = mysql_fetch_assoc($result)) {
$code[] = $row['user_id'];
$color[] = $row['user_color'];
}
...
$new = array_combine($code, $color);

SQL won't work? It doesn't come up with errors either

I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!

Categories