PHP Magento API catalog_product.info not working when running through a list - api

I am trying to create a magento API to get the pricing of each item. I have a table with all the SKU's i need to get info for. i ran the following for one item and it worked
$client = new SoapClient('http://www.mysite.com/api/soap/?wsdl');
$session = $client->login('user', 'pass');
$productId = 'ABC';
$att = array("visibility","sku","special_price", "price");
$arguments = array( $productId, NULL, $att);
$result = $client->call($session, 'catalog_product.info', $arguments);
echo $result['visibility'].",".$result['sku'].",".$result['special_price'].",".$result['price'];
the above code worked fine.
then i tested another code to make sure that my code to query the database and loop through each sku works
$getskus = "SELECT sku FROM items;";
$skus = mysqli_query($con, $getskus);
while($row = mysqli_fetch_array($skus))
{
$productId = $row['sku'];
echo $productId."<br>";
}
The above code works fine. My issue is when i combine the 2 i get a blank screen.
$client = new SoapClient('http://www.mysite.com/api/soap/?wsdl');
$session = $client->login('user', 'pass');
$getskus = "SELECT sku FROM items;";
$skus = mysqli_query($con, $getskus);
while($row = mysqli_fetch_array($skus))
{
$productId = $row['sku'];
$att = array("visibility","sku","special_price", "price");
$arguments = array( $productId, NULL, $att);
$result = $client->call($session, 'catalog_product.info', $arguments);
echo $result['visibility'].",".$result['sku'].",".$result['special_price'].",".$result['price'];
}
i get nothing. Any ideas?
update: if $row['sku'] = '9005' will magento think its a product id instead of a SKU?

This line:
$result = $client->call($session, 'catalog_product.info', $arguments);
This can't accept $arguments as the third param. Instead:
$result = $client->call($session, 'catalog_product.info', $row['sku'], null, $att, 'sku');
NB: not sure if 'null' (4th param) is a valid argument for store view. To be safe, replace with the correct store view (default, in most cases).
RTM: http://www.magentocommerce.com/api/soap/catalog/catalogProduct/catalog_product.info.html

Related

PDO bind variables to prepared mysql statement and fetch using while loop

I've used several of your guides but I can not get the following to run. If I hardcode the 2 variables in the Select statement it runs fine. I need to use variables, and I can't get the bind statement to work. Plenty of experience with the old Mysql_ but the PDO is still a challenge at this point.
$db_table = "ad";
$ID = "1";
$dsn = "mysql:host=$hostname;dbname=$database;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $password, $opt);
$result = $pdo->prepare("SELECT * FROM :ad WHERE id= :id "); // Line 359
$result->bindParam(':ad', $db_table, PDO::PARAM_STR);
$result->bindParam(':id', $ID, PDO::PARAM_STR);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$product = $row["product"];
$msrp = $row["msrp"];
$sale = $row["sale"];
$content = $row["content"];
echo "<strong>$product</strong> - $content<br />";
// echo $msrp . "<br />";
if($msrp != "0.00") { echo "MSRP $$msrp"; }
if($sale != "0.00") { echo "<img src='/images/c.gif' width='75' height='6' border='0'><span style='color: red;'>Sale $$sale</span>"; }
}
$pdo = null;
The above generates this error,
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '? WHERE id=?' at line 1' in
/XXXXXXXXXXXX/index_desktop_pdo.php:359
Your database structure is wrong. There should be always only one table to hold all the similar data. And therefore no need to make a variable table name.
To distinguish different parts of data just add another field to this table. This is how databases work.
So your code should be
$section = "ad";
$ID = "1";
$result = $pdo->prepare("SELECT * FROM whatever WHERE section=:ad AND id= :id");
$result->bindParam(':ad', $section);
$result->bindParam(':id', $ID);
$result->execute();

Shopify API getting order by name or order_number

