PHP and MongoDB - php

I am trying to connect to MongoDB via PHP.
mongod --version
db version v3.2.8
Then,
php -i | grep mongo
/etc/php/7.0/cli/conf.d/20-mongodb.ini,
mongodb
mongodb support => enabled
mongodb version => 1.1.8
mongodb stability => stable
libmongoc version => 1.3.5
mongodb.debug => no value => no value
I tried:
sudo pecl install mongodb
which returns
pecl/mongodb is already installed and is the same as the released version 1.1.8
install failed
which (the install failed bit) gets redressed if I try:
sudo pecl uninstall mongodb
and
sudo pecl install mongodb
I have this php file:
<?php
echo "I am here";
$connection = new Mongo('localhost');
$db = $connection->mydb;
$list = $db->listCollections();
foreach ($list as $collection) {
echo "$collection </br>";
}
echo "I am never here";
?>
I cannot see the second echo.
I would appreciate any thoughts.
Thank you.

First, check #sanjay comment and then apply this connection:
$db = new MongoClient('mongodb://localhost', [
'username' => 'root',
'password' => '',
'db' => 'YOUR DB'
]);
Hope it will work for you.

I managed to have it working. Thanks to this post:
After upgrading PHP to version 7, why can't I use the mongodb driver?
and this post:
Using the PHP Library for MongoDB (PHPLIB)
Sorry as it seems pretty odd (to me!) but indeed: MongoClient() has become (verbatim! with the slash!) MongoDB\Client().
Hence, the file I had in my original post becomes:
<?php
require 'vendor/autoload.php';
echo "I am here";
$manager = new MongoDB\Client();
$database = $manager->mydb;
foreach ($database->listCollections() as $databaseInfo) {
var_dump($databaseInfo);
}
echo "I managed to arrive here";
?>
and I can see the contents of mydb as well as the 2 echos. The vendor/autoload.php was generated by
sudo composer require "mongodb/mongodb=^1.0.0"
as I ran it from within the directory of the php file above. Probably not the best idea as I, now, have to resolve how to make the autoload.php (and all it carries with) globally available. But, nonetheless, at least, I managed to arrive somewhere.
I am using: PHP 7.0.8-0ubuntu0.16.04.2 (cli) ( NTS )
under: Ubuntu 16.04.1 LTS

Related

mamp pro, php 7.3.8 and remote mssql server

