How to connect to PostgreSQL DB with PHP? - php

As you can already see in the title I want to connect to a PostgreSQL Database I created on a server using PHP and Yii2. Unfortunately I am a total novice when it comes to this kind of job and I have never done it before so I have several questions that I hope some of you can answer.
I am using Yii2 basic and in the config directory there is a db.php file containing the following code:
return [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;dbname=my1DB',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
Is the code actually OK? Instead of localhost I will be using the host IP of course. The db my1DB is actually created and already contains a relation named countries.
I have Yii2 basic installed on my client. Now my question is, do I need to install it on the server as well? It may be a dumb question and I am truly sorry if it is, but I am not sure if I am understanding it all correctly. So, does the db.php file need to be on the server? Or is it OK if it is simply installed on my client?

The db.php would need to be on server side where the PHP is running at, in case the PostgreSQL server is running on the same server that PHP is, you can leave it as localhost and it should work fine, just make sure the credentials and db name exist.

Related

Can I generate database mysql from existing project developed in codeigniter framework?

Can I generate database mysql from existing project developed in codeigniter framework?
Screenshot of the project structure is given below.
I think, you are trying to generate migrations and seeders in Laravel, Similar thing is not possible in Codeigniter,
Another better way to do this, create a PHP file for run the MySql, that you have wrote before
I will suggest you use Codeigniter Migrations. That is if you are not a newbie.
You can read on it here: https://www.codeigniter.com/user_guide/libraries/migration.html
Else another option is to export your current database into an *.sql file and then import as your new database project using your SQL manager like PhpMyadmin.
Then go to your application/config/database.php file and change these settings
'hostname' => DB_HOSTNAME,//to your database host e.g localhost
'username' => DB_USERNAME,//your username for the host
'password' => DB_PASSWORD,// your password for the username
'database' => DB_NAME,// your database name

PDOException SQLSTATE[HY000] [1049] Unknown database 'forge' failed

I want to access a Mysql data the first step is to create a new table for "vanvlymen" and I typed mysql> USE vanvlymen; the database changed. and type SHOW tables; showing the available of the tables that the database contains.
mysql -u root -p
enter password: ****
mysql> show databases;
-databases-
information_schema
mysql
performance_schema
phpmyadmin
vanvlymen
5 rows...
everything is looking good...
I have decide to tell mysql to specify the database I am working on before executing the query as "vanvlymen"
app/config/database.php
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'vanvlymen',
'username' => 'foobar',
'password' => 'foobar',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
save as file go to FileZilla using FTP find a file drag and drop into my live server overwrite the database.php file.
I have tried to clear the cache like that
php artisan cache:clear
php artisan migrate
it errors:
SQLSTATE[42000] [1049] unknown database 'forge'.
Why keeping it said unknown database 'forge' I am excepting to change to vanvlymen database. Should I remove mysql and reinstall?
I am using windows 8.1 with laravel 4.2
Using phpmyadmin, I know what is the password and username to log in.
remove two files config.php and services.php in /bootstrap/cache. And try again.
Do you have something like app/config/yourEnvironment/database.php ?
For example local or production. 'forge' is default name of DB in this config file, so it looks like your app is loading wrong config file.
Hopefully this will help someone else. I suddenly had an issue where my dev site I was building stopped connecting to the DB, and just as the OP it was saying:
PDOException SQLSTATE[HY000] [1049] Unknown database 'forge' failed
After much head scratching (!) I found that my hostname value set inside the /bootstrap/start.php was wrong, because my hostname had changed on my macbook pro!? I have no idea how but it changed from something like RobMacbookPro2.local to RobMacbookPro.local. This meant it fell back to production thus loading the incorrect database.php file with the standard DB=forge (which was wrong)
Check this guide:
http://laravel.com/docs/4.2/configuration
Pay particular attention to the code:
<?php
$env = $app->detectEnvironment(array(
'local' => array('your-machine-name'),
));
On a mac and probably linux? you can determine your hostname by typing # hostname in terminal.
Hope that saves someone some time!
If you are running both Xampp and MySQL Workbench, or if You are Running Xampp on the port other than the default port, there may be chances of confusion, you may have created the database using PHPMyAdmin and you are trying to connect it to localhost:cusotmport (e.g. localhost:8080).
what I suggest is to create the database you want using MySQL workbench and then you would get your task done...

Why does yii2 try to connect to mysql when I have not configured it to?

This is what I did:
I downloaded the yii2 advanced template.
Ran php init.
Configured each of main-local.php files in
environments/dev/common/config
environments/prod/common/config
common/config
I added the following to the 'components'
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite:/path/to/sqlitedbs/yayr.sq3',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
I configured the apache vhosts as explained in the readme.
Running yii migrate created the sqlite database file in the configured location with no errors.
What breaks is when I go to the frontend app and try to submit the sign up form, it gives me this error:
Exception
Database Exception – yii\db\Exception
SQLSTATE[28000] [1045] Access denied for user 'root'#'localhost' (using password: NO)
↵
Caused by: PDOException
SQLSTATE[28000] [1045] Access denied for user 'root'#'localhost' (using password: NO)
in /home/johnsmith/dev/test/yayr/vendor/yiisoft/yii2/db/Connection.php at line 579
The full stack trace can be seen: http://pastebin.com/KEKH1zbM
I have used my IDE to search for every location that a mysql dsn exists. The only place is in /tests/codeception/config/config.php which should not be called by submitting a form. To double check, I commented out the config, and it didn't help.
I also tried setting 'driverName' => 'sqlite', in the config, but that did not make any difference. Neither did commenting out the username, password, or charset parameters.
None of the functions referenced by the stack trace appear to manually call MySQL. They all look for the configured dsn.
So, why does Yii think it can even try to connect to MySQL? Doesn't ActiveRecord abstract out all the SQL so that it won't matter if I'm using MySQL or sqlite?
How do I get past this issue? Using sqlite would make initial development a lot easier.
Thanks!
Basics of the Yii2 advanced template
You have the environments-folder containing you actual config files
The frontend- and backend-folders hold copies of those "local"-files, depending on which environment you selected, they get copied from dev or prod
Now what does that mean? If you perform changes on ANY file within the envirnments folder, you have to re-init your application. You simply do this by opening a console, navigate to the base folder of your application and call the init-command. You will then be asked which envirnment you want and what files to overwrite.
After that you should see your changes beeing reflected in the frontend- and backend-folder. The idea behind this is to prevent if/else-structures within the config files and have a clean application. By the way: the index.php within the web-folders gets copied the same way. That way you could even customize this...and therefore the way the application gets loaded initially.
Back to your problem
For me it looks like you changed the settings within the environments/.../local-...-configfile, which is right...but then didn't re-init the application. That way the config file within the front- and backend still contain your old settings.
Documantation of the advanced template
Everything is very well documented here:
https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md
After init command
Create a new database and add it in common/config/main-local.php
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=your-db',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
Apply yii migrate in console command!
It'll create the tables for the application to work

php netbeans and mysql: how do i retrieve data from my database

i am very new to php and i am trying to work my way through it. i have a php project which was not written on my pc and i imported onto the netbeans, i also set up my mysql database and connected it with netbeans since i am running the project on netbeans, also, i am working with a code igniter framework.
When i try to sign up, it doesn't sign me up, meaning my project doesn't see the database on my local server...anyone knows what i can do please? do i need to change some settings in my project? I tested my database connection on netbeans and it is working.
For code ignitior read this guide for connecting to the database:
http://ellislab.com/codeigniter/user-guide/database/connecting.html
you can try this in your php script:
$db = mysqli_connect(host,username,password,dbname);
In frameworks, database connection is usually done in config file. I dont know code igniter but in Yii framework it is done in /config/main.php and looks like this:
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=databasename',
'emulatePrepare' => true,
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
),

CakePHP Database connection "Mysql" is missing, or could not be created

There have been several other posts about this, but none of the answers seemed to work for me.
When I navigate to the CakePHP page on my local machine, there is one error:
Cake is NOT able to connect to the database. Database connection
"Mysql" is missing, or could not be created.
When I run this helpful code in my home.ctp, I get the following response:
Error!: SQLSTATE[42000] [1049] Unknown database 'test'
However, my Users/Ben/Sites/myapp/app/Config/database.php looks like this (I set MAMP to look for the document root in Users/Ben/Sites):
<?php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'Ben',
'password' => 'mypass',
'database' => 'CV',
);
}
I have created a mysql user called Ben with password mypass and created a database called CV under that. Moreover, I can't find mention of a test database anywhere. Help?
Try adding the socket:
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
An alternative to unix_socket (especially for OS X people) is to replace localhost with 127.0.0.1
Would be as Follows :
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => '127.0.0.1',
'login' => 'user',
'password' => 'password',
'database' => 'database-name',
'prefix' => '',
'encoding' => 'utf8',
);
Edit php.ini and add:
extension=php_pdo_mysql.dll
Then restart your web server
On Mac, using MAMP as a development platform, for cake the correct solution is using Domingo Casarrubio solution.
Add the unix_socket parameter to your database configurations.
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
This error can also be caused if your connecting database user doesn't have the proper privileges. I believe you only need a minimum of INSERT, SELECT, UPDATE, and DELETE.
Always check username/password and the user privileges first since CakePHP will most likely give a vague database connection error for either.
I noticed that you've had asked this an year ago, and most probably would've solved this by now. However, for those facing the same issues when attempting to install CakePHP on XAMPP, all you have to do is change the 'login' to 'root', i.e. the default login of XAMPP, and leave the 'password' as '', i.e. blank. The complete code in your database.php file should look like this:
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'ckblog',//replace with your own database name
'prefix' => '',
//'encoding' => 'utf8',
);
That's it.
I had the same problem and found out eventually that it was caused by CakePhp not accepting that I used a user with a password, even if that user was created in PHPMyAdmin. I had to use the user 'root' with no password.
I found this out after making the following change to the file /lib/Cake/Error/exceptions.php.
The original line:
protected $_messageTemplate = 'Database connection "%s" is missing, or could not be created.';
is changed into this instead (note the change from single to double quotes):
protected $_messageTemplate = "Database connection \"%s\" is missing, or could not be created:\n %s";
This will give you the reason for the problem so that you may change the cause properly.
I have had this problem since upgrading to OSX Yosemite and inserting following line did the trick for me:
'unix_socket' => '/tmp/mysql.sock'
It can be that mysql PDO support is missing.
as root (or using sudo):
apt-get install php5-mysql
Just to help Ubuntu users out:
I had the same error in my ubuntu 13.10 machine with the newest xampp downlaoded directly from apachefriends. Tried most of the stuff in every post I could find about this error, but not the mac-specific stuff.
In the end, the fix happened to be the same as the elected answer here:
Find the socket that mysqld creates for programs to connect to:
user#host /opt$ find . -name mysql.sock
/opt/lampp/var/mysql/mysql.sock
add it to your cakePHP database configuration file (cakePHP)/app/Config/database.php
'unix_socket' => '/opt/lampp/var/mysql/mysql.sock'
To me, this finally resulted in my cake commands being able to be executed without the "Error: Database connection "Mysql" is missing, or could not be created.".
Because, cake bake use unix socket for connecting to database
so that you need add unix_socket for connection string.
You have to confirm location that store mysql.sock in WAS
Example: in my case i'm using xampp on MACOS 10.11
(edit file Config/database.php)
public $default = array(
‘datasource’ => ‘Database/Mysql’,
‘persistent’ => false,
‘host’ => ‘localhost’,
‘login’ => ‘root’,
‘password’ => ‘root’,
‘database’ => ‘cakephp’,
‘encoding’ => ‘utf8’,
‘unix_socket’ => ‘/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock’
);
Finally, It's work for me!
What did it for me in the end was that I had created a table in my database, but there was no data in it.
In order for CakePHP to recognize the MySql connection, there has to be a table with data in it.
You might need to create the table in your php file... Open up phpMyAdmin and check to ensure that they database CV exists.
It's your model. Open that up and there must be the following line
public $useDbConfig = 'local';
This overwrites global config & set it back to local
I tried splicing the code from Example 2 of http://php.net/manual/en/pdo.connections.php into /app/View/Pages/home.ctp. I had to fix the arguments the PDO constructor and change the name of the table in the query. The example 2 code returned the error "Error!: could not find driver". Based on King Jk's answer I was attempting to modify the php.ini when I started to wonder where a php_pdo_mysql.so might live. http://php.net/pdo_mysql showed how it was compiled as part of PHP via the --with-pdo-mysql option to configure. Recompiling fixed my problem. Note I'm working on a Ubuntu 12.10 system with PHP 5.5.9 and Apache Webserver 2.4.6
In my case it was because the database didn't exist. I expected running ./app/Console/cake schema create would create it but it did not. Creating it with create database <database name> in mysql did the trick (although I had already assigned privileges).
I've been struggling with this the whole weekend and finally solved it. Turns out that the php.ini is pointing to a non-existing "extensions dir". Create a phpinfo() file and look at the value of this field:
I noticed that in the mamp php installed folder there is a no-debug-non-zts-20131226 folder, which is different from the value shown in the phpinfo(). What I did was to clone this folder and changed the name to the value of the phpinfo(). Probably you could modify the php.ini file but I didn't want to.
I don't know if you solved your problem, but I'm posting this because my problem was different and google took me here, so I hope to help future googlers having a similiar issue.
Hope this helps.
If you're on Godaddy (or any other shared hosting for that matter), they may be limiting outgoing connections to ports 80 and 443 only.
System configuration:
Fedora 32
php-fpm 7.4.13
mariadb 10.4.17
CAKE 2.10.17
Error message from CAKE:
Database connection "Mysql" is missing, or could not be created.
Enhanced error message using answer at https://stackoverflow.com/a/24722976/5025060
Database connection "Mysql" is missing, or could not be created: Selected driver is not enabled
My problem was no "connector" between PHP and SQL was installed. The solution was:
dnf install php-mysqlnd
This allowed PHP to connect to the database as specified in CAKE's database.php configuration file.

Categories