Setting a mysql table in a variable - php

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_

Related

database connect issues

Hello could anyone help me please with db connection, im using xampp, phpmyadmin, when i open the browser, DBConnection.class.php it shows blank and db doesnt work, thanks
<?php
class DBConnection{
public static function DbConn(){
$servername = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
try{
$conn = new PDO($servername, $username, $password);
return $conn;
echo"Connection succesful :)";
}
catch (PDOException $e) {
echo "Connection failed :( :" . $e->getMessage();
}
}
}
?>
Modified Code. Try this:
class DBConnection{
public static function DbConn(){
$servername = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
try{
$conn = new PDO($servername, $username, $password);
return "Connection succesfull :)";
//return $conn;
}
catch (PDOException $e) {
echo "Connection failed :( :" . $e->getMessage();
}
}
}
and then call like this
$Connection = new DBConnection();
print_r($Connection->DbConn());

Failing testing database connection in 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();
}

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 object cant acess inside function

In my project i had a file called connection.inc.php which is managing the data base connection using PDO.
include/connection.inc.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
i included this file in various other pages and it worked perfectly for me. But when i tried to acess the $conn object inside a function it not working. How to fix this problem.
You could do global $conn on top of your functions, but don't. I suggest wrapping it in a singleton instead.
<?php
class Connection {
private static $conn = null;
private $connection = null;
private function __construct() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage(); // Should look into a different error handling mechanism
}
}
public static function getConnection() {
if (self::$conn === null) {
self::$conn = new self();
}
return self::$conn->connection;
}
}
You can access it via Connection::getConnection()
This also has the advantage of not initializing the connection if the current request doesn't need to use it.
Honestly the simplest method is to set the connection inside of a function then you can use that function in other functions.
Example:
error_reporting(E_ALL);
ini_set('display_errors', 1);
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host='.DB_HOSTNAME.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step to close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
How To Use In Another Function:
function doSomething() {
$query = 'SELECT * FROM `table`';
$params = array();
$results = dataQuery($query,$params);
return $results[0]['something'];
}
You need to update your file as
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
//// define global variable
global $connection
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
/// assign the global variable value
$connection = $conn ;
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
Now you can call it any of your function like
function mytest(){
global $connection;
}
The best practice would be to pass the $conn as argument to the function.
But if you really need the function to have no arguments but still use a global variable, then adding this line in your function before using the variable should do the trick:
global $conn; // I want to use the global variable called $conn

Unable to connect to database?

This PHP is not working for me, it will not connect
Here is my code
<?php
$server = "localhost";
$database = "induadmi_db";
$username = "induadmi_main";
$password = "password";
$mysqlConnection = mysql_connect($server, $username, $password);
if (!$mysqlConnection)
{
echo "Please try later.";
}
else
{
mysql_select_db($database, $mysqlConnection);
}
?>
try this style:sample one and refer this following link
http://php.net/manual/en/function.mysql-connect.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Works fine on my end with my own connection parameters..
You need to change this block to see the exact error...
if (!$mysqlConnection)
{
die(mysql_error());
}
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
So nuff said..
Switch to PDO..
<?php
$dsn = 'mysql:dbname=induadmi_db;host=localhost';
$database = "induadmi_db";
$username = "induadmi_main";
$password = "password";
try
{
$dbh = new PDO($dsn, $username, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}

Categories