hay i am working on barcode reader project when i call upcdatabase from my php script it give me errors. i use the php example provided by www.upcdatabase.com
the code is
<?php error_reporting(E_ALL);
ini_set('display_errors', true);
require_once 'XML/RPC.php';
$rpc_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // Set your rpc_key here
$upc='0639382000393';
// Setup the URL of the XML-RPC service
$client = new XML_RPC_Client('/xmlrpc', 'http://www.upcdatabase.com');
$params = array( new XML_RPC_Value( array(
'rpc_key' => new XML_RPC_Value($rpc_key, 'string'),
'upc' => new XML_RPC_Value($upc, 'string'),
), 'struct'));
$msg = new XML_RPC_Message('lookup', $params);
$resp = $client->send($msg);
if (!$resp)
{
echo 'Communication error: ' . $client->errstr;
exit;
}
if(!$resp->faultCode())
{
$val = $resp->value();
$data = XML_RPC_decode($val);
echo "<pre>" . print_r($data, true) . "</pre>";
}else{
echo 'Fault Code: ' . $resp->faultCode() . "\n";
echo 'Fault Reason: ' . $resp->faultString() . "\n";
}
?>
when i check the $upc='0639382000393'; into upc data base view this then it works fine but i run this script into the browser then it give the following error Array
(
[status] => fail
[message] => Invalid UPC length
)
Unfortunately, their API appears rather short on documentation.
There are three types of codes the site mentions on the Item Lookup page:
13 digits for an EAN/UCC-13
12 digits for a Type A UPC code, or
8 digits for a Type-E (zero-supressed) UPC code.
Right after the page mentions those three types, it also says,
Anything other than 8 or 12 digits is not a UPC code!
The 13-digit EAN/UCC-13 is a superset of UPC. It includes valid UPCs, but it has many other values that are not valid UPCs.
From the Wikipedia article on EAN-13:
If the first digit is zero, all digits in the first group of six are encoded using the patterns used for UPC, hence a UPC barcode is also an EAN-13 barcode with the first digit set to zero.
Having said that, when I removed the leading zero from $upc, it worked as expected. Apparently the Item Lookup page has logic to remove the leading zero, while the API does not.
Array
(
[upc] => 639382000393
[pendingUpdates] => 0
[status] => success
[ean] => 0639382000393
[issuerCountryCode] => us
[found] => 1
[description] => The Teenager's Guide to the Real World by BYG Publishing
[message] => Database entry found
[size] => book
[issuerCountry] => United States
[noCacheAfterUTC] => 2011-01-22T14:46:15
[lastModifiedUTC] => 2002-08-23T23:07:36
)
Alternatively, instead of setting the upc param, you can set the original 13-digit value to the ean param and it will also work.
Related
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.
Please excuse the long post - I've tried to be as succinct as possible, whilst giving as much detail as I can ... and I've historically been a procedural PHP programmer, now getting my feet wet with objects.
I'm working on a test project where I'm using a 3rd party class (loaded via phar) to capture a stream from an online server. The online server posts events, I capture (using "capture.php") each event with the 3rd party class, serialize the data and then store it to a MySQL database as a BLOB field.
//capture.php
// include phar file
require_once 'PAMI-1.72.phar';
// set include path to have pami's phar first
ini_set('include_path', implode(PATH_SEPARATOR, array('phar://pami.phar', ini_get('include_path'))));
use PAMI\Client\Impl\ClientImpl as PamiClient;
use PAMI\Message\Event\EventMessage;
use PAMI\Listener\IEventListener;
$pamiClient = new PamiClient($pamiClientOptions);
// Open the connection
$pamiClient->open();
$pamiClient->registerEventListener(function (EventMessage $event) {
// Following line dumps the event to a text file in rawCapture.php
//var_dump($event);
$mysqli = new mysqli($server, $user, $pass, $db);
if ($mysqli->connect_error) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit;
}
$serializedData = $mysqli->real_escape_string(serialize($event));
$sql = 'insert into obj (data) values ("' . $serializedData . '")';
echo "\r\nSQL is $sql\r\n";
});
In a different script ("read.php" - I know - I'm VERY creative in script naming) I ensure that I have the include files to the class definition files, pick up the first entry in the database, pull the BLOB data and then unserialize it. At this point I'm testing the variable type in read.php and the variable is an object:
require_once 'PAMI-1.72.phar';
// set include path to have pami's phar first
ini_set('include_path', implode(PATH_SEPARATOR, array('phar://pami.phar', ini_get('include_path'))));
use PAMI\Client\Impl\ClientImpl as PamiClient;
use PAMI\Message\Event\EventMessage;
use PAMI\Listener\IEventListener;
/* All the MySQL stuff to get the $data from the db */
$event = unserialize($data);
echo "\r\nevent is " . gettype($event) . "\r\n";
print_r($event);
And this is the result I get:
event is object
PAMI\Message\Event\NewchannelEvent Object
(
[rawContent:protected] => Event: Newchannel
Privilege: call,all
Channel: Local/s#tc-maint-00006a43;2
ChannelState: 4
ChannelStateDesc: Ring
CallerIDNum:
CallerIDName:
AccountCode:
Exten: s
Context: tc-maint
Uniqueid: 1443368640.57856
[lines:protected] => Array
(
)
[variables:protected] => Array
(
)
[keys:protected] => Array
(
[event] => Newchannel
[privilege] => call,all
[channel] => Local/s#tc-maint-00006a43;2
[channelstate] => 4
[channelstatedesc] => Ring
[calleridnum] =>
[calleridname] =>
[accountcode] =>
[exten] => s
[context] => tc-maint
[uniqueid] => 1443368640.57856
)
[createdDate:protected] => 1443368636
)
Ok - so far so good, IMHO. This certainly appears to be an object, all the data certainly appears to have been stored correctly (rawCapture.php is another script which also polls the data and var_dumps the same events out to a text file, so that I can "compare" and ensure that everything is being recorded correctly).
However, now I want to deal with some of the object data and this is where I'm having issues. For example, I'm trying to obtain the value of the Uniqueid, but using $id = $event->Uniqueid; I get the following error PHP Notice: Undefined property: PAMI\Message\Event\NewchannelEvent::$Uniqueid in /home/dave/objRead.php on line 69
Now I'm stuck. I've tried checking that $event is in fact an object, using get_object_vars():
$objVars = get_object_vars($event);
if(is_null($objVars)){
echo "\r\nobjVars doesn't appear to be an object?!\r\n";
} else {
if(is_array($objVars)){
print_r($objVars);
} else {
echo "\r\nobjVars isn't an array!!\r\n";
}
}
and I'm getting my own error code "objVars doesn't appear to be an object?!".
Can anyone give me some advice on what on earth I'm doing wrong??
Also - I've tried to keep indentation in the code sections above but it wouldn't let me post without removing them. I've also amended my OP to show that I'm including the 3rd party code so that the class definitions are loaded, and the line that I use to unserialize the data from the MySQL table.
Have you tried changing the case of Uniqueid in $id = $event->Uniqueid; to lower case? So it would be $id = $event->uniqueid;
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 this sphinx search engine that I use through Zend using sphinxapi.php . It works fantastic. Really really great.
However, there is one problem: It randomly fails.
// Prepare Sphinx search
$sphinxClient = new SphinxClient();
$sphinxClient->SetServer($ip, $port);
$sphinxClient->SetConnectTimeout( 10 );
$sphinxClient->SetMatchMode( SPH_MATCH_ANY );
$sphinxClient->SetLimits( $resultsPerPage * ($nPage - 1), $resultsPerPage );
$sphinxClient->SetArrayResult( true );
$query = array();
$query['lang'] = '#lang "lang' . $language . '"';
if (isset($params)) {
foreach ($params as $param) {
$query['tags'] = '#tags "' . $param . '"';
}
}
// Make the Sphinx search
$sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED);
$sphinxResult = $sphinxClient->Query(implode(' ', $query), '*');
As seen here, I search for a language and an arbitrary amount of tags, imploded into a single query string in the end (instead of making a battleload of subqueries).
So, normally, this works like a charm, but occassionally sphinx returns that it found 2000 entries in English and, say, 1000 entries with the tag "pictures" (or some other purely english word) but ZERO hits that fit both results, which is purely false. In fact, refreshing the page everything returns to normal with something like 800 real results.
My question is why does it do this and how do I make it stop?
Any ideas?
:Edit: Added shortened output log
[error] =>
[warning] =>
...
[total] => 0
[total_found] => 0
[time] => 0.000
[words] => Array (
[langen] => Array (
[docs] => 2700
[hits] => 2701 )
[picture] => Array (
[docs] => 829
[hits] => 1571 ) ) )
have you checked to see if the sphinx client is giving you any error or warning messages that may describe the failure?
if($sphinxResult === false) {
print "Query failed: " . $sphinxClient->GetLastError();
} else {
if($sphinxClient->GetLastWarning()) {
print "WARNING: " . $sphinxClient->GetLastWarning();
}
// process results
}
This issue has been solved completely a few months after the original post. The issue is that our service providers in the umbrella corporation har mistakenly assigned the wrong root values to the sphinx commands. The problem above was actually running on Sphinx 0.9.8 and was obviously buggy. My advice, if you ever experience similar problems is to double-tripple-check the version you use both to index and to query.
It feels like one of those times your math calculation doesn't roll out because you forgot a minus on the first row. Thanks to everyone that have tried to help in this and related threads.