MySql database connection compress - php

How do i compress these two following database connection codes into one code?
Code1
<?Php
define($base_url = 'http://example.com/url/'); // Change this to your site URL and Path
define($from_email = 'example#email.com'); // Change this email id to your id
///////// Database Details change here ////
define($dbhost_name = 'mysql.host.com');
define($database = 'databasename123');
define($username = 'username123');
define($password = 'password123');
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Code2
<?php
define('DB_HOST', 'mysql.host.com');
define('DB_NAME', 'databasename123');
define('DB_USER','username123');
define('DB_PASSWORD','password123');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die(header('Location: ./admin/install.php'));
$db=mysql_select_db(DB_NAME,$con) or die(header('Location: ./admin/install.php'));
?>
If there is no possibilities, what is the best way to solve this problem?
Thank you on beforehand

One of your snippets uses PDO and the other uses mysql_connect. Combining them completely is non-trivial, however you could put your database host, name, username and password as variables in another file and then include that file in both the bits of code you have provided. That would at least mean you could update all the database details in one place.

Related

Using php I need to have 2 different connections to the database

I have a need to copy some rows from a database to a different database. I am experiencing difficulty. I have found several methods except none of the seem to work. The php version I am using is 5.4.
Both connections are in the same server, however everything else is different
This is the php code that I have found and it doesnt seem to work at all, I am unable to select from the first database
// Create connection
$wpdb = mysql_connect($servername, $username, $password);
// Check connection
if ($wpdb->connect_error) {
die("Connection failed: " . $wpdb->connect_error);
}
echo "Connected local successfully\n";
//$starttime = date("h:i:sa");
$mydb = mysql_connect('localhost','dbname','dbpassword', true);
// Check connection
if ($mydb->connect_error) {
die("Connection failed: " . $mydb->connect_error);
}
echo "Connected to Integrity successfully\n";
mysql_select_db($database, $wpdb);
mysql_select_db('wordpress_0', $mydb);
you can try with PDO.that provide a common interface to talk with many different databases.
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user',
'password');
I refuse to offer support for mysql_ syntax, so I'll offer the upgraded version.
Almost entirely copied from the php manual... http://php.net/manual/en/mysqli.select-db.php
Code:
/* attempt and check connection including first database selection "test" */
if (!$mysqli = new mysqli("localhost", "root", "", "test")) {
// never show the actual error to the public
echo "<div>Database Connection Error: " , $conn->connect_error , "</div>";
exit();
}
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
/* change db to "mysql" db */
$mysqli->select_db("mysql");
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
$mysqli->close();
Output:
Default database is: test
Default database is: mysql

php - blank page when using code to connect to data base

i get a blank page when using code to connect to a database using php
even any print statement out side of the connection code is not printed only a blank page when running the following code
<?php
$link = new mysqli('localhost', 'root', '7610', 'sites');
if ($link) {
print "connected";
}
else { print "faild";}
?>
Try to use mysqli_connect() instead of mysqli()
Most People agree that PDO offers so much advantages over mysqli functions.... Why not try that Route? You would be glad you did... Here's what a PDO-based version would look like....
<?php
//DATABASE CONNECTION CONFIGURATION:
defined("HOST") or define("HOST", "localhost"); //REPLACE WITH YOUR DB-HOST
defined("DBASE") or define("DBASE", "sites"); //REPLACE WITH YOUR DB NAME
defined("USER") or define("USER", "root"); //REPLACE WITH YOUR DB-USER
defined("PASS") or define("PASS", "7610"); //REPLACE WITH YOUR DB-PASS
try {
$dbh = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
}
if($dbh instanceof PDO){
print "The Coast is clear...";
}else{
print "We have a Huge Storm on our hands.... BAIL ;-)";
}
// FROM HERE ON, YOU COULD START USING $dbh AS YOUR PDO OBJECT...
// FOR EXAMPLE YOU COULD DO A SELECT LIKE SO:
$sql = 'SELECT u.* FROM user AS u';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
var_dump($result);

Can't Link To MySQL database

I am learning MySQL/PHP and I cannot figure out how to connect to MySQL on my localhost. I have written a short bit of code and I included root as my user name and root as my password because I have not set these elements yet (as far as I know). I feel that perhaps I am missing something in regards to the username/password combination. However, I feel that this should not be an issue because I have not tampered with the default conditions.
I need some help.
My code is below:
<?php
try {
$db = new PDO("mysql:host=localhost;dbname=shirts4max;port=3306", "root", "root");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf-8'");
} catch (Exception $e) {
echo "Could not connect to the database.";var_dump($e);
exit;
}
I am only seeing the error message on my page:
"Could not connect to the database."
Thank for reading. Please help me Obiwan.
Show the real error. Avoid using root except for maintenance.
From the PDO Manual page here, modified for you
<?php
$dsn = 'mysql:dbname=shirts4max;host=localhost';
$user = 'root';
$password = 'root';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Have you tried connecting via command line using: mysql -uroot -proot -hlocalhost -p3306? If you can't connect that way, the PDO connection won't go through either. Playing with the connection info via command line gives you a nice easy way to find what works, then include it in your code. Also, if you've not set the user/pw, it's possible there isn't one currently, so you wouldn't need those parameters at all.

Can't connect to database through PHP PDO class

I'm trying to connect to my mySQL database using the PDO class in PHP.
Here is my Code :
// Connects to Our Database via PDO.
if($local) {
try {
$db = new PDO("mysql:=localhost;dbname=bbc_archive;port=3306", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo "Connection to the DataBase was not possible. ";
die();
}
} else {
try {
$db = new PDO("mysql:=bbcarchive.db.11505263.hostedresource.com;dbname=bbcarchive", "bbcarchive", "myPassword");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo "Connection to the live DataBase was not possible. ";
die();
}
}
The $local variable is defined before and determines whether or not the script is running on a the live server or a test server.
When running in my local environment everthing works fine but on my live server it echo's out "Connection to the live DataBase was not possible." from the catch block.
I've contacted my host provider (godaddy) and they think it's a coding error. I've also, obviously, checked the hostname, dbname, username and password a 100 times and it's all correct. I just can't see the problem!
How can i do this ?
Your DSN seems to be incorrect. The documentation on MySQL DSNs indicates that it should look somewhat like this:
$db = new PDO("mysql:host=localhost;dbname=bbc_archive;port=3306", "root", "");

Check MySql credentials before creating tables

I am creating an install php script that creates some tables in a database and creates a config file. Everything works but I don't know how to check if their host, username and password are correct. I currently check if the database is there or not.. any help would be appreciated. This is on a WAMP server using PHP 5.4.12. The variables come from a basic form.
session_start();
$_SESSION['dbdatabase'] = $_POST['dbdatabase'];
$_SESSION['dbhost'] = $_POST['dbhost'];
$_SESSION['dbusername'] = $_POST['dbusername'];
$_SESSION['dbpassword'] = $_POST['dbpassword'];
$conn=mysqli_connect($_SESSION['dbhost'],$_SESSION['dbusername'],$_SESSION['dbpassword']);
if(!mysqli_select_db($conn, $_SESSION['dbdatabase']))
{
die ('Database does not exists. Please create a database before installing Pazzilla BackOffice.');
}
else
{
The function you are looking for is mysqli_connect_error().
<?php
$link = mysqli_connect('localhost', 'invalid_user', 'password');
if (!$link) {
die('Invalid database credentials. Mysql said: ' . mysqli_connect_error());
}
?>

Categories