i use mamp pro on mac (catalina) and try to connect to remote mssql server.
in order to work with mssql i installed on the relevant php mamp folder:
brew install msodbcsql17 mssql-tools
pecl install sqlsrv pdo_sqlsrv
than i updated the php.ini file
extension=sqlsrv.so
extension=pdo_sqlsrv.so
when i try to run (of course with the correct credentails and server name)
$db = new PDO("sqlsrv:Server=MY.SERVER;Database=MYDBNAME", "MYUSER", "MYPASS");
i get this error:
Fatal error: Uncaught PDOException: SQLSTATE[IMSSP]: This extension requires the Microsoft ODBC Driver for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver for SQL Server for x64: https://go.microsoft.com/fwlink/?LinkId=163712
what am i missing?
The PHP-PDO driver wants to access MS-SQL-server via the ODBC driver of SQL-server.
You need to install the odbc driver by doing
brew install msodbcsql17 mssql-tools
Afterwards, you need to enable TCP connections on sql-server, add a login, add the login to the correct role, and then you need to open port 1433, so TCP connections to SQL-server can work (unless you have both PHP and the sql-server run on the same machine).
And you might have to install UnixODBC:
brew install unixodbc
Also, you might have to add php_odbc to extensions
extension=php_odbc.dll
and php-fpm uses another ini file than php-cli/php-cgi.
On ubuntu, the PHP-fpm ini file is in
/etc/php/7.2/fpm/php.ini
while the other is in
/etc/php/7.2/cli/php.ini
Another alternative, if you can't get ODBC to work, is to use PDO_DBLIB, which uses FreeTDS instead of ODBC. That might be better anyway.
sudo pecl install pdo_dblib
However, that restricts you to php > 5.03 < 6.0.0.
Maybe you can compile it from source.
Mine works on Linux, all I had to do was:
sudo apt-get install php-fpm php-dev php-pear
sudo pecl install sqlsrv pdo_sqlsrv
(msodbcsql17 and mssql-tools I already had installed)
add the lines
extension=sqlsrv.so
extension=pdo_sqlsrv.so
into both ini files, and done.
Then I executed the connection-test-sample
php ./test.php
(i have port 2017, on docker), and it worked:
<?php
$serverName = "localhost,2017";
$connectionOptions = array(
"database" => "MY_DB_NAME",
"uid" => "sa",
"pwd" => "TOP_SECRET"
);
// Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
die(formatErrors(sqlsrv_errors()));
}
// Select Query
$tsql = "SELECT ##Version AS SQL_VERSION";
// Executes the query
$stmt = sqlsrv_query($conn, $tsql);
// Error handling
if ($stmt === false) {
die(formatErrors(sqlsrv_errors()));
}
?>
<h1> Results : </h1>
<?php
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['SQL_VERSION'] . PHP_EOL;
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
function formatErrors($errors)
{
// Display errors
echo "Error information: <br/>";
foreach ($errors as $error) {
echo "SQLSTATE: ". $error['SQLSTATE'] . "<br/>";
echo "Code: ". $error['code'] . "<br/>";
echo "Message: ". $error['message'] . "<br/>";
}
}
?>
<h1>Results: </h1>
Microsoft SQL Server 2017 (RTM-CU16) (KB4508218) - 14.0.3223.3 (X64)
Jul 22 2019 17:43:08 Copyright (c) Microsoft Corporation
Developer Edition (64-bit) on Linux (Ubuntu 16.04.6 LTS)
I get a funny warning, though:
PHP Warning: PHP Startup: Unable to load dynamic library
'/usr/lib64/php/modules/pdo_sqlsrv.so' -
/usr/lib64/php/modules/pdo_sqlsrv.so: undefined symbol:
php_pdo_register_driver in Unknown on line 0
If I remove
extension=pdo_sqlsrv.so
then it works, without warning.
Note:
Just fixed the crap.
If you run php --ini, it will list you all the ini-files php loads.
The correct location (on Linux) to put these two lines is
/etc/php/7.2/mods-available/pdo.ini
The above warning occurs if extension=pdo_sqlsrv.so is loaded before extension=pdo.so. Also, that way, you only need to set the extension ONCE, and it's done for both php-cli and php-fpm. The mods-available are then (already) symlinked into php-fpm and php-cli.
You might have the same problem on Mac.
To make sure there are no permission issues, create a test user that is sysadmin:
-- The available default languages:
-- SELECT * FROM sys.syslanguages AS sysl
CREATE LOGIN [WebServicesTest] WITH PASSWORD = 'TOP_SECRET'
,CHECK_EXPIRATION = off
,CHECK_POLICY = off
,DEFAULT_LANGUAGE = us_english;
EXEC master..sp_addsrvrolemember [WebServicesTest], N'sysadmin';
To test if the connection is actually working with the user, you can use AzureDataStudio.
Beware:
If your system uses OpenSSL 1.1 (e.g. Ubuntu 19.04), you need to download the insiders-build.
TDS-based providers (freeTDS/ODBC) need TCP open, even if you work on localhost.
if anyone needs the answer
turned out need to install one more thing:
brew install msodbcsql#13.1.9.2 mssql-tools#14.0.6.0

Error GRPC Spanner Google Cloud With PHP

I'm using PHP to try using the Google Cloud Spanner. I already did the gCloud settings and everything, and that's right. Now I need to make the connection via PHP to do a CRUD with the database that is in Spanner, but the code below always returns the error:
PHP Fatal error: Undefined constant 'Grpc\STATUS_UNKNOWN' in
/xxx/xxxx/www/vendor/google/cloud-spanner/Connection/Grpc.php on line
129
The code I have is:
<?php
require 'vendor/autoload.php';
use Google\Cloud\Spanner\SpannerClient;
/* Error start here */
$spanner = new SpannerClient([
'projectId' => 'my-project-id'
]);
$db = $spanner->connect('instance', 'database');
$userQuery = $db->execute('SELECT * FROM usuario WHERE login = #login', [
'parameters' => [
'login' => 'devteam'
]
]);
$user = $userQuery->rows()->current();
echo 'Hello ' . $user['login'];
The requirements I use in the composer are:
"require": {
"google/cloud": "^0.32.1",
"google/cloud-spanner": "^0.2.2"
}
I noticed that if I enter through the browser, the error presented above continues to appear. If I run the command php teste.php on the terminal, it runs the script correctly, ie, the terminal works and the browser does not.
Google Cloud PHP's spanner client is gRPC only. This means to use it you will need to install the gRPC PHP extension:
pecl install grpc
Once you have done that, add google/proto-client-php and google/gax to your composer.json and run composer update. After this is done, the error will be resolved.
For those wanting more detailed instructions, see this page for installing and enabling gRPC for PHP!
Since you mentioned that it works on CLI but not on browser, I can say that you need to enable the grpc extension on your php web server config.
E.g. Add
extension=grpc.so to your /etc/php/5.6/apache2/php.ini

Class 'MongoDB\Client' not found, mongodb extension installed

