Create database if not exist in FuelPHP - php

First of all I don't have any database and I write code in migrations to create database, table and data, I want to check if database not exist then auto create new database have name in db connect and try catch this connect if error.
public function up()
{
try {
\DBUtil::create_database('database_name', 'utf8_general_ci', true);
// the true flag adds a IF NOT EXISTS
} catch(\Database_Exception $e) {
echo $e->getMessage();
}
}
try code but give error "Unknown database database_name" when I run "php oil refine migrate" in commandline
Can I try catch custom exception this error?
1049!
Fuel\Core\Database_Exception [ 1049 ]:
SQLSTATE[HY000] [1049] Unknown database 'database_name'

Creating a database is not something that is usually done by migrations as it would tie you in to using the same DB name all the time, if you are deploying multiple sites on the same server or have a similar scenario this becomes a big problem.
It's generally assumed that the database itself has been created as part of the set-up, either manual or automatic, so is available for PHP to connect to.

Related

WordPress database error INSERT command denied to user 'readonly'

I'm working with Wordpress and PHP. We had an issue in which our w writer db became our reader r db during a fail over in the database cluster. This cause the production site to break. Currently, I'm trying to prevent the site from crashing do to this.
I get the following error from WP Engine when the database is trying to insert data into a table:
WordPress database error INSERT command denied to user
'readonly'#'xx.xxx.xx.xx' for table 'responses' for query INSERT INTO
responses (uid, data) VALUES
The error is raise from the following function:
<?php
namespace StatCollector;
function drools_request($data, $uid) {
try {
$db = _get_db();
$insertion = $db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
if($insertion === false) {
throw new \Exception('Error writing to the database: ' . $db->last_error);
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
When the database become --read-only this shouldn't stop the site to work. Why isn't error handling working in this case. Does this mean that to error handle this I need to catch an Error? Why isn't the error handling working here?
[Not sure this works, but it is too long for a comment]
You didn't mention your back-end database, so I bet it is MySQL because you mentioned Wordpress.
You can try to instruct mysql to throw exceptions, like this:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
class.mysqli-sql-exception
I wouldn't advice to do that in the core of wordpress itself, but you can try calling it before executing your try/catch.
Edit: Some people advice MYSQLI_REPORT_ALL instead of MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT. Give it a try and see what works best in your situation.

Laravel 5.1 - Checking a Database Connection

I am trying to check if a database is connected in Laravel.
I've looked around the documentation and can't find anything. The closest thing I've found is this, but this doesn't solve my problem.
I have three instances of MySQL that are set up on different machines. Below is a simplified version of what I am trying to achieve.
If database 1 is connected, save data to it
If database 1 is not connected, check if database 2 is connected
If database 2 is connected save data to it
If database 2 is not connected, check if database 3 is connected
If database 3 is connected, save data to it
To be clear, is there a way to check that a database is connected in Laravel 5.1?
Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!
use Illuminate\Support\Facades\DB;
// Test database connection
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration. error:" . $e );
}
You can use alexw's solution with the Artisan. Run following commands in the command line.
php artisan tinker
DB::connection()->getPdo();
If connection is OK, you should see
CONNECTION_STATUS: "Connection OK; waiting to send.",
near the end of the response.
You can use this, in a controller method or in an inline function of a route:
use Illuminate\Support\Facades\DB;
//....
try {
DB::connection()->getPdo();
if(DB::connection()->getDatabaseName()){
echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
}else{
die("Could not find the database. Please check your configuration.");
}
} catch (\Exception $e) {
die("Could not open connection to database server. Please check your configuration.");
}
You can also run this:
php artisan migrate:status
It makes a db connection connection to get migrations from migrations table. It'll throw an exception if the connection fails.
You can use this query for checking database connection in laravel:
use Illuminate\Support\Facades\DB;
// ...
$pdo = DB::connection()->getPdo();
if($pdo)
{
echo "Connected successfully to database ".DB::connection()->getDatabaseName();
} else {
echo "You are not connected to database";
}
For more information, you can check out this page https://laravel.com/docs/5.0/database.
I don't know if this worked in that version of laravel, but at least on newer ones you can run
php artisan db
and if your app can access the database then you should see a cli repl for it, for postgres you will see a psql instance
Another Approach:
When Laravel tries to connect to database, if the connection fails or if it finds any errors it will return a PDOException error. We can catch this error and redirect the action
Add the following code in the app/filtes.php file.
App::error(function(PDOException $exception)
{
Log::error("Error connecting to database: ".$exception->getMessage());
return "Error connecting to database";
});
Hope this is helpful.

Laravel and multiple database connections

This might be a silly question. I have two separate databases that are being used with Laravel 4. One of them can only be accessed with a certain IP (security reasons) while the other can be accessed. I have two different mysql connections. I have seen the Database connection test using this:
if(DB::connection('mysql')->getDatabaseName()){ }
To test what can be seen and what can't be seen, I tried to give the mysql a false password. I get this nice ugly error how it can't connect. Is there a way to make it where if the Database cannot be reached, just to ignore it? There's only one PHP class that's calling the secure only database on page load, but the above check doesn't seem to be working.
Going through the core code of laravel, there is no specific exceptions being thrown when a database connection fails.
The solution hence, is:
try {
//Strings always evaluate to boolean true
$dbConnected = (bool)DB::connection('mysql')->getDatabaseName();
}
catch (Exception $e)
{
$dbConnected = false;
}
Then work your code based on the variable $dbConnected.

PDO doesn't seem to create MySQL database

I'm trying to create a database using the following code:
// Set up DB connection and creates the DB
try {
$connection = new \PDO(
'mysql:host='.Settings\Database::$host.';',
Settings\Database::$username,
Settings\Database::$password);
$connection->exec("CREATE DATABASE IF NOT EXISTS ".Settings\Database::$databaseName." CHARACTER SET utf8 COLLATION utf8_unicode_ci;");
} catch (\PDOException $exception) {
die("Could not connect to database: ".$exception->getMessage());
}
The problem is that no database is being created and I receive no error except for the fact that when I try create a table with PDO i receive this error:
READ EDIT 2
Could not connect to database: SQLSTATE[HY000] [1049] Unknown database 'dbname'
Edit:
I have no problem manually creating the DB with phpMyAdmin and similars.
Edit 2:
Mistakenly I thought that the error was given by the CREATE TABLE... statement. Instead the error is returned by the die() function in the exception handling.
Your call to exec() isn't throwing exceptions. You have to enable that for each PDO connection with an attribute like this:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
If you were getting the error message from exec(), you would have seen this:
Could not connect to database: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'COLLATION utf8_unicode_ci' at line 1
The syntax for CREATE DATABASE uses the keyword COLLATE, not COLLATION.
See http://dev.mysql.com/doc/refman/5.6/en/create-database.html

PHP/PDO - Flush privileges

I'm doing some mysql server management with a script that flushes the MySQL users privileges when new privileges are added to a MySQL user.
I'm using the PDO class to do my queries, but when I do a simple
FLUSH PRIVILEGES;
I get, for
$connection->exec('FLUSH PRIVILEGES;');
and
$connection->query('FLUSH PRIVILEGES;');
SQLSTATE[42S02]: Base table or view
not found: 1146 Table 'mysql.servers'
doesn't exist
Is it possible to do such query with the PDO class or do I have to resort to using mysql(i)?
I've just tried the following portion of code :
$dsn = 'mysql:dbname=mysql;host=127.0.0.1';
$user = 'root';
$password = '********';
try {
$db = new PDO($dsn, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->query('flush privileges;');
} catch (PDOException $e) {
var_dump($e);
}
And I don't get any kind of error like the one you are describing.
Are you sure you don't have some problem with you MySQL server ?
Your error message says that table "mysql.servers" doesn't exists... But when I look at my local MySQL server, there is such a table -- are you sure your installation/configuration is not "broken" and you didn't delete that table or anything like that ?
BTW, it doesn't seem to be some kind of privilege you're not having : if you try to flush privileges without having the required privilege, you get the following error : "SQLSTATE[42000]: Syntax error or access violation: 1227 Access denied; you need the RELOAD privilege for this operation"

Categories