I am using mongodb 3.2 and php 7
I have installed the driver and its working..
Here is my code
<?php
$client = new MongoDB\Driver\Manager();
$db = $client->selectDatabase('inventory');
?>
how to connect to database "inventory"
the error that comes is
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::selectDatabase()
I don't think you want to call the Manager directly. The newer MongoDB extension that replaces the built-in PHP Mongo DB client; You need to have the following requirements for the code to work. The code example that follows assumes the following:
You load with the composer autoloader.
You have the new MongoDB Driver extension from here: http://php.net/manual/en/set.mongodb.php
That you use the composer MongoDB Client library from here: http://php.net/manual/en/mongodb.tutorial.library.php
PHP >=5.6
use MongoDB\Client as MongoDbClient;
// When auth is turned on, then pass in these as the second parameters to the client.
$options = [
'password' => '123456',
'username' => 'superUser',
];
try {
$mongoDbClient = new MongoDbClient('mongodb://localhost:27017');
} catch (Exception $error) {
echo $error->getMessage(); die(1);
}
// This will get or make (in case it does not exist) the inventory database
// and a collection beers in the Mongo DV server.
$collection = $mongoDbClient->inventory->beers;
$collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
foreach ($result as $entry) {
echo $entry['_id'], ': ', $entry['name'], "\n";
}
Related
I tried to connect to AS400 using Php Slim Framework.
It returned to me an error about odbc connection php function.
I edited this framework files this way.
SETTINGS.PHP
<?php
declare(strict_types=1);
use App\Application\Settings\Settings;
use App\Application\Settings\SettingsInterface;
use DI\ContainerBuilder;
use Monolog\Logger;
return function (ContainerBuilder $containerBuilder) {
// Global Settings Object
$containerBuilder->addDefinitions([
SettingsInterface::class => function () {
return new Settings([
'displayErrorDetails' => true, // Should be set to false in production
'logError' => false,
'logErrorDetails' => false,
'logger' => [
'name' => 'slim-app',
'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
'level' => Logger::DEBUG,
],
"db" => [
'name' => 'EDDXXXXXXX',
'username' => 'XXXXXXX',
'password' => 'XXXXXXXX',
'connection' => 'xxxxxx.xxx.xxxxx'
]
]);
}
]);
};
DEPENDENCIES.PHP
<?php
declare(strict_types=1);
use App\Application\Settings\SettingsInterface;
use DI\ContainerBuilder;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
LoggerInterface::class => function (ContainerInterface $c) {
$settings = $c->get(SettingsInterface::class);
$loggerSettings = ...........CODE HERE ..........
return $logger;
},
PDO::class => function (ContainerInterface $c) {
$settings = $c->get(SettingsInterface::class);
$dbSettings = $settings->get('db');
$name = $dbSettings['name'];
$username = $dbSettings['username'];
$password = $dbSettings['password'];
$dsn = "Driver={Client Access ODBC Driver (32-bit)};System=" .
$connection . ";libraries=" . $name .
";naming=system;transaction isolation=read committed;Uid=" .
$username .";Pwd=" . $password . ";";
//return new PDO($dsn, $username, $password);
return odbc_connect($dsn, $username, $password);
},
]);
};
ROUTES.PHP
$app->get('/db-test', function (Request $request, Response $response) {
$db = $this->get(PDO::class);
$sth = $db->prepare("SELECT * FROM XXXX");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$payload = json_encode($data);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
});
When i call /db-test I obtain this server error
"statusCode": 500,
"error": {
"type": "SERVER_ERROR",
"description": "ERROR: odbc_connect(): SQL error: [Microsoft][Driver Manager ODBC] Nome origine dati non trovato e driver predefinito non specificato., SQL state IM002 in SQLConnect on line 46 in file C:\\slim\\as400\\app\\dependencies.php."
}
I don't understand why it gives to me that error.
The odbc_connect function in your DI container is not correct, because it returns a resource, but not a PDO object. It should be return new PDO($dsn, $username, $password);
Data source name not found and default driver not specified., SQL state IM002. Make sure that the ODBC driver is installed and that the data-source name exists. I recommend to try this connection string for AS400.
Provider=IBMDA400;Data Source=MY_SYSTEM_NAME;User Id=myUsername; Password=myPassword;Default Collection=MY_LIBRARY;
or
Driver={IBM i Access ODBC Driver};System=mySystem;Uid=myUser;Pwd=myPassword;
File DSN for iSeries AS400 ODBC connection
https://www.connectionstrings.com/as-400/
My experience with PHP and IBM i is that you need to use the ODBC drivers, not PDO_ODBC. This experience is admittedly old, and may no longer be true, however, I looked at the current PHP 8.1 documentation for PDO_ODBC and found this:
ibm-db2
Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 express-C client.
unixODBC
Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.
generic
Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.
On Windows, php_pdo_odbc.dll has to be enabled as extension in php.ini. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN.
So PDO_ODBC supports DB2 UDB. This is only one of the three flavors of DB2, and unfortunately not the one used by IBM i. So maybe you can get the generic ODBC PDO to work, but I would stick to just ODBC, not PDO unless you execute the spend money command and purchase the DB2 Connect product which will let you access the enterprise DB2 products (DB2 for i and DB2 for zOS) from a Windows/Unix/Linux box.
I'm trying desperately to figure out how to create a simple audio transcription script (for longer audio files) via PHP (the only language I know). I'm getting the error Class 'Google\Cloud\Storage\StorageClient' not found
I'm using the gcloud console code editor and everything should be installed (unless there is a separate composer install just for cloud storage, although I haven't been able to find anything about it in the documentation if there is).
I also entered gcloud auth application-default print-access-token which printed out an access token, but I don't know what (if any) I'm supposed to do with that other than the "set GOOGLE_APPLICATION_CREDENTIALS" command that I copied and pasted into the console shell prompt.
Here's the php code:
<?php
namespace Google\Cloud\Samples\Speech;
require __DIR__ . '/vendor/autoload.php';
use Exception;
# [START speech_transcribe_async_gcs]
use Google\Cloud\Speech\SpeechClient;
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\ExponentialBackoff;
$projectId = 'xxxx';
$speech = new SpeechClient([
'projectId' => $projectId,
'languageCode' => 'en-US',
]);
$filename = "20180925_184741_L.mp3";
# The audio file's encoding and sample rate
$options = [
'encoding' => 'LINEAR16',
'sampleRateHertz' => 16000,
'languageCode' => 'en-US',
'enableWordTimeOffsets' => false,
'enableAutomaticPunctuation' => true,
'model' => 'video',
];
function transcribe_async_gcs($bucketName, $objectName, $languageCode = 'en-US', $options = [])
{
// Create the speech client
$speech = new SpeechClient([
'languageCode' => $languageCode,
]);
// Fetch the storage object
$storage = new StorageClient();
$object = $storage->bucket($bucketName)->object($objectName);
// Create the asyncronous recognize operation
$operation = $speech->beginRecognizeOperation(
$object,
$options
);
// Wait for the operation to complete
$backoff = new ExponentialBackoff(10);
$backoff->execute(function () use ($operation) {
print('Waiting for operation to complete' . PHP_EOL);
$operation->reload();
if (!$operation->isComplete()) {
throw new Exception('Job has not yet completed', 500);
}
});
// Print the results
if ($operation->isComplete()) {
$results = $operation->results();
foreach ($results as $result) {
$alternative = $result->alternatives()[0];
printf('Transcript: %s' . PHP_EOL, $alternative['transcript']);
printf('Confidence: %s' . PHP_EOL, $alternative['confidence']);
}
}
}
# [END speech_transcribe_async_gcs]
transcribe_async_gcs("session_audio", $filename, "en-US", $options);
With apologies, PHP is not a language I'm proficient with but, I suspect you haven't (and must) install the client library for Cloud Storage so that your code may access it. This would explain its report that the Class is missing.
The PHP client library page includes two alternatives. One applies if you're using Composer, the second -- possibly what you want -- a direct download which you'll need to path correctly for your code.
Some time ago, I wrote a short blog post providing a simple example (using Cloud Storage) for each of Google's supported languages. Perhaps it will help you too.
I am using Laravel 5.5 with the AWS SDK for laravel (https://github.com/aws/aws-sdk-php-laravel).
I'm trying to do a simple request to establish that I'm connecting correctly. I believe I have my credentials all set and nothing points to that as an error.
Here is the function in my laravel controller that is being called:
public function testData(Request $request) {
$sdk = new Sdk([
'endpoint' => 'http://localhost:80',
'region' => 'us-east-1',
'version' => 'latest'
]);
$dynamodb = $sdk->createDynamoDb();
$marshaler = new Marshaler();
$tableName = 'funTalkDataStorage';
$params = [
'TableName' => $tableName
];
try {
$result = $dynamodb->query($params);
} catch (DynamoDbException $e) {
echo "Unable to query:\n";
echo $e->getMessage() . "\n";
}
}
The table 'funTalkDataStorage' does exist out on AWS already where there are two records already.
The thing that I'm not understanding is why I'm getting the following error from Laravel:
Aws \ Api \ Parser \ Exception \ ParserException
Error parsing JSON: Syntax error
being thrown by :
aws\aws-sdk-php\src\Api\Parser\PayloadParserTrait.php
The error is originating from the line in my code:
$result = $dynamodb->query($params);
I've been digging through the sdk and searching the web and I'm just not getting where the issue is. Any help would be marvalous!
Ok. My issue was that i was using port 80. It should have been port 8000.
I am using the PHRETS PHP library to fetch the RETS data from the rets API. I have and issue with getting the Data. It's giving me the Requested Class not found Error. Please help to solve this Error. My Code is:
date_default_timezone_set('America/New_York');
require_once("vendor/autoload.php");
$log = new \Monolog\Logger('PHRETS');
$log->pushHandler(new \Monolog\Handler\StreamHandler('php://stdout', \Monolog\Logger::DEBUG));
$config = new \PHRETS\Configuration;
$config->setLoginUrl('http://rets.navicamls.net/login.aspx')
->setUsername('xxx')
->setPassword('xxx')
->setRetsVersion('1.7.2');
$rets = new \PHRETS\Session($config);
$rets->setLogger($log);
$connect = $rets->Login();
if ($connect) {
echo "Connected!<br>";
}
else {
echo "Not Connected!<br>";
print_r($rets->Error());
exit;
}
//results consists of Property, class, and query
$results = $rets->Search(
"Property",
"A",
"*",
[
'QueryType' => 'DMQL2',
'Count' => 1, // count and records
'Format' => 'COMPACT-DECODED',
'Limit' => 10,
'StandardNames' => 0, // give system names
]
);
print_r($results); exit;
You need to first verify the name of the class in your search query is correct by looking up the metadata.
Use RETSMD.com and enter the RETS Server login url, username, and password.
Use the metadata functions in the PHRETS documentation on the main page
a. $system = $rets->GetSystemMetadata();
b. $classes = $rets->GetClassesMetadata('Property');
So i always get a pdo exception when i try to create my db in the constructor of my Mapper class.
on this line:
$this->db = new PDO($dsn, $db_config['username'], $db_config['password']);
this is my dsn creation:
$db_config = array(
'driver' => 'pgsql',
'username' => $dbUser,
'password' => $dbPassword,
'schema' => 'r0628740',
'dsn' => array(
'host' => 'gegevensbanken.khleuven.be',
'dbname' => '2TX31',
'port' => '51314',
)
);
and finaly my constructor:
public function __construct(){
global $db_config;
$dsn = $db_config['driver'] . ':';
foreach($db_config['dsn'] as $key => $value){
$dsn .= $key . '=' . $value . ';';
}
try{
$this->db = new PDO($dsn, $db_config['username'], $db_config['password']);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(($db_config['driver'] == 'pgsql') && isset($db_config['schema'])){
$this->db->query(sprintf("SET SEARCH_PATH TO %s"), $db_config['schema']);
}
}catch (PDOException $e){
var_dump($e->getLine());
error_log($e->getMessage());
}
}
The PHP contains a dll required by pgsql and pgsql_pdo driver libpq.dll...
Add PHP binary path to system path or copy de DLL into Windows\system32. On linux dependency are installed automatically.
I found article somewhere, works for me. Assuming you have installed PostgreSQL and your WAMP installation is on c:\wamp, you will need to copy:
c:\wamp\bin\php\php5.3.9\libpq.dll to c:\wamp\bin\apache\Apache2.2.11\bin.
Make sure you also have the following files:
C:\wamp\bin\php\php5.3.9\ext\php_pdo_pgsql.dll and
C:\wamp\bin\php\php5.3.9\ext\php_pgsql.dll
Also, make sure you have enabled the above 2 files as extensions, either via the WAMP menu (click on WAMP icon on taskbar: PHP > PHP extensions, find the above 2 and 'check' them).
Please note that php5.3.9 and Apache2.2.11 refer to my specific PHP and Apache versions.
Adjust those to suit your installation.
Copying this libpq.dll from c:\wamp\bin\php\php5.3.9\libpq.dll to c:\wamp\bin\apache\Apache2.2.11\bin. has worked for me