I tried to create new mongo connection executing the following code
$m = new MongoDB\Client();
and i got this error:
Fatal error: Class 'MongoDB\Client' not found
i think i have properly installed MongoDB extension
(Copied php_mongodb.dll to ext folder and updated php.ini with extension=php_mongodb.dll).
The following code confirms it is loaded:
echo extension_loaded("mongodb") ? "loaded\n" : "not loaded\n";
I still receive the same error.
Here is
phpinfo()
I appreciate all your help. Thank you!
If you are using latest MongoDB extension of PHP, MongoDB\Driver\Manager is the main entry point to the extension.
Here is the sample code to retrieve data using latest extension.
Let's say you have testColl collection in testDb. The you can retrieve data using MongoDB\Driver\Query class of the extension.
// Manager Class
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// Query Class
$query = new MongoDB\Driver\Query(array('age' => 30));
// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$cursor = $manager->executeQuery('testDb.testColl', $query);
// Convert cursor to Array and print result
print_r($cursor->toArray());
Output:
Array
(
[0] => stdClass Object
(
[_id] => MongoDB\BSON\ObjectID Object
(
[oid] => 5848f1394cea9483b430d5d2
)
[name] => XXXX
[age] => 30
)
)
I'm using PHP 7.1.9 and I had this issue. Solved it by removing and reinstalling mongodb/mongodb
composer remove mongodb/mongodb
composer require mongodb/mongodb
Also, If you are using Dreamweaver, don't for get to put the vendor folder in the server copy.
After installing, I can now use MongoDB\Client.
mongodb API Version 1.3, Mongodb Extension 1.4
same happened with me, check the version of php install on your server.
You have to use php version 5.6 .Check the apche error log to get more precise error detail.
Just simple way to install
sudo apt-get install php-mongodb
after install mongo
Different for Apache and Nginx it appears.
Though this post is old but I help this migh help someone. I recently ran into same problem. With me it was s different php.ini.
I kept placing the mongoextension into /cli/php.ini.
Thoough when I ran <?php phpinfo() ?> I found out that in my case the loaded configuration is in /fpm/php.ini. This was because I was unsing Nginx with fpm.
90% of the time it is your Mongodb extension configuration. kindly check in php.ini
\MongoDB\Driver\Manager(); is now "low level" extension (php_mongodb), \MongoDB\Client was rewritten to "PHP class" and you need extra install https://docs.mongodb.com/drivers/php/ to use old style nice new \MongoDB\Client('mongodb://127.0.0.1');

PHP & Mongo broken after Mac OSX Mavericks upgrade

Following an OSX 10.9.3 upgrade a number of things didn't work. Apache, Mongo and PHP are all working independently now, however the mongo extension for php is not. I am hoping the stackoverflow community can help. Here's the basic problem:
$ sudo pecl install mongo
pecl/mongo is already installed and is the same as the released version 1.5.3
install failed
$ php --re mongo
Exception: Extension mongo does not exist
Pecl and PHP are having a disagreement on whether the mongo extension is there. mongo.so does physically exist here: /opt/local/lib/php/extensions/no-debug-non-zts-20090626/mongo.so where it was installed and here: /usr/lib/php/extensions/no-debug-non-zts-20100525 where I copied it because that is where php.ini points. It is executable in both places. It seems odd that it is getting installed in the wrong spot, so maybe there is a pecl config that needs to be flipped? Also pecl is not finding php.ini at the end of the install, but I am updating manually.
The best summary of the directions for getting back up after the 10.9 upgrade appears to be here: http://fighterpilotstress.blogspot.com/2013/10/installing-mongodb-driver-with-php-on.html and I have followed it faithfully. I have also installed the commandline tools as referenced here: Unable to install mongodb php driver on mac os 10.9.
Relavent php.ini lines:
include_path = ".:/usr/lib/php/pear"
extension=mongo.so
any help appreciated. Thanks, Brian
I hanged up for a while in the same situation on ubuntu, then I just tried
1) In your phpinfo() screen, make sure the Configuration file Path and Loaded Configuration File match the PHP file you are editing. If not, then find the correct php.ini and add the mongo.so extension.
2) In your phpinfo() screen, look at the extension_dir value and confirm that mongo.so exists in that directory. If not, find the mongo.so file and copy it to this directory.
3) Restart your web server.
4) If it's still not working, take a look at the web server & php logs for clues as to why the extension might not be loading.
from Error enabling MongoDB module
All was ok on my side, but still I kept getting,
$ php --re mongo
Exception: Extension mongo does not exist
then I checked with this test script and was able to connect to mongoDB.
<?php
try {
// open connection to MongoDB server
$conn = new Mongo('localhost');
// access database
$db = $conn->test;
// access collection
$collection = $db->items;
// execute query
// retrieve all documents
$cursor = $collection->find();
// iterate through the result set
// print each document
echo $cursor->count() . ' document(s) found. <br/>';
foreach ($cursor as $obj) {
echo 'Name: ' . $obj['name'] . '<br/>';
echo 'Quantity: ' . $obj['quantity'] . '<br/>';
echo 'Price: ' . $obj['price'] . '<br/>';
echo '<br/>';
}
// disconnect from server
$conn->close();
} catch (MongoConnectionException $e) {
die('Error connecting to MongoDB server');
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
?>
Therefore try the script and if you are able to connect without errors, forget about the extension :).

