I'm building a simil web-service in php. This web service can read all record from a table of database and return a list of it in json format.
This is the code of my getArticoli.php file:
<?php
require_once('lib/connection.php');
$query_Articolo = "SELECT CodArticolo,NomeArticolo,Quantita,CodiceBarre, PrezzoAttuale, PrezzoRivenditore,PrezzoIngrosso
FROM VistaArticoli ";
$result_Articoli = $connectiondb->query($query_Articolo);
$answer = array ();
while ($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] = ["id" => $row_Articoli['CodArticolo'],
"nome" => '"' . $row_Articoli['NomeArticolo'] . '"',
"quantita" => $row_Articoli['Quantita'],
"codiceBarre" => $row_Articoli['CodiceBarre'],
"codartFornitore" => $row_Articoli['CodiceBarre'],
"PrezzoAttuale" => $row_Articoli['PrezzoAttuale'],
"prezzoRivenditore" => $row_Articoli['prezzoRivenditore'],
"prezzoIngrosso" => $row_Articoli['prezzoIngrosso']];
}
//echo "fine";
echo json_encode($answer);
?>
Now, if I try to open this page, with this url: http://localhost/easyOrdine/getArticoli.php
I don't get the json_response.
In the table of database, there are 1200 records. If I try to insert an echo message in while cycle, I see it.
I have noticed that the problem lays with this field:
"nome"=>'"'.$row_Articoli['NomeArticolo'].'"'
If I remove this field from the response, I can correctly see the json response.
In this field there are any character from a-z/0-9 and special character like "/ * ? - and other".
It is possible that these special character can cause any error of the json answer?
EDIT
I have limit at 5 my query and this is the response:
[{"id":"878","0":"ACCESSORIO PULIZIA PUNTE DISSALDANTE 3 MISURE","quantita":"1","codiceBarre":"DN-705100","codartFornitore":"DN-705100","PrezzoAttuale":"14.39","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"318","0":"ACCOPPIANTORE RJ11 TELEFONICO VALUELINE VLTP90920W","quantita":"20","codiceBarre":"5412810196043","codartFornitore":"5412810196043","PrezzoAttuale":"0.68","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"320","0":"ACCOPPIATORE AUDIO RCA VALUELINE VLAB24950B","quantita":"5","codiceBarre":"5412810214136","codartFornitore":"5412810214136","PrezzoAttuale":"1.29","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"310","0":"ACCOPPIATORE RJ45 VALUELINE VLCP89005W","quantita":"8","codiceBarre":"5412810228843","codartFornitore":"5412810228843","PrezzoAttuale":"0.38","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"311","0":"ACCOPPIATORE USB2 VALUELINE VLCP60900B","quantita":"5","codiceBarre":"5412810179596","codartFornitore":"5412810179596","PrezzoAttuale":"1.80","prezzoRivenditore":null,"prezzoIngrosso":null}]
First, remove those extraneous quote characters. You don't need them and they could hurt you down the road:
while ($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] = [
"id" => $row_Articoli['CodArticolo'],
"nome" => $row_Articoli['NomeArticolo'],
"quantita" => $row_Articoli['Quantita'],
"codiceBarre" => $row_Articoli['CodiceBarre'],
"codartFornitore" => $row_Articoli['CodiceBarre'],
"PrezzoAttuale" => $row_Articoli['PrezzoAttuale'],
"prezzoRivenditore" => $row_Articoli['prezzoRivenditore'],
"prezzoIngrosso" => $row_Articoli['prezzoIngrosso']
];
}
Then, run your query as is (without the LIMIT), and afterwards run echo json_last_error_msg()';, which could give you a hint to what's going on.
Also, being that your DB is in italian, maybe its encoding is not UTF-8. json_encode requires UTF-8 encoded data. So you may try to utf8_encode your article names before json_encoding the array:
"nome" => utf8_encode($row_Articoli['NomeArticolo']),
And see what you get.
Changing your DB charset to 'utf8mb4' could do the trick as well, and it is usually recommended.
Related
I am using this php code which works flawless for one file but when I upload multiple files generated json contains error.
$response = array('file' => ''.$file.'', 'date' => ''.date("d:m:y").'', 'save' => ''.$saving.'%');
echo json_encode($response);
If I am using one file the json output is valid
{"file":"http:\/\/xyy.com\/3\/4\/23968281479202046440249.png","date":"15:11:16","save"
:"<br>Original Size:8.3 Kb, Compressed Size:2.9Kb, Saving:65%"}
but if I am using two or more files json output is invalid and contains error.
{"file":"http:\/\/xxxxxxx.com\/4\/352118314792022053319009.png","date":"15:11:16","save"
:"Saving:68%"}{"file":"http:\/\/way2enjoy.com\/pdf\/1\/2\/3\/4\/270182314792022054204908.png","date":"15:11:16"
,"save":"Saving:65%"}
Any help will be great to make it work for multiple files.
The string with two file objects looks like a couple of JSON objects printed one after another. You should join the arrays before encoding and printing them in order to produce a valid JSON object, e.g.:
$date = date("d:m:y");
$response = [
['file' => $file1, 'date' => $date, 'save' => $saving.'%'],
['file' => $file2, 'date' => $date, 'save' => $saving.'%'],
];
// Also, use the correct MIME type for JSON content
header('Content-Type: application/json');
echo json_encode($response);
Otherwise, make separate HTTP requests for each file.
Using a javascript application I am making a server side request for a search functionality. It works for some queries, but not for others.
For some queries the GET request returns no response, despite the fact that testing the query in workbench returns thousands of records. I tried turning on errors - no errors are generated. I tried increasing memory limit - that's not the culprit. I tried to output PDO errors/warnings - nothing generated, the PDO actually returns the records, I verified this using var_dump, as shown below.
So to conclude, everything in the below code, seems to work flawlessly, until the final line that is responsible for encoding the array into a json object - it echos nothing.
I appreciate any assistance in resolving this.
PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '2048M');
$db = new PDO('mysql:host=localhost;dbname=mydb', 'root', '');
$search = $_GET['search'];
$searchBy = ( isset($_GET['searchBy']) && !empty($_GET['searchBy']) ) ? $_GET['searchBy'] : 'name';
$sql = "SELECT * FROM business WHERE name LIKE '%university%' GROUP BY id";
$query = $db->prepare($sql);
$query->execute();
$results = $query->fetchAll(); //query returns 5000+ records in under a second in workbench
$headers = array('Business', 'City', 'State', 'Zip', 'Phone');
$json = array("results" => $results, 'headers' => $headers, 'query' => $sql);
var_dump($json); //prints successfully
echo json_encode($json); // echos nothing!
EDIT:
use utf8_encode() then json_encode() as mentioned here (Special apostrophe breaks JSON)
OR
$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
will parse all the data in utf8.
Old
What's the result if you do this ?
echo json_encode($results);
//scratch those
//$json = array("results" => $results, 'headers' => $headers, 'query' => $sql);
//var_dump($json); //prints successfully
May be you run out of memory? Try with a 100 results. I know from experience with other projects that json_encode can consume a shared server's ram.
Sorry if I am not as helpful as you would like me to be but we can't really test you code, you have to do it for us.
I had this exact error when I tried to use json_encode the other day. It returned no errors... just a blank screen, and finally it hit me. The issues was with character encoding. The column I was trying to use had been used by copywriters who cut and pasted from Microsoft Word directly into the wysiwyg.
echo json_last_error() after your json_encode and see what you get
.
.
.
echo json_encode($json); // echos nothing!
echo json_last_error(); // integer if error hopefully 0
It should return an integer specifying one of the errors below.
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
In my case it returned a 5. I then had to clean every "description" column before it would work. In the event it is the same error, I've included the function you will need to run all your columns through to clean them out.
function utf8Clean($string)
{
//reject overly long 2 byte sequences, as well as characters above U+10000 and replace with *
$string = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
'|[\x00-\x7F][\x80-\xBF]+'.
'|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
'|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
'|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
'*', $string );
//reject overly long 3 byte sequences and UTF-16 surrogates and replace with ?
$string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]'.
'|\xED[\xA0-\xBF][\x80-\xBF]/S','?', $string );
return $string;
}
for more info on json_last_error() go to the source!
http://php.net/manual/en/function.json-last-error.php
It is really easy with the JSON Builder : Simple JSON for PHP
include('includes/json.php');
$Json = new json();
$Json->add('status', '200');
$Json->add('message', 'Success');
$Json->add('query', 'sql');
$Json->add("headers",$headers);
$Json->add("data",$results);
$Json->send();
Not an experienced developer and using CodeIgniter for the first time. I'm trying to grab a signed URL for a given MP3 filename stored in S3. This is currently working with the exception of files that contain brackets.
Relevant controller code:
function index ($streamfile) {
// Load S3 client
$this->load->spark('amazon-sdk');
$s3 = $this->awslib->get_s3();
// Define request parameters
$s3bucket = $userdata['s3bucket']; // defined elsewhere
$streamfiletest = ($string)'Crazy_(Remix).mp3';
// Request signed URL
$url = $s3->get_object_url($s3bucket, ***EITHER $streamfiletest or $streamfile***, '5 minutes');
// Fetch status code
$http = new CFRequest($url);
$http->add_header('Content-Type', '');
$http->send_request(true);
$code = $http->get_response_code();
$headers = $http->get_response_header();
// Load the view
$data['filename'] = $url;
$data['debug'] = array(
'file1' => $streamfile,
'file2' => $streamfiletest,
'signed_url' => $url,
'code' => $code,
'headers' => $headers
);
$this->load->view('play', $data);
Relevant view code:
<?php if (isset($debug)) {
echo "DEBUGS:";
echo '<pre>' . print_r($debug, TRUE) . '</pre>';
} ?>
As you can see I either pass $streamfile or $streamfiletest. In the debug I can confirm that both variables are the same string.
When passing $streamfile to the URL request, the URL in the response is incorrect:
DEBUGS:
[file1] => Crazy_(Remix).mp3
[file2] => Crazy_(Remix).mp3
[signed_url] => http://s3-...(removed)/Crazy_%26%2340%3BRemix%26%2341%3B.mp3?AWSAccessKey...
[code] => 404
You can see that the brackets have been strangely encoded %26%2340%3B and therefore I can't find the file in S3.
When passing $streamfiletest however, the response is fine:
DEBUGS:
[file1] => Crazy_(Remix).mp3
[file2] => Crazy_(Remix).mp3
[signed_url] => http://s3-...(removed)/Crazy_%28Remix%29.mp3?AWSAccessKey...
[code] => 200
The brackets are encoded correctly in the signed URL an I get a HTTP 200 from S3.
Any ideas what could be causing this?
In the debug I can confirm that both variables are the same string
Actually, not quite.
If you look closely, it becomes apparent what the url escaped values must mean:
%26%2340%3B %26%2341%3B
& # 40 ; & # 41 ;
Those are numeric html character codes that the browser will display as ( and ) but it does not in fact mean that the two strings have identical content. They only appear to.
The solution, of course, depends on how they are getting transformed that way, and either not doing that, or decoding the numeric character codes.
Try doing the following to decode the url encoded brackets
$data['filename'] = urldecode($url);
This should return the string to its expected format ie with brackets
I am just starting on the PHP.
I am working on getting information from WordPress database.
The plugin writes data to a DB, from the Sign up form.
What I want is to get this data formatted on my own way, let's say a table, on a separate page.
So what I did already, is to connect to a DB, and print the data. Did it by this:
<?php
//connect to the database
mysql_connect ("host","user","pasw") or die ('Cannot connect to MySQL: ' . mysql_error());
mysql_select_db ("database") or die ('Cannot connect to the database: ' . mysql_error());
//query
$query = mysql_query("select id, data from wp_ninja_forms_subs") or die ('Query is invalid: ' . mysql_error());
//write the results
while ($row = mysql_fetch_array($query)) {
echo $row['id'] . " " . $row['data'] . "
";
// close the loop
}
?>
The thing is, that I get the results, which doesn't really suit me:
14 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:8:"John Doe";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:11:"+3706555213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 1";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" Finansiniai ";}}} 15 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:10:"Bill Gates";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:11:"+5654412213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 2";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" ?vaizd˛io ";}}} 16 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:7:"Person3";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:7:"6463213";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:9:"Company 3";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:2:{i:0;s:10:" HTML/CSS ";i:1;s:12:" Photoshop ";}}} 17 a:4:{i:0;a:2:{s:8:"field_id";i:2;s:10:"user_value";s:11:"Pretty Girl";}i:1;a:2:{s:8:"field_id";i:4;s:10:"user_value";s:9:"643122131";}i:2;a:2:{s:8:"field_id";i:12;s:10:"user_value";s:4:"Zara";}i:3;a:2:{s:8:"field_id";i:8;s:10:"user_value";a:1:{i:0;s:13:" ?vaizd˛io ";}}}
Now, what I want to see is a table:
2013.10.25 Pretty Girl 643122131 Zara Įvaizdžio
2013.10.25 Person3 6463213 Company 3 HTML/CSS , Photoshop
2013.10.25 Bill Gates +5654412213 Company 2 Įvaizdžio
2013.10.25 John Doe +3706555213 Company 1 Finansiniai
Could someone tell me, how to achieve that?
I believe, that my data output is an array, or am I wrong about it too?
If yes, maybe someone could give me an example how to format one part of that array, so I could do the rest?
Or even some hint on what to google for?
Thanks!
Use "\n" for new line character :)
Your individual values (a:4:{i:0....}) have been "serialized". This one was an array of four elements that was passed to the serialize() PHP function. The function returned it's textual representation (i.e. it has "serialized" the array). So you have the entire array saved in one cell in database as simple text.
Function unserialize() does the opposite - turns the "serialized" (text) values and returns the original PHP object (an array in this case).
You can serialize almost any PHP object as long as it doesn't have some any "resources" attached to it. But there is already a separate question for that: What could cause a failure in PHP serialize function?
As long as you serialize arrays of numbers, strings and arrays and even simple objects there is nothing to worry about.
Your first cell (no 14) when unserilalized:
array (
0 =>
array (
'field_id' => 2,
'user_value' => 'John Doe',
),
1 =>
array (
'field_id' => 4,
'user_value' => '+3706555213',
),
2 =>
array (
'field_id' => 12,
'user_value' => 'Company 1',
),
3 =>
array (
'field_id' => 8,
'user_value' =>
array (
0 => ' Finansiniai ',
),
),
)
(Using: http://www.functions-online.com/unserialize.html) Run these trough a for loop or something to get the rendering you need, that's up to you.
I have such code:
for ($j = 0; $j < mysql_num_rows($subcategoriesData); $j++)
{
$subcategoriesStrResult = mysql_fetch_array($subcategoriesData);
//echo $subcategoriesStrResult['title']."<br>";
$itemFeatures = array( $subcategoriesStrResult['title'] => $subcategoriesStrResult['path']);
array_push($arrayDataSubcategoryItems, $itemFeatures);
};
array_push($mainArrayForJSON, $item = array(
'parent_id' => $subcategoriesStrResult['parent'],
'level' => $subcategoriesStrResult['level'],
'items' => $arrayDataSubcategoryItems
));
After my $mainArrayForJSON is ready I'm trying to check the json-code by the simple echo
echo json_encode($mainArrayForJSON);
Meanwhile, to be sure that I get what I need I'm checking the single value of my string by the echo too (this string is commented now) - it works OK, I see on Chrome good readable text (in database this text is stored in utf8, of course).
But last call to echo for check the prepared JSON leads me to the next output:
[{"parent_id":"8-590","level":"3","items":[{"\u041c\u0435\u0442\u0430\u043b\u043b\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043b\u043e\u0442\u043e\u043a BAKS (\u041f\u043e\u043b\u044c\u0448\u0430)":"8-590-1404"},{"\u041c\u0435\u0442\u0430\u043b\u043b\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043b\u043e\u0442\u043e\u043a INPUK
So, I have no idea how to fix it - I tried to hardcode UTF-coding "SET NAMES ..." and called header(), and iconv() - last has no sense becouse of I'm sured that my text is in UTF8.
Please, help, thanks.
If you want to output your text on a web page, use javascript. And you'll get your Russian characters. For example:
<script type="text/javascript">
var a = "\u041c\u0435\u0442\u0430\u043b\u043b\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043b\u043e\u0442\u043e\u043a BAKS (\u041f\u043e\u043b\u044c\u0448\u0430";
alert(a);
</script>
Outputs this: