MySQL PHP: PDO connection not working when getting credentials from file() - php

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.

Related

Connect to MySQL database in PHP

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);
?>

Using user-supplied database credentials across multiple pages

I am learning to use MySQL with PHP and while practicing, I tried to create a simple web application using Core PHP and MySQL. It is summarized below:
-It has a pretty simple html page where username(uname) and password(pword) for MySQL are input in a form and are sent by POST method to a PHP script called PHP1.php
-PHP1 makes connection to MySQL. The code is(skipping PHP tags):
//Get input username and password
$username = $_POST['uname'];
$password = $_POST['pword'];
//Server information
$server = "localhost";
//Connect
$conn = new mysqli($server, $username, $password);
//Check success/failure
if ($conn -> connect_error)
{
die("Connection failed".$conn->connect_error);
}
After connecting, PHP1 retrieves information about the databases stored in the respective account and displays radio buttons to select the database and sends the name of the selected database by GET method to another script PHP2.php
-In PHP2.php I want to display the TABLES in the selected database.
However, when control is transferred to PHP2.php, connection to MySQL is terminated. I first tried to include my PHP1.php file in PHP2.php and use the $conn variable but ofcourse it'll try to reconnect to MySQL due to the above mentioned code and at the same time, the first request containing uname and pword is lost resulting in an authentication error.
How can I overcome this problem?
EDIT:
I have seen other questions here but all of them have fixed usernmae/passwords and so the connection script can be placed in a separate file easily. I require to take username and password from the user.
Use Sessions which will persist the session variables across pages:
PHP1
session_start();
$_SESSION['username'] = $username = $_POST['uname'];
$_SESSION['password'] = $password = $_POST['pword'];
$server = "localhost";
$conn = new mysqli($server, $username, $password);
PHP2
session_start();
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$server = "localhost";
$conn = new mysqli($server, $username, $password);
In PHP1 you're going to want to check that the $_POST values are set and in other pages you'll want to check that the $_SESSION variables are set. See isset.

Connection to server via pdo is not working, how to add port to the connection?

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.

query doesn't working using php

I am new in Php and MYsql,
I am trying to create a simple query using which contain a variable using php.
however I think I am not writing the querty correctly with the variable since the result of this query is 0.
would be happy for assistance here is my code:
<?php
$phone = $_GET['phone'];
echo $phone;
$query = "SELECT * FROM `APPUsers` WHERE `Phone` LIKE "."'".$phone."' ";
echo $query;
$result = mysqli_query($mysqli, $query);
echo mysqli_num_rows($result);
?>
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = $conn->query($sql);
Above there is a fast solution , but it is not safe ,
because is vulnerable to injection ...
Below let's see how to do it and why to do it in this way
It is a good practice to store sensible information in a separate file
out of the document root , it means will be not accesible from the web .
So let's create a file configDB.ini for example and put in db informations
servername = something;
username = something;
password = something;
dbname = something;
Once did it we can create a script called dbconn.php and import the file with credentials ,
in this way there is an abstraction between credentials and connection .
in dbconn.php :
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
We can even improve the code connecting to db only once and use the same connection all the time we need query .
function db_connect() {
// static will not connect more than once
static $conn;
if(!isset($conn)) {
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
return $conn;
}
...
$conn = db_connect();
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = mysqli_query($conn,$sql);
In the end let's say something about mysqli_query
Reasons why you should use MySQLi extension instead of the MySQL extension are many:
from PHP 5.5.0 mysql is deprecated and was introduced mysqli
Why choose mysqli (strenghts)
object oriented
prepared statements
many features
no injection
Do you connect to the database?
The apostrophes around APPUsers and Phone might not be the right ones, as they are not the single apostrophes but some weird squiggly ones.
Try this :
$query = "SELECT * FROM 'APPUsers' WHERE 'Phone' LIKE '".$phone."' ";

mysql_insert_id() suddenly stopped working

Don't know how to say this, but I have used mysql_insert_id() for many many years. Recently I included it in my web applications and worked well, I have successfully received 50 transactions and was happy.
All of a sudden all my transactions are coming in with ids equal 0, I Google'd around and read something about persistent connection being set to true? I just want me to make sure I give the right info to my network server guy, God knows, whenever something changes, they don't let me know, I only find out when my code all of a sudden breaks.
is there another function to use other than mysql_insert_id() in my PHP/MySQL code?
just for those who want to see code here is what i have: I am not including "id" as it is "auto increment not null primary key, etc"
<?php
$db_host2 = 'localhost';
$db_user2 = 'different';
$db_pass2 = 'different';
$db_name2 = 'different';
$conn2 = &NewADOConnection('mysqlt');
$db2 = $conn2->Connect($db_host2,$db_user2,$db_pass2,$db_name2);
if($conn2->isConnected()==false)
die("Could not connect to the database. Please try again in the next few minutes.");
$db_host = 'localhost';
$db_user = 'admin';
$db_pass = 'pass';
$db_name = 'name';
include_once('adodb/adodb.inc.php');
define('ADODB_FETCH_ASSOC',2);
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$conn = NewADOConnection('mysqlt');
$db = $conn->Connect($db_host,$db_user,$db_pass,$db_name);
if($conn->isConnected()==false)
die("Could not connect to the database. Please try again in the next few minutes.");
$q="insert into tableA(name,address,phone) values ('','','')"
$rs=$conn->execute($q);
$myid=mysql_insert_id();
?>
You just need 1 configuration example :
// database config
$DB_TYPE = "mysql";
$DB_HOST = "xxxxx";
$DB_USER = "xxxx";
$DB_PWD = "xxxx";
$DB_NAME = "xxx";
then use last insert ID for :
$db->Insert_ID

Categories