Doctrine 2 configuration and performance

I've got some problems with Doctrine 2 on my localhost. One page, which uses only one query, is loading on localhost in about 1.5s. Meanwhile, on remote server loading takes about 300ms (http://gieromaniak.pl/contact). I have no idea what could be wrong. Is it Doctrine 2 configuration or sth else? Or maybe I don't have some PHP extension on my server (WAMP - Apache 2.4.2, PHP 5.4.3)?
Nevertheless, I'm including source code of my Doctrine configuration file:
<?php
use Doctrine\Common\ClassLoader,
Doctrine\ORM\Configuration,
Doctrine\ORM\EntityManager,
Doctrine\DBAL\Types\Type,
Doctrine\Common\Cache\ArrayCache,
Doctrine\DBAL\Logging\EchoSqlLogger;
// include the class loader directly
require_once __DIR__ . '/Doctrine/Common/ClassLoader.php';
$doctrineClassLoader = new ClassLoader('Doctrine', __DIR__ . '/');
$doctrineClassLoader->register();
Config::load('base');
Config::load('database');
if(Config::get('base.mode') == 'development') {
$bProxyGen = TRUE;
} else {
$bProxyGen = FALSE;
}
// Set up caches
$cache = new ArrayCache;
$config = new Configuration;
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
// Metadata Driver
$driverImpl = $config->newDefaultAnnotationDriver($models);
$config->setMetadataDriverImpl($driverImpl);
// Proxy configuration
$config->setProxyDir(PATH_ROOT.Config::get('database.proxy_dir'));
$config->setProxyNamespace(Config::get('database.proxy_namespace'));
$config->setAutoGenerateProxyClasses($bProxyGen);
// Database connection information
$connectionOptions = array(
'driver' => 'pdo_mysql',
'charset' => 'utf8',
'dbname' => 'dbname',
'user' => 'username',
'password' => 'password',
);
// Create EntityManager
$entityManager = EntityManager::create($connectionOptions, $config);
Thank You in advance for any help!
I would recommand to install apc and to improve mysql performance:
Install APC
I strongly recommend to use Wamp server (x86) for that, the apc.dll for the x64 version of windows doesn't work well.
follow this tutorial with the following modifications:
the link to apc.dll
find the Zend Extension Build or PHP Extension Build ,from your phpinfo(); you can use that http://localhost/?phpinfo=1 for your WAMP localhost
the Zend Extension Build should be like this :
API220100525,TS,VC9
Note the TS word, it can be blank; look if their is a different word like NTS
download the latest version according to the TS or NTS value
rename the dll php_apc.dll
put the php_apc.dll in YourWampFolder/bin/php/ext/
there are 2 php.ini files in wamp : wamp\bin\apache\apacheX.X.XX\bin\ and wamp\bin\php\phpX.X.X\ (replace the X.X... by your versions)
write extension=php_apc.dll; in both of them
close/open Wamp (not restart)
from the wamp icon->php->PHP extensions->php_apc.dll check to activate
restart wamp
you can verify that APC is running by downloading the apc.php file into your project dirctory. You will find it in the compressed file available at the PECL website. Take the latest version.
Now from your browser : http://localhost/yourproject/apc.php
You can modify the settings of APC from php.ini (try both)
exemple :
//php.ini
...
[APC]
apc.ttl=7200
apc.user_ttl=7200
apc.shm_segments=3
apc.shm_size=90M
apc.max_file_size = 2M
apc.include_once_override = 1
just in case you want to clear the cache
// resetcache.php
<?php
if ( $_GET['pass'] == 'yes') {
if(function_exists('apc_clear_cache')){
if (apc_clear_cache() && apc_clear_cache('user'))
print 'All Clear!';
else
print 'Clearing Failed!';
print '<pre>';
print_r(apc_cache_info());
print '</pre>';
}else print "fuction_doesn't exist";
} else {
print 'Authenticate, please!';
}
i put some extra security to prevent unwanted access but do not include apc.php and clearcache.php in the production server.
Increase Mysql performance
link1
link2
link3
Clean local machine
You can clean your browser cache and temp folders. CCleaner
This is all that i did to increase the speed of Doctrine2 on my local machine in the past.
you can also monitor the Ram used by Mysql/Apache process to see if you don' t need to buy/allocate more RAM.

Categories