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);
Related
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);
}
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 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 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;
}
}
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);