I'm trying to build a blog website.
It is deployed on Heroku and it is supposed to connect to a MySQL database. The info required to login to my database is stored in an environment variable on Heroku, and looks like this (These are fake credentials of course):
mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true
It contains the DB name, the user, the password and the host.
Is there a way to use this one string directly in my PHP code to connect to the database? I checked MySQLi and PDO documentation, and it seems like they only accept DSN/user/password or Host/user/password/DBname format.
This is a url after all, so you can use parse_url function to extract data.
// Connection string from environmental variable in heroku
$connectionStringHerokuEnv = 'mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true';
$parsed = parse_url($connectionStringHerokuEnv);
$dbname = ltrim($parsed['path']. '/'); // PATH has prepended / at the beginning, it needs to be removed
// Connecting to the database
$conn = new PDO("{$parsed['scheme']}:host={$parsed};$dbname={$dbname};charset=utf8mb4", $parsed['user'], $parsed['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
For database connection you should always use PDO and not mysqli driver. PDO allows you to connect to almost any database, without rewriting code in 85% of cases.
dont forget options [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION], this will allow you to catch any errors and handle them accordingly to application needs.
PDO accept this connection string driver: host=DATABASE_HOST;dbname=DATABASE_NAME; charset=DEFAULT_CHARSET(use utf8 whenever you can)
Learn more on parse_url: https://www.php.net/manual/en/function.parse-url
Learn more on PDO:
https://www.php.net/manual/en/class.pdo.php
<?php
$str = "mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true";
// If I correctly understanded 'mysql://login:passwd#host/dbname?some_params'
// data parsing from input string
$sp = explode('/', $str);
$sp1 = explode('#', $sp[2]);
$first_part_sp = explode(':', $sp1[0]);
$login = $first_part_sp[0];
$passwd = $first_part_sp[1];
$host = $sp1[1];
$dbname = explode('?', $sp[3])[0];
$connect_str = "mysql:host=$host;dbname=$dbname";
echo $connect_str." ".$login." ".$passwd;
// database access
$pdo = new PDO($connect_str, $user, $passwd);
?>
Related
I am trying to connect to the database via PDO and my db.php file is as follows:
$host = "localhost";
$db = "mydb";
$user = "user";
$pass = "qRES2fIWK8Gg";
try
{
$db = new PDO("mysql:host = $host; dbname = $db", $user, $pass);
$db -> exec ("SET NAMES utf8"); // charset = utf8 doesn't work.
echo "Database connection is successful. <br>";
}
catch (PDOException $e)
{
echo $e -> getMessage();
}
I have two problems which I think there is a connection between them.
When I check the db.php, I can get Database connection is successful message even though I change the host and dbname with random and incorrect values. How is that possible? When I try the same process on the database username and password, it gives an error.
I am unable to run SQL queries without stating database name in it as PDO
doesn't fetch database name from db.php. For example, this SQL query
doesn't work:
SELECT * FROM settings WHERE settings_id= :id
However, this one works successfully:
SELECT * FROM mydb.settings WHERE settings_id= :id
I was working on localhost. After this problem, I thought it has been related to localhost and I moved my project to a virtual host. However, this step hasn't fixed the problems.
Removing the spaces in your DSN string should resolve your issues:
"mysql:host=$host;dbname=$db"
I'm hosting a domain at 1&1 and I want to connect with my database using pdo. Without using a port, it doesn't work and I don't know how to add the port to my code....
$mysql_host = "xxxxxxxxx";
$mysql_username = "xxxxxxxxxxxxxx";
$mysql_database = "xxxxxxxxxxxxxxx";
$mysql_password = "xxxxxxxxxxxxxxx";
$pdo = new PDO("mysql:host=" . $mysql_host . ";dbname=" . $mysql_database , $mysql_username , $mysql_password);
Im not sure but maybe the Problem doesn't go together with the connection, but with the mysql-commands...
$schematic_statement = $pdo->prepare('SELECT title FROM schematics-download WHERE id = 1');
$schematic_statement->bindParam('title', $Title);
$schematic_statement->execute();
$TITLE = $schematic_statement->fetch();
echo ($TITLE);
Thank you for your help!
"Without using a port, it doesn't work and I don't know how to add the port to my code...."
This (probably) has nothing to do with porting.
Your code however, contains a few (syntax) errors.
1) You can't bind a column (or a table)
Your SELECT title and bindParam('title' suggest it.
2) FROM schematics-download - mysql is interpreting that as FROM schematics MINUS download, therefore you need to escape the table name.
I.e.:
FROM `schematics-download`
If this is a porting issue, then this user contributed note shows you how to do it.
$conn = new PDO('mysql: host=123.4.5.6;dbname=test_db;port=3306','username','password');
^^^^^^^^^^
and from http://php.net/manual/en/ref.pdo-mysql.connection.php
More complete examples:
mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
As for error handling, PDO has that:
http://php.net/manual/en/pdo.error-handling.php
which would have thrown you a few.
Taken from Chris' comment:
"Later you fetch which returns an array so $TITLE can't be echoed."
Take a look at the documentation on fetching data in PDO:
http://php.net/manual/en/pdostatement.fetch.php
There are ample examples in there to show you on to do this.
I've already searched for an answer to this questions, but all that I found didn't work for me. I've a problem with the pdo connection in php.
When I enter the mysql datas directly into the pdo statement, it works properly. But when I use variables instead, it doesn't. I already looked up how to include variables into a pdo statement, but it didn't work.
This is the code, when it works:
$host = 'localhost';
$username = 'root';
$password = 'password';
$dbname = 'Database';
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
And here is the code, when it doesn't work:
$file = "mysqldatas.txt";
$lines = file($file);
$host = $lines[1];
$username = $lines[2];
$password = $lines[3];
$dbname = $lines[4];
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
As you can see, I try to read the datas from a text file the second time. But I don't see where the difference between 'localhost', and $lines[1] is, because when I echo the $lines[1], the output is localhost, as it should be.
Please help me guys, this is really annoying. It would be great, if you could also explain why it makes a difference between directly entering the hostname, or using a variable, that holds the hostname (as I said, I used echo, and it said localhost).
Thank you for your help guys!
Bye.
The actual issue is that the file() will also get newlines with each line, unless the FILE_IGNORE_NEW_LINES is used (or some sort of trim() function). So you'll need to use
$lines = file($file, FILE_IGNORE_NEW_LINES);
instead. From the manual of file(), it tells us that
Note:
Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.
trim() is also a possibility instead of this flag.
There's a few other, different possibilities to separate credentials and connections, the most common one is to either use a file connection.php which creates the object, where you just include that, and use that wherever you need a connection, or creating your own .ini file with the credentials, and getting it via parse_ini_file().
connection.php
$host = 'localhost';
$username = 'root';
$password = 'password';
$dbname = 'Database';
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
Other files
require "path/to/connection.php";
$con->prepare(...);
Then there's usage of .ini files. You can create a config.ini file, and get the values from parse_ini_file()
config.ini
host = localhost
dbname = Database
user = root
password = password
type = mysql
Connection
$config = parse_ini_file("config.ini");
$con = new PDO($config['type'].":host=".$config['host'].";dbname=".$config['dbname'], $config['username'], $config['password']);
References
http://php.net/manual/en/function.file.php
http://php.net/manual/en/function.trim.php or http://php.net/manual/en/function.rtrim.php
http://php.net/manual/en/function.parse-ini-file.php
pretty sure you are getting newlines when you use the file function. try this:
$file = "mysqldatas.txt";
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$host = $lines[1];
$username = $lines[2];
$password = $lines[3];
$dbname = $lines[4];
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
From http://php.net/manual/en/function.file.php :
Return Values ΒΆ
Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.
I try to set connection with my site and mssql database. I can connect to database, but i can't execute SQL queries. My code is
$connection = mssql_connect('jass8l1.database.windows.net', 'username', 'password');
if (!$connection){
print_r(mssql_get_last_message());
}else{
$res= mssql_query('SELECT * FROM [my_database].[dbo].[table]', $connection);
print_r(mssql_get_last_message());
$row = mssql_fetch_array($res);
echo $row[0];
}
This code shows error
Reference to database and/or server name in 'my_database.dbo.table' is not supported in this version of SQL Server.
But when I execute this query online, link MANAGE URL, this error does not occur.
How can I solve this problem? Maybe I need some additional driver is for PHP?
The error message cannot be more descriptive than it is!
You simply cannot use the 4-word-notation (i.e. [DB_NAME].[SCHEMA].[TABLE_NAME].[COLUMN]. With SQL Azure you shall always use the 3-word notation (i.e. [SCHEMA].[TABLE].[COLUMN]).
Something more for SQL Azure is that you have to explicitly set Database in your connection. You can not do USE [DB_NAME] in SQL Azure.
When using SQL Azure with PHP I recommend that you go through the How to: Connect to Windows Azure SQL Database from PHP.
You have to alter your connection to something like:
$serverName = "tcp:ProvideServerName.database.windows.net,1433";
$userName = 'ProvideUserName#ProvideServerName';
$userPassword = 'ProvidePassword';
$dbName = "TestDB";
$table = "tablePHP";
$connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);
sqlsrv_configure('WarningsReturnAsErrors', 0);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if($conn === false)
{
FatalError("Failed to connect...");
}
Also, it is strongly recommended to use Microsoft's MS SQL driver and not the standard PHP provided MSSQL (also referred in the How To).
I have connected to an MS-SQL Server 2008 database via PHP and now I want to extract data to variables, how is that done?
I have the following code:
$myServer = "214187-1";
$myUser = "ytuser";
$myPass = "***********";
$myDB = "*********";
//create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr); //Open the connection to the database
//declare the SQL statement that will query the database
$query = "SELECT FacebookAppID, FacebookAppSecret, TwitterConsumerKey, TwitterConsumerSecret, LinkedinAPIKey, LinkedinSecretKey FROM Systems WHERE SystemID = " $G_SYSTEMID;
$FacebookAppID = ;
$FacebookAppSecret = ;
$TwitterConsumerKey = ;
$TwitterConsumerSecret = ;
$LinkedinAPIKey = ;
$LinkedinSecretKey = ;
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
Any help would be greatly appreciated..
neojakey
I suggest you look into a few things - somebody telling you exactly how to do it isn't going to help you.
First up, learn how to structure your query properly with some basic SQL knowledge Basic SQL Syntax
Next, look at how php executes a SQL statement - the two main commands you'll need to define a variable are:
mysql_query - this is used to execute the query.
and
mysql_fetch_array - this is for getting the data into an array from the mysql_query (note: you dont have to use '...fetch_array' - there are others such as '...fetch_row'.
Read up on those and you'll have the knowledge to do what you want.