PHP PEAR error Class 'XML_Serializer' not found? - php

I need to turn an array into an XML file.
I have the following code:
<?php
$nouser = 'There is no user with that ID in the database.';
try {
$handler = new PDO('sqlite:Ebsco.db');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = '';
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
};
$query = $handler->query('SELEcT * FROM Users WHERE ID='.$name);
$User = $query->fetch(PDO::FETCH_ASSOC);
if ($User) {
$Serializer = &new XML_Serializer();
$XML = $Serializer->serialize($User);
print_r($XML);
print_r($Serializer);
}
else {
echo $nouser;
}
}
catch (PDOException $e) {
echo $nouser;
die();
}
?>
The code works fine for retrieving the array and passing it back to the html as an array, but I am having issues with the PEAR XML_SERIALIZER.
I have downloaded the files and placed them in the php/pear/xml folder (except for "package" which I left in the main pear folder, as I have no idea what it is meant to do), and checked the phpinfo() to make sure the include_path leads to php/pear.
However, when I add the XML_SERIALIZER, I get the following error:
Fatal error: Class 'XML_Serializer' not found in...
I am new to PEAR so I'm not sure if I installed everything correctly (other than putting the files in the library, is there anything else I need to do?), or if this is caused by another issue.
Thanx

You need to include the file manually, there is no autoloading with PEAR1 packages except you do that yourself.
require_once 'XML/Serializer.php';

Related

