database connection. Misunderstanding of error messages - php

I am receiving these error messages:
Warning: PDO::__construct() expects parameter 4 to be array, string given in C:\wamp\www\MyProjects\GhislainPOO\personnages.php on line 2. There is no password required, I am wondering what it's meant by array here?
Fatal error: Call to a member function query() on a non-object in C:\wamp\www\MyProjects\GhislainPOO\personnages.php on line 3. is $bdd not an object, although I use "new PDO"?
PHP
<?php
$bdd= new PDO ('localhost', 'POO', 'root', '');
$bdd->query( "SELECT * FROM jeux_combats");
$result = $bdd->query( "SELECT * FROM jeux_combats");
while ($donnee = $result->fetch()) {
echo '<p>'.'le personnage'.$donnee['nom'].'a une force de'.$donnee['forceperso'].'</p>';
}
?>

Please read the manual: http://php.net/manual/en/pdo.construct.php
parameter: information about the database connection
parameter: username for the connection
parameter: password for the connection
parameter: a key=>value array of driver-specific connection options (optional)
It should be like this:
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
About your second question. The error should disappear after you will fix your first problem. Anyways... You could check if $bdd is null or not if you fear that the second error could appear again even after you will fix your first problem. Something like:
if($bdd != null){
if($result = $bdd->query( "SELECT * FROM jeux_combats")){
while ($donnee = $result->fetch(PDO::FETCH_ASSOC)) {
echo '<p>'.'le personnage'.$donnee['nom'].'a une force de'.$donnee['forceperso'].'</p>';
}
}
}
The whole code in your case would be:
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$bdd = new PDO($dsn, $user, $password);
if($bdd != null){
if($result = $bdd->query( "SELECT * FROM jeux_combats")){
while ($donnee = $result->fetch(PDO::FETCH_ASSOC)) {
echo '<p>'.'le personnage'.$donnee['nom'].'a une force de'.$donnee['forceperso'].'</p>';
}
}
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

Related

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_

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

PDO MSSQL error query on null

I am trying to select rows from my database table, and I am getting an error stating that
Fatal error: Call to a member function query() on null in..
Our connection to the database shows successful. Below is my php code:
<?php
require_once("dbconn.php");
$db = getConnection();
$input_pid = "870104-07-5448";
$sql = "SELECT * FROM Pat WHERE PID ='$input_pid'";
$stmt = $db->query($sql);
$row = $stmt->fetchObject();
echo $row->PID;
echo $row->Name;
?>
This is the dbconn.php code:
function getConnection(){
try {
$hostname = "busctrlctr-pc";
$dbname = "DispenserSystem";
$username = "sa";
$password = "123456";
$db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
echo 'We are succesful to connect the database !!'.'<br>'; // successful word
} catch (PDOException $e){
echo "connection failed problem is >> ". $e -> getMessage()."\n";
exit;
}
}
Can i know why I am getting this error. Thank you.
You never return $db in your funtion getConnection();
change the funtion to:
function getConnection(){
try {
$hostname = "busctrlctr-pc";
$dbname = "DispenserSystem";
$username = "sa";
$password = "123456";
$db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
echo 'We are succesful to connect the database !!'.'<br>'; // successful word
return $db;
} catch (PDOException $e){
echo "connection failed problem is >> ". $e -> getMessage()."\n";
exit;
}
}

PHP: PDO prepare() causing halt in script

I am working on a simple database helper for part of a test site. I want to be able to access a database by simply doing:
require_once 'include/database_system.php'
...
$row = DB_query("SELECT userID FROM users WHERE username = :username",
array(':username' => $ourUsername));
So I've written up a little script to do so:
<?php
session_start();
$username = "xxxx";
$password = "xxxx";
$host = "localhost";
$dbname = "xxxx";
$dboptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
var_dump($db);
}
catch(PDOException $ex)
{
die("MySQL: Failed to connect to API Testing Database");
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
var_dump($db);
// break magic quotes
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function break_magic_quotes(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
break_magic_quotes($value);
}
else
{
$value = stripslashes($value);
}
}
}
break_magic_quotes($_POST);
break_magic_quotes($_GET);
break_magic_quotes($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
function DB_query($query, $queryArgs)
{
global $db;
echo 'TRYING TO QUERY SERVER ';
var_dump($query);
var_dump($queryArgs);
var_dump($db);
try
{
echo 'PREPARE ';
$stmt = $db->prepare($query);
echo 'EXECUTE ';
$result = $stmt->execute($queryArgs);
}
catch(PDOException $ex)
{
echo "QUERY FAILED: $query";
die("Query failed: " . $query);
return;
}
echo 'SERVER QUERY OK';
return $stmt->fetch();
}
So naturally, I'm working on a bit of form action code for the login page, by doing:
require_once 'database.php'
....
$row = DB_query("SELECT * FROM users WHERE username = :username",
array(':username' => $_POST['u']) );
The output is not very conclusive at all. Not only does it fail to get past the $db->prepare() statement, but it doesn't even look like the PDO is valid.
object(PDO)#1 (0) { } object(PDO)#1 (0) { } TRYING TO LOGINobject(PDO)#1 (0) { } TRYING TO QUERY SERVER string(46) "SELECT * FROM users WHERE username = :username" array(1) { [":username"]=> string(4) "derp" } NULL PREPARE
I don't know why it would be doing any of this. I have checked the PHP settings and it looks like PDO is properly turned on. I have checked everything up and down and I haven't been able to get anywhere. If anyone has any insight, that would be great.

Invalid Data Source PHP PDO Mysql

<?php
#require_once('inc/dbc1.php');
$dsn = 'mysql:dbname=dbname;host=somehost;
$user = 'someuser';
$password = 'SomePass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$pdo1 = new PDO($dsn, $user, $password);
$pdo1->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth1 = $pdo1->prepare('SELECT pID, lname, fname FROM Professor ORDER BY pID DESC LIMIT 5;');
$sth1->execute(array());
?>
Throws the error:
Uncaught exception 'PDOException' with message 'invalid data source name' in PDO->__construct('', NULL, NULL) on line 1
Anyone see anything wrong with this?
you have
$dsn = 'mysql:dbname=dbname;host=somehost;
maybe just maybe ...
$dsn = 'mysql:dbname=dbname;host=somehost';
unless this was a mouso when cut-and-pasting the question.

Categories