Failing testing database connection in php - php

I've set up a database using MAMP.
When I try the following test, I only receive a blank page. Fairly new to this, and I've tried different suggestions found on the web with no luck.
Tried using both port and socket.
<?php
$user = 'root';
$password = 'root';
$db = 'test';
$host = 'localhost';
$port = 3306;
$socket = "/Applications/MAMP/tmp/mysql/mysql.sock";
$link = mysql_connect(
"$host:$socket",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
if (!$link){
echo "ERROR";
}
else {
echo "Success";
}
mysql_close($link);
?>

<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Would you like to try PDO ?!
<?php
$dsn = "mysql:host=localhost;dbname=databasenamehere";
$user = 'root';
$pass = '';
$option = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connect = new PDO($dsn, $user, $pass,$option);
$connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $r) {
echo 'Failed' . $r->getMessage();
}

Related

Combining connect data into one file

I have a PHP file that I use to include when I connect to my db. It looks something like this:
<?php
$mysqlhst = "localhost";
$database = "mydb1";
$username = "my_usr";
$password = "mypas2db1";
try {
$db = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
I also have a second database that I frequently access at the same time as the first one. Can I combine both connections like this or is there a better way of doing it?
<?php
$mysqlhst = "localhost";
$database = "mydb1";
$username = "my_usr1";
$password = "mypas2db1";
try {
$db = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$database = "mydb2";
$username = "my_usr2";
$password = "mypas2db2";
try {
$db2 = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Assuming you're not using Classes, you could DRY (Do-not Repeat Yourself) up your code a little like the following. This allows for extending into even further databases/users/servers in the future if required:
<?php
$connections = [
'db1' => [
'host' = 'localhost';
'database' = 'mydb1';
'username' = 'my_usr1';
'password' = 'mypas2db1';
],
'db2' => [
'host' = 'localhost';
'database' = 'mydb2';
'username' = 'my_usr2';
'password' = 'mypas2db2';
],
];
function getDatabaseConnection($connectionName = 'db1'): ?PDO
{
global $connections;
if (empty($connections[$connectionName]) {
// Throw an exception because this connection doesn't exist.
throw new \Exception(
"Connection: {$connectionName} not specified."
);
}
$data = $connections[$connectionName];
$dbHost = $data['host'] ?: 'localhost';
$dbUsername = $data['username'] ?: '';
$dbPassword = $data['password'] ?: '';
$dbName = $data['database'] ?: '';
if (!$dbUsername || !$dbName) {
// We don't have a username or database to connect to. Fail.
throw new \Exception(
'No valid database name or user provided.'
);
}
$db = new PDO(
"mysql:host={$dbHost};dbname={$dbName};charset=UTF8",
$dbUsername,
$dbPassword
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
// We don't need to specify a connection because we want the default, db1.
$db1 = getDatabaseConnection();
// Specify we want a connection to db2.
$db2 = getDatabaseConnection('db2');

can't connect to database with php (mysql) [duplicate]

If I want to put the connection in an external file, what part of this code should be in that external file?
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
This part will go in external file e.g connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and then your code will look like
require("connection.php");
try {
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Till this part can go to external file, and can be used to open a connection where ever required.

Setting a mysql table in a variable

Okay so I'm using this code to store tables in a variable:
<?php
$host = "localhost";
$user = "x";
$password = "x";
try {
$account = new PDO("mysql:host=$host;dbname=account", $user, $password);
} catch(PDOException $e) {
die('connection cant be made');
}
try {
$player = new PDO("mysql:host=$host;dbname=player", $user, $password);
} catch(PDOException $e) {
die('connection cant be made');
}
and everything I do I get "connection can't be made". So I found another code and I switched to it and everything works.
<?php
$host = "localhost"; // Ip-ul de la server
$user= "xx"; // User-ul de conectare la database
$password = "xx"; // Parola de conectare la database
mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db('account');
mysql_set_charset('utf8');
?>
but now I have no db assigned to $account and $player and I can't use my site properly. Ideas?
In $e you have reason why you can't connect to database. Catch exception and do nothing with it...
<?php
define('__DEBUG', true);
try {
$account = new PDO("mysql:host=$host;dbname=account", $user, $password);
} catch(PDOException $e) {
if(__DEBUG) {
print $e->getMessage();
}
die('connection cant be made');
}
for use 2 connections in (not so^) old way style:
$con1 = mysqli_connect();
$con2 = mysqli_connect();
mysqli_query('query', $con1);
mysqli_query('query', $con2);
^ use mysqli_ instead mysql_

How to connect MySQL db using new XAMPP

Old connection method mysql_connect maybe deprecated from PHP7 so what is the best way to connect and query in mysql using XAMPP or how I implement PDO in my bellow script.
<?php
$key = $_GET['key'];
$array = array();
$con = mysql_connect("localhost", "root", "");
$db = mysql_select_db("search", $con);
$query = mysql_query("select * from ajax_example where name LIKE '%{$key}%'");
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row['name'];
}
echo json_encode($array);
?>
Database connection using mysqli_* :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
For further mysqli_* statement syntax refer: Mysqli_* Manual
Database connection using PDO_* :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
For further PDO_* statement syntax refer PDO_* Manual
$conn = new Connection();
$query = "select * from ajax_example where name LIKE '%{$key}%'";
$res = $conn->execute_query($query)->fetchall(PDO::FETCH_ASSOC);
if (!empty($res))
{
$result['data'] = $res;
echo json_encode($result);
}

PDO. How to put the connection in an external file

If I want to put the connection in an external file, what part of this code should be in that external file?
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
This part will go in external file e.g connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and then your code will look like
require("connection.php");
try {
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Till this part can go to external file, and can be used to open a connection where ever required.

Categories