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);
Related
I am trying to retrieve data from my database using PDO Fetch object and it says
Fatal error: Uncaught Error: Call to undefined method mysqli_result::execute()
what I'm doing wrong
This is what I have tried
<?php
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "messages_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$getquery = $conn->query('select col_name from db where id = 2');
$getquery->execute();
$result = $getquery->fetch(PDO::FETCH_OBJ);
?>
<div><?= $result->col_name; ?></div>
Firstly, don't mix PDO and mysqli. Stick to one. Here's a PDO example. You first need to create a new PDO object. and connect to DB at the start
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "dbname";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername,
$dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
$rtrv = "select col_name from db where id = 2"
$stmt = $pdo->prepare($rtrv);
//Execute.
$stmt->execute();
//Fetch.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// Do whatever you want after this
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 could not insert values in table (MSSQL) by using pdo php. I got message that connection is established but query does not work. I have never used MSSQL server I am not sure is this query good.
$database = "db";
$server = "xxx\SQLEXPRESS";
$conn = array( "Database"=>"db", "UID"=>"user", "PWD"=>"xxx" , "CharacterSet" => "UTF-8");
if( $conn ) {
echo "connection established";
}else{
echo "Connection could not be established.";
die( print_r( sqlsrv_errors(), true));
}
// insert values into table,
// variables are defined above didnt write them here
$query = $conn->prepare("INSERT INTO dbo.FKNarudzbaKupacaStavke(IdFirma, VrstaDokumenta, BrojDokumenta, BrojDokumentaKroz,
DatumDokumenta, IdKupac, VrstaCijene, NacinPlacanja, DatumZadnjeAkcije, Status, StatusArhive, StatusIzmjene,
StatusStampe, VrstaFakture) VALUES(:IdFirma, :VrstaDokumenta, :BrojDokumenta, :BrojDokumentaKroz, :DatumDokumenta, :IdKupac, :VrstaCijene, :NacinPlacanja,
:DatumZadnjeAkcije, :Status, :StatusArhive, :StatusIzmjene, :StatusStampe, :VrstaFakture)");
$query->bindParam(':IdFirma',$IdFirma);
$query->bindParam(':VrstaDokumenta',$VrstaDokumenta);
$query->bindParam(':BrojDokumenta',$BrojDokumenta);
$query->bindParam(':BrojDokumentaKroz',$BrojDokumentaKroz);
$query->bindParam(':DatumDokumenta',$DatumDokumenta);
$query->bindParam(':IdKupac',$IdKupac);
$query->bindParam(':VrstaCijene',$VrstaCijene);
$query->bindParam(':NacinPlacanja',$NacinPlacanja);
$query->bindParam(':DatumZadnjeAkcije',$DatumZadnjeAkcije);
$query->bindParam(':Status',$Status);
$query->bindParam(':StatusArhive',$StatusArhive);
$query->bindParam(':StatusIzmjene',$StatusIzmjene);
$query->bindParam(':StatusStampe',$StatusStampe);
$query->bindParam(':VrstaFakture',$VrstaFakture);
$query->execute();
I got this error :
Fatal error: Call to a member function prepare() on a non-object..
Any help or advice is appreciated!
The way you've written it, $conn isn't a connection, it's just an array.
Try this to connect to the database:
$hostname = 'xxx\SQLEXPRESS';
$username = 'user';
$password = 'xxx';
$dbname = 'db';
$conntype = 'mysql'; //or dblib or mssql
try {
$conn = new PDO("$conntype:host=$hostname;dbname=$dbname", $username, $password);
}
catch( PDOException $e ) {
echo( $e->getMessage() );
}
You are actually not establishing the connection there, please change your $conn variable as show below
$conn = new PDO("mssql:host=".$server.";dbname=db", "user", "xxx");
I am VERY new to PHP / PDO, so please be gentle...
I am trying to enter code into my database and then fetch it into a webpage. I am able to do the first but am having difficulty displaying it. I am wondering if it's because i'm trying to combine $stmt and $handler together?
This is my code for entering the information into the database:
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);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO survey (storename, receipt, date_visit)
VALUES (:storename, :receipt, :date_visit)");
$stmt->bindParam(':storename', $storename);
$stmt->bindParam(':receipt', $receipt);
$stmt->bindParam(':date_visit', $date_visit);
// insert a row
$storename = $_POST['storename'];
$receipt = $_POST['receipt'];
$date_visit = $_POST['date_visit'];
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
It works perfectly.
This is my code for fetching information from my database.
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
$handler->setAttribute(PDO::ATRR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
class SurveyEntry {
public $id, $storename, $receipt, $date_visited,
$entry;
public function __construct() {
$this->entry = "{$this->storename} posted: {$this->receipt}";
}
}
$query = $handler->query('SELECT * FROM survey');
$query->setFetchMode(PDO::FETCH_CLASS, 'SurveyEntry');
while($r = $query->fetch()) {
echo $r->entry, '<br>';
}
?>
I can confirm that it connects correctly, but I can't get it to display any information. I'm wondering if it's something to do with the difference in $stmt and $handler that i'm using? I've been following tutorials online and have quite possibly mixed 2 tutorials together to try and achieve what i'm looking for.
UPDATE:
I managed to get it to work by updating how I called from the database:
$host = "localhost";
$dbname = "test";
$user = "test";
$password = "test";
$handler = new PDO( "mysql:dbname=$dbname;host=$host" , $user , $password );
Figured it out - I had 'ATRR_ERRMODE' instead of 'ATTR_ERRMODE' (typo)
how are you?
You should try to fix it:
1- Two different connections:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
<?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.