Azure Table Storage PHP Error - php

This is my PHP code
<?php
// Load Azure Drivers
require_once '../vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Common\ServiceException;
use MicrosoftAzure\Storage\Table\Models\QueryEntitiesOptions;
// Connection String
$connectionString = 'DefaultEndpointsProtocol=https;AccountName=<account_name>;AccountKey=<account_key>==';
// Create table REST proxy.
$tableRestProxy = ServicesBuilder::getInstance()->createTableService($connectionString);
$user_input = "Username eq '<user>'";
try {
$result = $tableRestProxy->queryEntities("<table>", $user_input);
}
catch(ServiceException $e){
echo "<h1>Error querying, please contact Admin.</h1>";
die();
}
$entities = $result->getEntities();
foreach($entities as $entity){
echo $entity;
}
?>
I have censored out all the connection and table information. But everything works when I use the demo code. But I want to retrieve the full row. When I execute this I get this error
Catchable fatal error: Object of class MicrosoftAzure\Storage\Table\Models\Entity could not be converted to string
Any ideas?

Generally speaking, you are trying to echo an object which raised this issue. As the $entity in your looping statement is an object, you cannot directly echo it.
The queryEntities() returns QueryEntitiesResult object, and then you call getEntities() function which returns Entity objects in array.
So you can use functions $entity->getXXXX() or $entity->getPropertyValue({key}) to get the properties in your table storage's entity.
You can refer to a simple sample for a quick glance.

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);

How to get mongodb collection iterator?

