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
Related
I'm trying to get PDO connecting to an SQL server to enter READ UNCOMMITTED, according to various sources (https://msdn.microsoft.com/en-us/library/cc296183(v=sql.105).aspx) this is how you do it.
$pdo = new PDO ("sqlsrv:server=$hostname;database=$dbname",$username,$pw,[PDO::SQLSRV_TXN_READ_UNCOMMITTED]);
This results in a PDOException: "The auto-commit mode cannot be changed for this driver"
When you're using PDO, you have to use this form:
$conn = new PDO("sqlsrv:Server=".$hostname.
";Database=".$database.
";TransactionIsolation=".PDO::SQLSRV_TXN_READ_UNCOMMITTED,
$username, $pw);
https://msdn.microsoft.com/en-us/library/ff628167.aspx
I was reading the post "Create new database and tables on the fly"
I tried to implement an updated version of the create schema function:
public static function createSchema($schemaName)
{
$dbName = "db_{$schemaName}";
return DB::getSchemaBuilder()
->getConnection()
->statement("CREATE DATABASE :schema", ['schema' => $dbName ]);
}
but I get the following error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1 (SQL: CREATE DATABASE :schema)
PDO does not allowed to bind params on a create database query. So i'm not sure how to create DB's on the fly as safely as possible. Can anyone show me the way, before i have to introduce a security flaw in our site.
You cannot use bindings with CREATE DATABASE and PDO, because in CREATE DATABASE foo, foo isn't a quoted identifier, it's a raw new database name. You'll need to do any sanity checking yourself rather than relying on parameter binding to protect you.
public static function createSchema($schemaName)
{
$dbName = "db_{$schemaName}";
$quotedDbName = preg_replace("/[^_a-zA-Z0-9]+/", "", $dbName);
return DB::statement("CREATE DATABASE $quotedDbName");
}
See this question for more details about CREATE DATABASE with PDO binding.
public static function createSchema($schemaName)
{
// We will use the `statement` method from the connection class so that
// we have access to parameter binding.
return DB::getConnection()->statement('CREATE DATABASE :schema', ['schema' => 'db_' . $schemaName]);
}
i believe you dont need schema builder here
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.
I'm migrating my local files online and having PHP issues with my db script. Works fine locally (running PHP 5.3.8) but gives me the following errors on my server (PHP 5.3.10)
Without $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Fatal error: Call to a member function setFetchMode() on a non-object in /.../...php on line 108
With $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user '...'#'205.186.180.26' for table 'invited'
Here is my code:
class guest {
public $id;
public $guest_name;
public $url_phrase;
}
$guest = new guest;
if (isset($_GET['p'])) {
$url_phrase = urldecode($_GET['p']);
} else if (isset($_POST['p'])) {
$url_phrase = urldecode($_POST['p']);
}
if (isset($url_phrase)) {
try {
$DBH = new PDO("mysql:host=myhost.com;dbname=mydbname", "myusername", "mypassword");
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$url_phrase = $DBH->quote($url_phrase);
$sql = "SELECT id, guest_name, url_phrase FROM mydbname.invited WHERE url_phrase = $url_phrase";
$stmt = $DBH->query($sql);
$stmt->setFetchMode(PDO::FETCH_INTO, new guest);
$guestNumber = $stmt->rowCount();
if($guestNumber > 0) {
etc...
}
if($guestType == "solo") {
foreach($stmt as $guest) {
$name = $guest->guest_name;
etc...
}
}
} else {
other stuff.. etc..
$DBH = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I've gotten simple select statements to work fine as this user (I don't think its permission-related), my problem seems to be with my implementation of PDO. How can I get rid of this error? Am I preparing/executing the statement in a weird way that's messing this up? Thanks for any help
I had the same problem. After I uploaded my code from local to production server, and the user had all privileges. The problem was the database name -- in my local environment it was something like dattabase1 and in production the name was different...prefix_ddatabas1. I changed the name of the database to the correct one and everything was ok.
Sounds like an access issue on the server:
SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command
denied to user '...'#'205.186.180.26' for table 'invited'
Have you tested from the CLI (or some other sql client outside of PHP) to ensure your script will have access?
You will likely need to log into the db to give access to a user your script is running as or check the credentials you're using in the script are accurate for the db in the server environment.
I had same issue, code working at dev server but not at prod server, and other scripts working with same table were working. I had missed to correct database table prefixes between dev and prod environment. (the database's names were not the same) ^^
I received the same error. The dev DB name was different than the production DB name thus causing this error. I changed the name of the db in my code to the production DB name and it worked.
Thanks
You have an access violation:
Syntax error or access violation
The user/host you're using:
1142 SELECT command denied to user '...'#'205.186.180.26'
can not select from the table 'invited'
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"