why i can't use the "administration command" in php when i am working in mongoDB

Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::listDatabases()
this error keep showing when i wanted to use the administration command for mongodb using php. I do not know whats the problem here and someone with kind soul please help me. The following codes is what i have tried which cause that error.
<?php
$client = new MongoDB\Driver\Manager( 'mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'#'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
);
try{
$dbs = $client->listDatabases();
echo '<pre>';
print_r($dbs);
echo '</pre>';
// Or Nothing if you just wanna check for errors
}
catch(Exception $e){
echo "Unable to connect to Database at the moment ! ";
exit();
}
$colecciones = $client->listCollections();
foreach ($colecciones as $col) {
echo $col->getName();
}
?>
these two are the refereces that i used but is not working for me
Get collections in mongodb with PHP
Is there a way to test MongoDB connection in PHP?
what i am trying to do here is to make sure that my database connection is successful and also list out the collection name of my mongodb database.`
You are trying to call an undefined method in the MongoDB\Driver\Manager class
You can see the list of methods and functions here
https://www.php.net/manual/en/class.mongodb-driver-manager.php
In addition please follow all the listed function and methods in php mongodb driver.
Try to use this to query data from the database:
$manager = new MongoDB\Driver\Manager('mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'#'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
);
$filter = [];
$option = [];
$read = new MongoDB\Driver\Query($filter, $option);
$query = $mongo->executeQuery(‘db.Collection_Name’ $read);
$exportQuery = $query->toArray();
var_dump($exportQuery);

SLIM Application error. Code 8: Array to string conversion

I'm currently working in a mobile application (Front-end) which brings some data through a Php Slim backend from a MySQL database using PDO. This (Back-end) was developed by a team mate and works like a charm on his computer.
There's a GET route which is supposed to return some JSON data:
$app->get('/users', function () {
require_once 'controllers/User.php';
$user = new User();
$user->setJsonMode(true);
$user->setJoin('default');
$user->setSelect('user_id, user.role_id, role, name,
userName, email, picture, user.last_update');
echo $user->select();
});
The 'User' Controller as all of them, inherit from 'CtrlDB' controller.
If I try to access 'api/users' I get:
Type: ErrorException
Code: 8
Message: Array to string conversion
File: /home/shy-n/projects/tienda/api/controllers/CtrlDB.php
Line: 32
The line 32 is located at the CtrlDB constructor:
public function __construct($table,$fields,$idProperty,$relations) {
$dsn = DB_ENGINE.':host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8';
try {
$this->db = new PDO($dsn, DB_USERNAME, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
$response = $this->response("error","Connection failed: " . $e->getMessage(),null);
echo $response;
exit;
}
$this->table = $table;
$this->idProperty = $idProperty;
$this->fields = $fields;
$this->relations = $relations;
$this->start = 0;
$this->limit = 25;
$this->select = "`".implode("`, `",$fields)."`";
}
In "echo $response" I get the error, and I have no clue what's going on.
He uses WAMP server with php 5.5.12
I'm using Arch Linux 64 Bits with LAMP with php 5.6.5. I have enabled both extensions
mysqli.so and pdo_mysql.so in my php.ini file.
I have imported the database used with phpmyAdmin, containing the same registers as my friend in the back-end.
In spite of all of this, he can get the JSON data accessing the /users route, but I can't.
Thanks in advance for your help.
instead of
echo $response;
try
echo json_encode($response);
you shouldn't be echoing out arrays

Handling $resource request from PHP backend using SLIM

I'm having problems accessing my PHP backend from AngularJS.
I have followed:
http://coenraets.org/blog/2012/02/sample-application-with-angular-js/
Routing with AngularJS and Slim PHP
Some other's too but those are similar. I've tackled the problem for a few days now and still can't get it working.
First way to call my php script
app.controller('PhoneDetailCtrl',function($scope, $modal, $resource) {
var request_Id = 1;
var Request = $resource('http://mobiiltelefonid24.ee/api/kasutatud_telefonid/'+request_Id);
$scope.request = Request.get();} //this way I get code 200 but 119 empty chars.. So I figure routing should be correct?
Second way I tried
app.controller('PhoneDetailCtrl',function($scope, $modal, Service) {
$scope.request = Service.get({id:1});} //this gives me code 200 but 119 empty chars...
app.service('Service', function ($resource) {
return $resource('api/kasutatud_telefonid/:id', {}, {
update: {method:'PUT'}
});});
PHP code (using mysql db)
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/', 'getPopularPhones');
$app->get('/uued_telefonid','getNewPhones');
$app->get('/kasutatud_telefonid','getUsedPhones');
$app->get('/uued_telefonid/:id', 'getPhoneDesc');
$app->get('/kasutatud_telefonid/:id', 'getPhoneDesc');
$app->run();
/*Other get methods are exactly the same but with different name*/
function getPhoneDesc($id) {
$sql = "SELECT * FROM Phone";
try {
$db = getConnection();
$stmt = $db->query($sql);
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
getConnection() is implemented as shown in wine app tutorial. There is one row in db that has 21 colums so it should return something. Also tried to pass string $wine="teststring" but that also arrived as jibbrjabbre.
Is routing wrong or is there problems with querying from db? (I can query just fine from phpMyAdmin). Out of ideas...
Solved! Slim was falsely configured and meekroDB worked just fine (Thanks mainguy). On top of that there were some issues on webhosts side.

facebook php access token

I have all of the files (facebook.php, base_facebook.php, index.php) in the same directory. My server(s) are Apache, and both support php.
My code:
<html>
<body>
<?php
try
{
echo("STARTING<br>");
require("facebook.php");
}
catch(Exception $e)
{
echo("ERROR1: $e");
}
try
{
$facebook = new Facebook("***","###");
}
catch(Exception $e)
{
echo("ERROR2: $e");
}
$token = $facebook->getAccessToken();
echo("Access token: ".$token."<br>");
My text output is as follows:
STARTING
ERROR1: Object id #1before create fb instance
Fatal error: Class 'Facebook' not found in /(FILE PATH)/index.php on line 16
Note: line 16 is: $facebook = new Facebook("***","###");
The first catch statement is printing: Object Id #1. Then it does my next print statement. Then it returns Fatal Error that is not caught. What am I missing here?
Why can the server not get the correct access token?
You failed to require the facebook.php, hence the ERROR1: Object id #1 - you're trying to echo out the exception error object. Try
catch ($e) {
die($e->getMessage());
}
instead.
You should not catch that kind of error. if a require fails, the only useful solution is to abort execution, because you've not gotten what you REQUIRED to continue execution.
Basically you've implemented a PHPized version of visual basic's on error resume next, with all the nasty stupidity that goes with it.
You should put the code before the header is sent :
Go here for further information : https://developers.facebook.com/docs/reference/php/
Basically, put this on very on top of your code :
<?php
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);
?>
Then load your HTML (In MVC style will be better for maintenance ;-)

php and webservices

I have a wsdl file and i am trying to call it from a php class. I am using the following code:
<?php
include ("dbconn.php");
class dataclass
{
function getCountries()
{
$connection = new dbconn();
$sql = "SELECT * FROM tblcountries";
$dataset = $connection -> connectSql($sql);
return $dataset;
}
function getTest()
{
$connection = new dbconn();
$sql = mysql_query('CALL sp_getTest');
$dataset = $connection -> connectSql($sql);
return $dataset;
}
##-------------------------------------------CUSTOMER METHODS-------------------------------------------
function registerCustomer($username,$name,$surname,$password,$email,$country,$tel)
{
$connection = new dbconn();
$sql="INSERT INTO tblcustomer (customer_username, customer_password, customer_name, customer_surname,
customer_email, customer_country, customer_tel)
VALUES('$username','$name','$surname','$password','$email','$country','$tel')";
$dataset = $connection -> connectSql($sql);
}
ini_set("soap.wsdl_cache_enabled", "0");
// start the SOAP server - point to the wsdl file
$webservice = new SoapServer("http://localhost/dataobjects/myWebservice.wsdl", array('soap_version' => SOAP_1_2));
// publish methods
$webservice->addFunction("getCountries");
$webservice->addFunction("registerCustomer");
// publish
$webservice->handle();
}
?>
It is all the time giving me a problem with ini_set("soap.wsdl_cache_enabled", "0");
The error is:
Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:\Program Files\xampplite\htdocs\dataobjects\dataClass.php on line 47
I believe it is because you have ini_set() call in the body of your class. Put it at the top of the file or in the constructor if you have one.
class dataClass
{
function registerCustomer()
{
// some stuff
}
ini_set(/*args*/); // it's illegal to put instructions in the body of the class
}
Now I see the whole thing. You probably want to close the class with a closing backet before line 47.
You let the parser think "0" is a string, and not a number, please remove the quotes!
Edit 1 If that wouldn't work, your error must be before that line, please post the full code for review.
Edit 2 The code you provided was running inside the class, you miss a bracket before the line with ini_set.
Move the last } in front of ini_set(...)
By the way, you said you want to call a web service, but you are creating a server which may be called by others.
To call a web service, try something like this:
try{
$client = new SoapClient($service, array('location' =>"http://example.org/myWebService"));
$parameter1 = new myWebServiceParameter();
$result = $client->myWebServiceFunction($parameter1);
} catch (Exception $e) {
// handle errors
}
myWebServiceParameter must be any class with a member variable foreach WSDL message attribute of the same name.
And myWebServiceFunction is the name of the web service method.

Categories