I need to get some data using a web service in PHP. The first function I run returns an id. If I give this id as a variable to the second function (I wrote this function clearly below), it returns null. But if I write statically, the data comes. What could be the problem?
$tc = "xxxxxxxxxxx";
$bireyId = firstFunc($tc); //Get user uniqId
// second function codes
$client = new SoapClient("URL/Service.asmx?WSDL");
try{
$authHeader = array(
"Username" => "Username",
"Password" => "Password"
);
$requestData = array(
"InstructorId" => $bireyId
);
$header = new SoapHeader("http://tempuri.org/","AuthHeader",$authHeader,false);
$client->__setSoapHeaders($header);
$result = $client->GetInstructorCourses($requestData);
print_r($result);
}catch (Exception $ex){
return $ex->faultstring;
}
If I manually write 1111 to the InstructorId value, the data comes. But if I write as above, the data is not coming.
Hey I found out what the problem is. The first function sends me xml data, not a string value. I solved the problem when I shredded this data
I'm fairly new to PHP and playing around with Goutte/Guzzle to grab some basic information from a website after filling out a few forms.
However I have problems finding issues (there might be a ton of them) since I could not find a way to display or console log any of the results or problems. The script finishes with Code 0 but does not return anything. A tip on how to print out what is currently stored in $client would already go a long way.
Here is the whole code I'm trying to run with a bunch of comments for clarification. I'm sorry for using such a large block, but any of this could have issues.
<?php
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
class grabPlate
{
// WKZ
public function checkPlate
{
$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
'cookies' => true,
'timeout' => 60,
));
$goutteClient->setClient($guzzleClient);
$crawler = $goutteClient->request('GET', 'https://kfz-portal.berlin.de/kfzonline.public/start.html?oe=00.00.11.000000');
//Click the first "Start" in the top left
$link = $crawler
->filter('a:contains("Start")')
->eq(0)
->link()
;
$crawler = $client->click($link);
//Check checkbox, fill in name and press the button
$buttonCrawlerNode = $crawler->selectButton('Weiter');
$form = $buttonCrawlerNode->form();
$form['gwt-uid-1']->tick();
$form['select2-hidden-accessible']->select('Herr');
$form['gwt-uid-4'] = 'John';
$form['gwt-uid-5'] = 'Doe';
$client->submit($form);
//Fill some Data into the forms and search
$buttonCrawlerNode = $crawler->selectButton('Button-3616');
$form = $buttonCrawlerNode->form();
$form['.kfzonline-KennzeichenGrossEb'] = 'AB';
$form['.kfzonline-KennzeichenGrossEn'] = '123';
$client->submit($form);
//Extract collection
$info = $crawler->extract('.collection');
//return 1 if something is inside collection, 0 if it's empty
if($info == NULL) {
return 1;
} else {
return 0;
}
}
}
?>
As I said just running the script in PHPStorm returns the status 0. However when plugging it into an API and accessing it, I get a server timeout response.
You should either use a Debugging. Install xDebug to do so in PHP. This is also easy to integrate into Phpstorm.
Alternatively use var_dump() for printing out debug information about variables of any type to console.
You can display the requested page inside your php page, you have to add this snippet :
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.facebook.com/');
echo $res->getBody();
I have a relatively average (however basic) knowledge with PHP but I'm fairly new to PhalconPHP. I've learned of PhalconPHP while browsing a specific online course website and that this framework is rather fast and unique than other PHP Frameworks, plus it has a Micro package for easy development of REST API.
So as it is, I'm trying to learn how to develop an API with the help of PhalconPHP Framework. And as it is, for beginners like me, I'd like to start with using raw SQL statements rather than the provided phql syntax because I'm not entirely developing an MVC Application (and I'm really having a hard time learning the entire concept of PHQL itself, I need a separate time to learn this).
I have managed to make things work when working with multi-column query results that map to the class much like how it is supposed to be with PhalconPHP, with below sample code:
<?php
namespace MyApplication\Db\ShortLinks\Services;
use MyApplication\Db\ShortLinks\DatabaseTables;
use Phalcon\Mvc\Model\Resultset\Simple as ResultSet;
class VisitorService
{
function getVisitorLogByLinkId($id)
{
$sqlQry = "SELECT * FROM visitors v WHERE v.link_id = $id ORDER BY v.visitor_id DESC;";
$visitor = new DatabaseTables\Visitor();
$resultSet = new ResultSet(null, $visitor, $visitor->getReadConnection()->query($sqlQry));
$data = [];
foreach ($resultSet as $result) {
$data[] = [
"visitor_name" => $result->visitor_name,
"access_timestamp" => $result->access_timestamp
];
}
return $data;
}
}
?>
However, I cannot seem to get the concept on how to work this out with single-columned query results such as getting the SUM, COUNT, or even ids and specific data type. I've tried below code as I've tried to recreate provided answer here:
function isLinkIdValid($id)
{
$sqlQry = "SELECT IF(COUNT(l.link_id) = 0, 0, 1) 'is_exist' FROM links l WHERE l.link_id = $id;";
$result = $app->di->db->query($sqlQry);
$result->setFetchMode(Phalcon\Db::FETCH_ASSOC);
$result = $result->fetchAll($result);
return $result;
}
But, as i have expected, it would not work since $app (which is an instance of Phalcon\Mvc\Micro which is in index.php) is not accessible from the function.
Also, its best to explain to everyone that while I do have models for the database tables, I've separated all database logic from the model object to keep it clean and serve its only purpose - being a model. How I've done this is I've created a new folder named /service and creating service for each model that there is (for example: VisitorService).
To show everyone my code, I basically patterned it after PhalconPHP's REST Tutorial, below is a snippet of my code:
index.php:
<?php
use Phalcon\Loader;
use Phalcon\Mvc\Micro;
use Phalcon\Di\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMySql;
use Phalcon\Http\Response;
# Loader initialization and namespace registration
$loader = new Loader();
$loader->registerNamespaces([
"MyApplication\Db\ShortLinks\DatabaseTables" => __DIR__ . "/models/",
"MyApplication\Db\ShortLinks\Services" => __DIR__ . "/services/"
]);
$loader->register();
# DependencyInjector initialization and instantiation of database connection
$di = new FactoryDefault();
$di->set("db", function() {
return new PdoMySql([
"host" => "127.0.0.1",
"username" => "username",
"password" => "password",
"dbname" => "short_links"
]);
});
# Micro initialization, route definition
$app = new Micro($di);
$app->notFound(function() use ($app) {
$response = new Response();
$response->setStatusCode(404, "Not Found");
$response->setJsonContent([
"status" => 404,
"message" => "The specified route was not found, or does not exist",
"data" => ""
]);
return $response;
});
require "routes/visitor_route.php";
$app->handle();
?>
routes/visitor_route.php
<?php
use Phalcon\Http\Response;
use MyApplication\Db\ShortLinks\Services;
require "services/visitor_service.php";
$app->get('/v1/visitors/log/{id:[0-9]+}', function($id) use ($app) {
$response = new Response();
# validate id parameter
if($id <= 0) {
$response->setStatusCode(422, "Unprocessable Entity");
$response->setJsonContent([
"status" => 422,
"message" => "Invalid link id specified.",
"data" => ""
]);
return $response;
}
$service = new Services\VisitorService();
$response->setStatusCode(200, "OK");
$response->setJsonContent([
"status" => 200,
"message" => "",
"data" => $service->getVisitorLogByLinkId($id)
]);
# This partially works, except that it does not return whether a link id is valid, so I'm trying to create a logic for one.
// return $response;
$tempService = new Services\LinkService();
$tempResult = $tempService->isLinkIdValid($id);
return print_r($tempResult);
});
?>
service/visitor_service.php
<?php
namespace MyApplication\Db\ShortLinks\Services;
use MyApplication\Db\ShortLinks\DatabaseTables;
use Phalcon\Mvc\Model\Resultset\Simple as ResultSet;
class VisitorService
{
# technically belongs to 'services/link_service.php' but placed here to shorten attached codes.
function getAllLinks()
{
$sqlQry = "SELECT * FROM links;";
$link = new DatabaseTables\Link();
$resultSet = new ResultSet(null, $link, $link->getReadConnection()->query($sqlQry));
$data = [];
foreach ($resultSet as $result) {
$data[] = [
"link_id" => $result->link_id,
"description" => $result->description,
"original_url" => $result->original_url,
"short_url" => $result->short_url
];
}
return $data;
}
# technically belongs to 'services/link_service.php' but placed here to shorten attached codes.
function createNewShortLink($link)
{
$sqlQry = "INSERT INTO links VALUES (DEFAULT, '$link->description', '$link->original_url', $link->base_url, '$link->unique_key', DEFAULT, DEFAULT);";
$link = new DatabaseTables\Link();
$link->getReadConnection()->query($sqlQry);
}
# technically belongs to 'services/link_service.php' but placed here to shorten attached codes.
# This is the experimental code i am working with
function isLinkIdValid($id)
{
/*
As it is, everything here doesn't work.
*/
$sqlQry = "SELECT IF(COUNT(l.link_id) = 0, 0, 1) 'is_exist' FROM links l WHERE l.link_id = $id;";
$result = $app->di->db->query($sqlQry);
$result->setFetchMode(Phalcon\Db::FETCH_ASSOC);
$result = $result->fetchAll($result);
return $result;
}
function getVisitorLogByLinkId($id)
{
$sqlQry = "SELECT * FROM visitors v WHERE v.link_id = $id ORDER BY v.visitor_id DESC;";
$visitor = new DatabaseTables\Visitor();
$resultSet = new ResultSet(null, $visitor, $visitor->getReadConnection()->query($sqlQry));
$data = [];
foreach ($resultSet as $result) {
$data[] = [
"visitor_name" => $result->visitor_name,
"access_timestamp" => $result->access_timestamp
];
}
return $data;
}
}
?>
To summarize, I'm looking for a way to fetch single-columned data from my database using RAW SQL Statements inside PhalconPHP. I've dug up several resources but there's just too few of them, if not lacking.
EDIT 1: i know that how i implemented the service is not perfect, and that is prone to security attacks. but please focus on the issue main issue. i'll resolve other issues afterwards. also, what i'm looking for is to be able to use the PdoMysql stored in $app->di["db"] from the index.php much like how i managed to in getAllLinks() and createNewShortLink($link) functions. however, i made a "temporary" solution by passing in the PdoMysql object from the $app->di["db"] to the function like below:
function isLinkIdValid($dbConn, $id)
{
$sqlQry = "SELECT IF(COUNT(l.link_id) = 0, 0, 1) 'is_exist' FROM links l WHERE l.link_id = $id;";
$isExist = $dbConn->fetchAll($sqlQry, \Phalcon\Db::FETCH_ASSOC);
return $isExist;
}
I am using a platforme call ideamart to create some sms based applications.
They provide a api called subscription api.
deatils about ideamart subscription API
Guid to work with subscription API
I use below first code to request BaseSize details.is that code is correct.?
can I Display response using PHP echo() Function .? or any other way.?
<?php
include_once "definitions.php";
include_once "subscription.php";
$sub = new Subscription();
$AppId = "APP_00001";
$Password = "yuhst345";
$baseSize = $sub->getBaseSize($AppId,$Password);
?>
here is the getBaseSize function that includes in subscription.php
public function getBaseSize($applicationId, $password){
$arrayField = array(
"applicationId" => $applicationId,
"password" => $password);
$jsonObjectFields = json_encode($arrayField);
$resp=$this->sendBaseRequest($jsonObjectFields);
$response = json_decode($resp, true);
$statusDetail = $response['statusDetail'];
$statusCode = $response['statusCode'];
$status =$response['baseSize'];
return $status;
}
So, it looks like your getBaseSize() is returning an simply the base size. So, you should be able to do a
print $baseSize;
OR
echo $baseSize;
And you'll print out the string.
Hello so I have a simple code here which will do an update in a column and redirect to a page based on the GET parameter. My code is here:
In my html:
Move
and in the index.php
$app->get('/user/admin/table/:table_id/move', 'RecycleTable');
function RecycleTable($table_id)
{
$session = new \RKA\Session();
$app = \Slim\Slim::getInstance();
if (!$session->type) {
$app->redirect('/user/login');
}
else {
$sponsorID = $app->request()->get('sponsor');
$db = new db();
$bind = array(
':table_id' => $table_id
);
$update = array(
'status' => '2'
);
$db->update("tables", $update, "tableID = :table_id", $bind);
$db = null;
$app->redirect('/user/admin/table/'.$sponsorID);
}
}
When I try to click Move I get a 404 error. Do I get the parameter sponsor correctly? Or is there something wrong here?
It appears as if your link in the HTML is incorrect. Your route states that the path should be:
Move
not
Move
You are missing the /user/admin/table part which is why you would be receiving a 404. It cannot resolve to the correct route.