Im using a plugin for CakePHP to make the calls to obtain certain orders. I can call all orders with certain fields, but I was wondering how would I have to make the call to get the orders with a certain name or order_number? Here is the source for the call to Shopify. Its already authenticated and everything:
public function call($method, $path, $params=array())
{
if (!$this->isAuthorized())
return;
$password = $this->is_private_app ? $this->secret : md5($this->secret.$this->ShopifyAuth->token);
$baseurl = "https://{$this->api_key}:$password#{$this->ShopifyAuth->shop_domain}/";
$url = $baseurl.ltrim($path, '/');
$query = in_array($method, array('GET','DELETE')) ? $params : array();
$payload = in_array($method, array('POST','PUT')) ? stripslashes(json_encode($params)) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
$request_headers[] = 'X-Shopify-Access-Token: ' . $this->ShopifyAuth->token;
list($response_body, $response_headers) = $this->Curl->HttpRequest($method, $url, $query, $payload, $request_headers);
$this->last_response_headers = $response_headers;
$response = json_decode($response_body, true);
if (isset($response['errors']) or ($this->last_response_headers['http_status_code'] >= 400))
throw new ShopifyApiException($method, $path, $params, $this->last_response_headers, $response);
return (is_array($response) and (count($response) > 0)) ? array_shift($response) : $response;
}
private function shopApiCallLimitParam($index)
{
if ($this->last_response_headers == null)
{
return 0;
}
$params = explode('/', $this->last_response_headers['http_x_shopify_shop_api_call_limit']);
return (int) $params[$index];
}
...and the code that makes the GET call:
// I only want the id and title of the collections
$fields = "fields=name,id,status,financial_status,fulfillment_status,billing_address,customer";
// get list of collections
$custom_collections = $this->ShopifyAPI->call('GET', "/admin/orders.json", $fields);
$this->set('collections', $custom_collections);
I think I'm missing the place where I can put the conditions for the call to get certain orders. I've already read the API documentation but can't seem to get the answer.
I've tried putting the ?name=%231001 on the url after .json to try and get the order #1001, but it brings back a empty array.
Then I tried ?order_number=1001 but it brings me every order with as well 1001 D: This is really confusing, Could anyone help me?
Thanks in advance.
Well I found out that you can actually get the order using the name or order_number. Its another property that is not listed on the documentation for some reason. But in the URL, if your using another language, all you have to add in the GET is admin/order.json?name=%2310001&status=any this is to get the order 10001 so just add the order_number after the %23. I saw this on a forum in Shopify university, I was just implementing this wrong on my code. If your using the CakePhp shopify plugin like me all I did was add on the $field the ?name=%23". number ."&status=any";
Ill leave the code here:
$this->layout = 'main';
$order_number = "18253";
$fields = "name=%23". $order_number ."&status=any";
$order = $this->ShopifyAPI->call('GET', "/admin/orders.json", $fields);
if (!empty($order)) {
$this->set('order', $order);
} else {
$this->Session->setFlash('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> No existe el numero de orden ingresado.','default',array('class' => 'alert alert-danger alert-dismissible', 'type' => 'alert'));
}
Hope this helps someone :P

PDO row doesn't exist?