I'm connecting to mongo db like this:
$mongoClient = new MongoDB\Client($db_string);
Getting collection like this:
$collection = $mongoClient->selectCollection('database_name', 'collection_name');
And getting collection iterator like this:
$iterator = $collection->find();
However last call shoots error:
[error] Could not retrieve source count from demo_article: Authentication failed.
What I'm doing wrong here?
UPDATE:
Here:
protected function initializeIterator()
{
$this->iterator = $this->collection->find();
if($this->iterator instanceof Traversable) {
echo "**Traversable!**";
}
iterator is Traversable. But then, this code is called from SourcePluginBase:
protected function doCount() {
$iterator = $this->getIterator();
if($iterator instanceof Traversable) {
echo "**TRAVERSABLE!**";
}else{
echo "**NOT TRAVERSABLE!**";
}
and it's not Traversable?! How can it loos that traversable status ?
As stated in the documentation for the MongoDB\Client class, the constructor does not perform the actual connection:
A MongoDB\Driver\Manager is constructed internally. Per the Server Discovery and Monitoring specification, MongoDB\Driver\Manager::__construct() performs no I/O. Connections will be initialized on demand, when the first operation is executed.
It means that the connection will be opened only when you execute the first query. If you provided no credentials in the connection string, or if they are incorrect, then you get an "Authentication failed" error on that query.

PHP Doc comment after unserialization

The ReflectionMethod instance from PHP (http://php.net/manual/en/class.reflectionmethod.php) has the getDocComment method that returns the annotation of a method. This works ok, unless you use unserialized object.
$ref = new ReflectionClass('a');
var_dump(method_exists($ref, 'getDocComment')); //bool(true)
var_dump($ref->getDocComment()); //bool(false)
$ref = unserialize(serialize($ref));
var_dump(method_exists($ref, 'getDocComment')); //bool(true)
var_dump($ref->getDocComment()); //PHP Warning: Uncaught Error: Internal error: Failed to retrieve the reflection object
Is there any way of testing if the ReflectionMethod object has correctly defined doc comment? I mean, I do not care about getting the annotation after serialize/unserialize, but I want to check if calling getDocComment is safe.
Edit: According to responses that advice error handling + fallback, I rephrase the Q.
I have some simple cache of reflections (array of ReflectionMethod objects). Until I use item from that cache, I wold like to chech its correctness. I do NOT want to handle error, I want to "predict error". Awesome would be something like hasDocComment method that does not generate any error, but returns only true/false within any ReflectionMethod object state.
The general approach of serializing reflection objects is wrong. There exists a PHP Bug report for it, but it has been set to "irrelevant":
https://bugs.php.net/bug.php?id=70719
The reason is, that you cannot connect a reflection object back to its class again, because you would have to deal with source code changes and all kinds of stuff. What you should do instead is, to serialize the name of the class and generate a NEW reflection object from that class, when you unserialize.
Code Example:
class A { }
$ref = new ReflectionClass('A');
var_dump(method_exists($ref, 'getDocComment'));
// serialize only the class name
$refClass = unserialize(serialize($ref->getName()));
// get a new reflection object from that class ...
$ref = new ReflectionClass($refClass);
var_dump(method_exists($ref, 'getDocComment'));
// If you want to serialize an object
$a = new A();
$a2 = unserialize(serialize($a));
$ref = new ReflectionClass(get_class($a2));
var_dump(method_exists($ref, 'getDocComment'));
If you need to be able to handle errors, you can try/catch the execution block. Since alt-php71-7.1.0-1 (which you seem to be using), this will throw an instance of Error instead of simply a Fatal Error, which allows you to do error handling.
<?php
class A { }
$ref = new ReflectionClass('A');
var_dump(method_exists($ref, 'getDocComment')); //bool(true)
var_dump($ref->getDocComment()); //bool(false)
// serialize only the class name
$refClass = unserialize(serialize($ref));
try {
$refClass->getDocComment();
// do your work
}
catch (Error $e) {
echo "Malformed Reflection object: ".$e->getMessage();
}
Demo
And since you can still get the class name from the malformed Reflection instance, you can instantiate a new one right in your catch block:
<?php
class A { }
$ref = new ReflectionClass('A');
var_dump(method_exists($ref, 'getDocComment')); //bool(true)
var_dump($ref->getDocComment()); //bool(false)
// serialize only the class name
$refClass = unserialize(serialize($ref));
try {
$refClass->getDocComment();
}
catch (Error $e) {
$recoveredRef = new ReflectionClass($refClass->getName());
var_dump($recoveredRef);
var_dump($recoveredRef->getDocComment()); // works correctly
echo "Malformed Reflection object, but recovered: ".$e->getMessage();
}
Demo

PHP accessing webservices

I am trying to access this web service and it is working fine but when i come to diplay the results using the TopGoalScorersResult it is giving me this error "Catchable fatal error: Object of class stdClass could not be converted to string". Can anyone please help me with this. The $results variable is filled with the correct answers just want to display them using the method TopGoalScorersResult
<?php
try {
$client = new SoapClient(
'http://footballpool.dataaccess.eu/data/info.wso?wsdl');
var_dump($client->__getFunctions());
var_dump($client->__getTypes());
$results = $client->TopGoalScorers(array("iTopN"=>"20"));
var_dump($results);
echo $results->TopGoalScorersResult;
} catch (SoapFault$e) {
echo "<pre>" . $e->getMessage() . "</pre>";
}
?>
web services in php4 you can use SOAP on the WSDL to call the web-service functions exmaple link is hereenter link description here
$client = new SoapClient("youridSome.wsdl");
and now $client is now an object . There was a method called getTime() in the WSDL then you use
$result = $client->getTime();

Internal Server Error on a PHP app that is calling a function that calls MySQL database

Basically I am building a MVC app. In the Model, dbFunctions.php is this code:
<?php
require("config.php");
require("dbconnection.php");
class dbFunctions
{
// setting up the object to connect to the Database
function __construct()
{
$dbConnect = new dbConnection();
}
public function insertPortfolioAdminData($value='')
{
# code...
}
public function login($value='')
{
# code...
}
public function logout($value='')
{
# code...
}
public function dbStoreContactForm($value='')
{
# code...
}
// returns a query with a collection of database objects for the portfolio
public function fetchAllPortfolioItems()
{
$fetchAllPortfolioItemsReturnQry = mysql_query("SELECT description FROM PortfolioItems") or die ('Error: '.mysql_error ());
if($fetchAllPortfolioItemsReturnQry){
return $fetchAllPortfolioItemsReturnQry;
}
}
public function fetchSinglePortfolioItems($primaryKey='')
{
# code...
}
}
?>
dbConnection.php
<?php
require("config.php");
class dbConnection {
private $databaseConnection;
public function dbConnection(){
$databaseConnection = mysql_connect(dbHostName,dbUserName,dbPassword) or die(mysql_error());
mysql_select_db(dbDatabaseName) or die(mysql_error());
}
public function closeConnection(){
mysql_close($databaseConnection);
}
}
?>
The controller:
<?php
// Calling the class to do the work on database
require("./model/dbfunctions.php");
$dbMethods = new dbFunctions();
while($row = mysql_fetch_array($dbMethods->fetchAllPortfolioItems()))
{
$pageContent = $row["description"];
}
// calling the template
require("./views/page_12.php");
?>
Here's the error:
Internal Server Error
The server encountered an internal
error or misconfiguration and was
unable to complete your request.
Please contact the server
administrator,
webmaster#mvcportfolio.adambourg.com
and inform them of the time the error
occurred, and anything you might have
done that may have caused the error.
More information about this error may
be available in the server error log.
Additionally, a 404 Not Found error
was encountered while trying to use an
ErrorDocument to handle the request.
Basically I am trying to do all my DB work in the model then through the model pass it to the view to output it.
I see a few problems that may contribute to the error:
1 - You're using require for the "config.php" but you should really be using require_once. There's no need to load it more than once.
// Replace the require('config.php') with:
require_once('config.php');
2 - Are you defining constants in your "config.php"? The dbConnection::dbConnection() function is looking for constants named dbHostName, dbUserName, dbPassword, and dbDatabaseName. Make sure your "config.php" is defining constants.
3 - The while($row = mysql_fetch_array($dbMethods->fetchAllPortfolioItems())) in dbFunctions.php is wrong. The mysql_fetch_array portion of the while is "recalculated" on every iteration which means that it's executed over and over again. If you assign the value of $dbMethods->fetchAllPortfolioItems() to a variable first, the function is only executed once and the while will iterate through the results. Use this instead:
$result = $dbMethods->fetchAllPortfolioItems();
while($row = mysql_fetch_array($result))
{
$pageContent = $row["description"];
}
As per the while documentation:
It tells PHP to execute the nested
statement(s) repeatedly, as long as
the while expression evaluates to
TRUE.
The mysql_fetch_array($dbMethods->fetchAllPortfolioItems()) part of the while you're using will always evaluate to TRUE as long as the query return a row as it's getting called over and over (thus returning the same first row every single time).
The error that's causing the "Internal Server Error" is probably because your script is taking more than the max_execution_time allowed in php.ini.
It's maybe because you're never actually connecting to the database before you query it.
Essentially, you've made a function with the same name as the class for dbConnection instead of using the __construct method.
You will see a very clear error message in your server error log, in apache on linux:
/var/log/apache/error.log
and I would also take a look (if it is not clear from the previews log) at the mysql error log, which is also somewhere under /var/log/...

Categories