I'm getting a problem using ZF2 and DbAdapter.
I'm making a select statement and trying to get te exception when happen some error.
I have my select statement inside a block try... catch... but the problem is when I set a "wrong query", the exception is not threw.
Here my service:
return array(
'db' => [
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=my_dbname;host=localhost',
'username' => 'root',
'password' => 'root',
'driver_options' => [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]
],
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => function ($serviceManager) {
$adapterFactory = new Zend\Db\Adapter\AdapterServiceFactory();
$adapter = $adapterFactory->createService($serviceManager);
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter);
return $adapter;
}
),
),
);
Here my query:
try {
$db = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$sql = "SELECT * FROM `table`";
$statement = $db->query($sql);
$res = $statement->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
Reivaldo, welcome to stackoverflow!
Since Zend DB drivers utilizing custom statement instances, Exceptions thrown by PDO and other possible errors handled internally and converting to Zend\Db\Adapter\Exception instances if necessary.
Check out this example.
Instead of catching the PDOException in your code, always catch possible exceptions from most specific one to most generic one. This is a good practice.
For example:
try {
// code to throw exceptions
} catch (\Zend\Db\Adapter\Exception $e) {
echo $e->getMessage();
} catch (\Exception $e) {
// This is not an adapter exception, anyway its an exception.
echo $e->getMessage();
} finally {
// This block always executed, an exception thrown or not.
}
You may also want to read some documentation about exception handling.
Related
Given the code
$connectionParams = array(
'dbname' => $this->dbname,
'user' => $this->dbuser,
'password' => $this->dbpass,
'host' => $this->dbhost,
'driver' => 'mysqli',
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
var_dump($conn);
How can I get the underlying mysqli handle from $conn (which is a Doctrine\DBAL\Connection)?
I have found *a way* to access it, but its obviously not the way it's supposed to be done, so I'm up for suggestions:
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
foreach((array)$conn->getWrappedConnection() as $mysqli){
// TODO: find official way of getting the handle.
// here we are casting it to (array) to access its PRIVATE PROPERTIES
// it's a fugly hack.
break;
}
var_dump($mysqli);
You can get it this way:
$mysqli = $conn->getWrappedConnection()->getWrappedResourceHandle();
I have the following code :
DB::select($sql, $params);
DB::beginTransaction();
try {
DB::commit();
} catch (Exception $e) {
DB::rollback();
return [
'code' => 500,
'error' => true,
'message' => 'There was a problem saving your transaction.'
];
}
Which is causing the following error:
message: "There is no active transaction"
exception "PDOException"
There should be more instructions in the try statement but to show that none of them have an affect they have been removed. It seems to be that select is for some reason opening a transaction and not closing it. (The select is running an SP that returns two result sets but I only want one hence the use of select.) Everything works well without the select statement, and the select statement on it's own doesn't cause any errors and returns what I need. However, if I put the select statement in the try statement it causes an exception.
Thanks.
Does something like this work?
DB::beginTransaction();
DB::select($sql, $params);
try {
// your code that could fail
}
catch (Exception $e)
{
DB::rollback();
return [
'code' => 500,
'error' => true,
'message' => 'There was a problem saving your transaction.'
];
}
DB::commit();
return [
'code' => 200,
'error' => false,
'message' => 'Successful transaction.'
];
I am writing a database class which is going to connect to my pdo database. This class is using this config file to get the information needed:
<?php
return [
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'database_name' => 'books',
'database_type' => 'mysql',
'options' => []
];
And this is the database class:
<?php
class DB
{
public static function connect($config)
{
try {
return new PDO([
$config['database_type'] . ':host=' . $config['host'] . ';dbname=' . $config['database_name'],
$config['username'],
$config['password'],
$config['options']
]);
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I am getting this error:
Fatal error: Uncaught TypeError: PDO::__construct() expects parameter
1 to be string, array given in and etc...
I am wondering what I did wrong, sicne I don't see any syntax mistakes in my code.
You have an extra set of brackets:
return new PDO([
...
]);
... shouldn't have the [ and ] respectively; they're turning your four function parameters into a single array parameter. You want simply
return new PDO(
...
);
HTH!
I am having problems with a connection to the database, specifically, when I try to access the system and the database does not respond.
I am getting an error in my services.php file.
And this is the code:
try{
$di->set('db', function () use ($config) {
$config = $config->get('database')->toArray();
$dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
if (stripos($config['adapter'], 'Mysql')!== false) {
$mi_conf = array(
"host" => $config['host'],
"username" => $config['username'],
"password" => $config['password'],
"dbname" => $config['dbname'],
"options" => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
)
);
} else {
$mi_conf = array(
"dbname" => '//'.$config['host'].'/'.$config['dbname'],
"username" => $config['username'],
"password" => $config['password'],
'charset' => 'utf8'
);
}
unset($config['adapter']);
return new $dbClass($mi_conf);
});
} catch (Exception $e) {
$error .= 'db, ';
return null;
}
I do not know if it will be necessary to change there or I have to make changes to each call from each model.
Any advice?
Thank you.
The code looks without errors.
Use setShared to avoid connecting to the database multiple times, or use the "persistent" attribute on the configuration to take effect. Maybe it does the trick. By the way, change the try catch to the moment where the service was created, so you can catch the exception.
$di->setShared('db', function () use ($config) {
try {
$config = $config->get('database')->toArray();
$dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
if (stripos($config['adapter'], 'Mysql') !== false) {
$mi_conf = array(
"host" => $config['host'],
"username" => $config['username'],
"password" => $config['password'],
"dbname" => $config['dbname'],
"persistent" => false,
"options" => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
),
);
} else {
$mi_conf = array(
"dbname" => '//' . $config['host'] . '/' . $config['dbname'],
"username" => $config['username'],
"password" => $config['password'],
"persistent" => false,
'charset' => 'utf8',
);
}
unset($config['adapter']);
return new $dbClass($mi_conf);
} catch (Exception $e) {
$error .= 'db, ';
return null;
}
});
Google released recently a new version of its Gmail API which now makes possible to create filters.
However the documentation is quite limited and I'm facing issues to get it working. I'm using the latest version of their PHP client. Any help would be appreciated to construct the request body.
public $gmail;
public function createFilter($userId) {
try {
$filter = new Google_Service_Gmail_Resource_UsersSettingsFilters();
// Here, we should create the request body...
// https://developers.google.com/gmail/api/v1/reference/users/settings/filters#resource
// $filter->setCriteria() ??
$this->gmail->users_settings_filters->create($userId, $filter);
} catch (Exception $e) {
// Logging errors...
}
}
UPDATE (Working method)
public $gmail;
public function createFilter($userId) {
try {
$filter = new Google_Service_Gmail_Filter([
'criteria' => [
'from' => 'example#gmail.com'
],
'action' => [
'addLabelIds' => ['STARRED']
]
]);
$this->gmail->users_settings_filters->create($userId, $filter);
} catch (Exception $e) {
// Logging errors...
}
}
See https://github.com/google/google-api-php-client#making-requests for guidance on constructing request objects. You should be able to populate the filter properties using native PHP arrays or the autogenerated objects. Example:
$filter = new Google_Service_Gmail_Resource_UsersSettingsFilters([
'criteria' => [
'from' => 'somebody#example.com'
],
'action' => [
'addLabelIds' => ['STARRED']
]
]);