Below is my code:
<?php
$url = $_GET['url'];
$wordlist = array("Www.", "Http://", "Http://www.");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$url = preg_replace($wordlist, '', $url);
?>
<?php
$oDB = new PDO('mysql:dbname=mcnsaoia_onsafe;host=localhost;charset=utf8', 'mcnsaoia_xx', 'PASSWORD');
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt=ja");
$hStmt->execute(array('hjemmside' => $url));
if( $row = $hStmt->fetch() ){
echo "EXIST";
}else{
echo "NOT EXIST";
}
?>
My problem is that it says NOT EXIST, because I know that there is a row which should be found with the following query:
SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt=ja
So why does it say not exist? I have absolutely no idea :(
Instead of
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside
AND godkendt=ja");
try
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside
AND godkendt='ja'");
The left is most likely a column and the right side is a string? I don't speak your language, but this is the first thing coming to my mind.
You should surround with quotes your not integer variable in your query
AND godkendt='ja'
Or maybe let pdo deal with it
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt = :ja");
$hStmt->execute(array(':hjemmside' => $url, ':ja' => 'ja'));
//^ i added : for placeholder here, you missed it
I would also rather check if rows are returned
if($hStmt->$eowVount() > 0){
$row = $hStmt->fetch()
echo "EXIST";
}else{
echo "NOT EXIST";
}

Cloadflare Return 'rec_id' For 1 'A' Record in a Zone : PHP

I have a PHP script that adds a new 'A' record to a Cloudflare zone, however, by default these new 'A' records are set as non-active by Cloudflare and now days you can not set them as active when creating them.
So, to edit the new record to set it as active, you need the 'A' records 'rec_id'. In this case action 'rec_load_all' can't be used as there are too many zone 'A' records and I don't think you can filter the request (could be wrong & would be good to be wrong). The zone needs to be filtered.
I have tried the following 'dns_get_rec_one' but it just returns 'NULL' with no error message:
function returnId(){
$request = array();
$request['a'] = 'dns_get_rec_one';
$request['tkn'] = $this->tkn;
$request['email'] = $this->apiEmail;
$request['z'] = 'domain.com';
$request['name'] = 'sub.domain.com';
$response = #json_decode(file_get_contents('https://www.cloudflare.com/api_json.html?' . http_build_query($request)), true);
}
Any ideas as I have little experience with API interactions?
Thanks
Ok, I have worked this out with some help.
When you make the CURL 'rec_new' call to Cloudflare the response includes the 'rec_id' for the new "A" record. This can then be used as the 'id' in the next CURL 'rec_edit' call to edit the record as being active.
The guys at Cloudflare support answer within 24hrs as well and are helpful.
Snippets from class bellow:
private function newSub(){
$fields = array(
'a' => 'rec_new',
'tkn' => $this->tkn,
'email' => $this->apiEmail,
'z' => $this->domain,
'type' => 'A',
'name' => $this->subName,
'content' => $this->content,
'ttl' => 1
);
//url-ify the data for the POST
foreach($fields as $key=>$value){
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, 'https://www.cloudflare.com/api_json.html');
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$response = curl_exec($ch);
//close connection
curl_close($ch);
$response = json_decode($response,true);
if(!$response || $response['result'] != 'success'){
$responseError = $response['msg'];
// ERROR Handling
}else{
// Set rec_id for from the nw A record
$this->rec_id = $response['response']['rec']['obj']['rec_id'];
// Activate
$this->makeActive();
}
}
private function makeActive(){
$request['a'] = 'rec_edit';
$request['tkn'] = $this->tkn;
$request['email'] = $this->apiEmail;
$request['z'] = $this->domain;
$request['id'] = $this->rec_id;
$request['type'] = 'A';
$request['name'] = $this->subName;
$request['content'] = $this->content;
$request['service_mode'] = '1';// Make active
$request['ttl'] = '1';
$response = #json_decode(file_get_contents('https://www.cloudflare.com/api_json.html?' . http_build_query($request)), true);
//var_dump($response); die;
if(!$response || $response['result'] != 'success'){
$responseError = $response['msg'];
// ERROR Handling
}
}
Hope that this helps someone.

How to output JSON from recordset in Dreamweaver with minimal manual code? [duplicate]

I have a basic MySQL database table People with 3 columns (ID, Name, Distance)
I am trying to output this with PHP as a JSON so my web app can pick it up. I tried using the solution from another answer:
$sth = mysql_query($con,"SELECT * FROM People");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
However I am just returning a blank array of [].
Update: Changed to mysqli and added dumps:
$sth = mysqli_query("SELECT * FROM Events",$con);
$rows = array();
var_dump($sth);
while($r = mysqli_fetch_assoc($sth)) {
var_dump($rows);
$rows[] = $r;
}
print json_encode($rows);
Returns:
NULL []
Swap your query and connection in the mysql_query-statement:
$sth = mysql_query("SELECT * FROM People", $con);
Besides that, the mysql-library is deprecated. If you're writing new code consider using mysqli_ or PDO.
Why no mysql_connect ?
var_dump($sth); // check the return of mysql_query()
var_dump($rows); // check the array of mysql_fetch_assoc result
I would check if your query is returning any rows first.
<?php
$rows = array();
array_push($rows, array("name" => "John"));
array_push($rows, array("name" => "Jack"));
array_push($rows, array("name" => "Peter"));
print json_encode($rows);
?>
Produces this output.
[{"name":"John"},{"name":"Jack"},{"name":"Peter"}]
Solved using a combination of answer to get:
$sth = mysqli_query($con,"SELECT * FROM Events");
$datarray = array();
while($row = mysqli_fetch_assoc($sth)) {
$datarray[] = $row;
}
print_r(json_encode($datarray));