<?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.
Related
Im trying to connect php to SQL server driver using below:
It works fine for MYSQL., but not for SQL Server.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$data = json_decode(file_get_contents('php://input'), true);
if(!empty($data)):
header('Content-Type:text/plain');
$hostname = '10.8.8.9';
$username = 'siddharth';
$password = '1234';
$dbname = 'AirportFootfall';
$mssqldriver = '{SQL Server}';
//$dbh = new PDO("mssql:host=$hostname;dbname=AirportFootfall", $username, $password);
//$dbh = new PDO("sqlsrv:Server=10.16.34.90;Database=AirportFootfall", $username, $password);
//$dbh = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=AirportFootfall", $username, $password);
//$dbh = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=AirportFootfall", $username, $password);
//$dbh = new PDO("dblib:host=$hostname;dbname=AirportFootfall", $username, $password);
//$dbh = new PDO("dblib:host=$hostname;dbname=$dbname", $username, $password);
$dbh = new PDO("dblib:host=$hostname;dbname=$dbname", $username, $password);
$arraykey=array_keys($data);
$array=$data[$arraykey[0]];
try
{
$count = $dbh->exec('INSERT INTO RadioCon_Sensor_Raw_Data(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES ("' . implode('", "', $array) . '")' ) or die(print_r($dbh->errorInfo(), true));
//echo $count;
$dbh = null;
echo 'Data Successfully inserted!!<br />';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
endif;
?>
UPDATE: Have insatalled the pdo_dblib extension.
Im getting
Fatal error: Uncaught exception 'PDOException' with message 'could not find driver' in /var/www/html/RADIOLOCOUS/GMR/gmrsample_copy.php:14 Stack trace: #0 PDO->__construct('odbc:Driver={SQ...', 'siddharth', '1234') #1 {main} thrown in ....line 14
Any alternate way to connect apart from pdo
Im using Ubuntu 14.04 LAMP with php 5.5
My php_info says:
PDO drivers dblib, mysql
The documentation for PDO_DBLIB shows the following DSNs:
mssql:host=localhost;dbname=testdb
dblib:host=localhost;dbname=testdb
So I'd like to suggest this:
$dbh = new PDO("dblib:host=$hostname:1433;dbname=AirportFootfall", $username, $password);
You can test your connection this way:
<?php
header('Content-Type:text/plain');
$hostname = '10.8.8.9';
$username = 'siddharth';
$password = '1234';
$dbname = 'AirportFootfall';
try {
$dbh = new PDO("dblib:host=$hostname:1433;dbname=$dbname", $username, $password);
$sql = "SELECT 'It is working' AS name";
foreach ($dbh->query($sql) as $row) {
print $row['name'] . "\n";
}
} catch (PDOException $ex) {
print $ex->getMessage();
}
?>
It looks like the $mssqldriver var is commented... Did you try to uncomment?? If you look carefully the Connection statement use that var:
$dbh = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=AirportFootfall", $username, $password);
I gotten this error
Database Connected successfully Fatal error: Call to a member function prepare() on a non-object in D:\home\site\wwwroot\DatabaseMethods.php on line 22
I can't seem to find what is causing this any one could point out whats wrong please enlighten me.
I have tried to call the connection before running the prepared statement but cant seems to work or what should i do
Thanks in advance
DatabaseMethods.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("DatabaseConnection.php");
date_default_timezone_set("Asia/Singapore");
//Register
function RegisterUser($email , $password)
{
$conn = connect_db();
$stmt = null;
$stmt = $conn->prepare("INSERT INTO secure_login (email,password,created_dt) VALUES(?,?,?)"); //ERROR LINE
$stmt->execute(array($email, $password , date("Y-m-d h:i:s")));
if( $stmt )
{
return "success";
}
else
{
return "Failed";
}
}
//date("Y-m-d h:i:s")
//End Register
?>
DatabaseConnection.php
<?php
function connect_db()
{
$servername = "xxxx";
$username = "xxx";
$password = "xxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=xxx", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>
Answer
<?php
function connect_db()
{
$servername = "xxx";
$username = "xxx";
$password = "xxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=xxx", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database Connected successfully";
return $conn;
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>
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();
}
I know that error occurs usually when query returned false but this time this occurs with no reason! (or just I'm making a big mistake)
if(!$security_SenderId){
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?'");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
}else{
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?' AND `ticket_sender` = '?'");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
}
if($getbaseticket === false){
return false;
}else{
$baseticket = $getbaseticket->fetch(PDO::FETCH_ASSOC);
}
I've theese lines in a function that returns support ticket information as array but as I said the error occurs when I tried to fetch the ticket information. I tried to check mysql errors just before fetch line by enabling the pdo debug mode and db->errorInfo() but it didn't work.
What can the problem be here?
Edit:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
class TICKET_MANAGER
{
function __construct($dbhost, $dbname, $dbuser, $dbpass) {
try{
$this->db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Connection failed: ' . $e->getMessage() );
}
}
function viewTicket($ticket_safeid, $security_SenderId = false)
{
try{
if(!$security_SenderId){
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ?");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
}else{
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ? AND `ticket_sender` = ?");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
}
}catch(PDOException $e){
die('Mysql error: ' . $e->getMessage() );
}
...
}
...
}
It's the quotes around all your '?' - Remove them.
Read the manual
http://php.net/pdo.prepared-statements
from the manual:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
Exceptions should have told you that error
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
and used right after you've connected to your DB.
-http://php.net/manual/en/pdo.error-handling.php
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Query:
try {
// your query
}
catch(PDOException $e){
print $e->getMessage();
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
I'm a newbie to php pdo. Here i'm trying to fetch my database records from database using prepared statements. But it didn't fetch the records. I'm getting this following error
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
why i'm getting this error? why it didn't fetch the records from database?
<?php
$user = "root";
$password = "password";
try {
$conn = new PDO('mysql:host=localhost;database=evouchers', $user, $password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo 'DATABASE ERROR : ' . $e->getMessage();
}
$sql = "SELECT UserName FROM ebusers ORDER BY UserName";
$db = $conn->query($sql);
$db->setFetchMode(PDO::FETCH_ASSOC);
while($row = $db->fetch())
{
print_r($row);
}
?>
in your db connection string instead of database use dbname
$conn = new PDO('mysql:host=localhost;database=evouchers', $user, $password);
---------------------------------------^
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);
Docs link: http://php.net/manual/en/pdo.connections.php
I think it should be
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);
Alternatively try just after you init PDO
$conn->exec('USE evouchers;');
use the following line for pdo connection
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);