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");
Related
I want to insert 2 tables columns ids to another table
I got the query but there is the annoying error.
I tried to solve this problem for hours none worked :(
This code:
$query = "INSERT INTO
groups(
group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count
)
VALUES(
$group_shcool_id,
$group_teacher_id,
'$group_name',
'$group_note',
'$group_system',
'$group_students_count'
)";
this old:
<?php
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
mysqli_query($con, "SET NAMES 'utf8'");
}
?>
this new:
<?php
// if you are using php just don't forget to add php tags though
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
//using try catch statements
try{
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
?>
its connects successfully but all my code use the old one, how to change to convert it? I dont know what pdo I like to learn it, it seems more pro type, but is there solution for this site only using mysqli?
sorry for the long post this is my 1st one, dont know how to explain enough
Thanks
give this error :
QUERY FAILED .You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , 'test', '', 'test' at line 11
I thought it will work fine like this but I think the problem with the query syntax.
Just an advice try to use PDO prepared statements example below:
$query = "INSERT INTO groups(group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count)
VALUES (:gsid,:gtid,:gname,:gnote,:gsystem,:gstudcount)";
//assuming $conn is your object variable name for database connection
$stmnt = $conn->prepare($query);
$stmnt->execute(array(':gsid'=>$group_school_id,
':gtid'=>$group_teacher_id,
':gname'=>$group_name,
':gnote'=>$group_note,
':gsystem'=>$group_system,
':gstudcount'=>$group_students_count));
//to check if you have inserted data into your table
$rows = $stmnt->rowCount();
echo "Inserted ".$rows." row";
the :gsid are placeholders for your variables, also make sure that each variable passed are inline with column datatypes in your database
//if you are using php just don't forget to add php tags though
$dbhost = "localhost";
$dbname = "whatevername";
$dbuser = "root";
$dbpass = "";
//using try catch statements
try{
$conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
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);
Hi I am attempting to execute a stored procedure in my sqlserver database through php. I have the following code that has worked before when executing stored procedures. This time however the stored procedure includes parameters which I am having difficult time declaring. The two paramaters are TODATE and FROMDT, which are coming from date input boxes on a previous page.
enter <?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "";
$userName = "";
$userPassword = '';
$dbName = "ENERGY";
$connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$FROMDT = 'POST_["FROMDT"]';
$TODATE = 'POST_["TODATE"]';
$params = array($FROMDT, $TODATE);
$sql = "ENERGY.dbo.P_KPI_DAILY_D $FROMDT $TODATE" ;
You aren't getting the post data correctly.
Change
$FROMDT = 'POST_["FROMDT"]';
To:
$FROMDT = '';
if(isset($_POST['FROMDT'])){
$FROMDT = $_POST['FROMDT'];
}
if($FROMDT == ''){
// error handling
}
Also ensure you have the correct permissions write/execute the proc for the MSSQL user.
You could clean up your code a bit too. the below is extracted from a 'DataHandler' I built to automate binding parameters and allow for analytics.
<?php
define( "CONN_STRING", "sqlsrv:server=".DB_SERVER."; Database =".DB_NAME);
try{
$this->conn = new PDO($sConnString, $sDB_USER, $sDB_PASSWORD);
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'Connection failed: <bR>'; //.$e->getMessage();
exit;
}
$st = $conn->prepare( $sSQL );
$this->st->bindValue( $sParamName, $_POST['ParmName'], PDO::PARAM_INT );
$this->st->execute();
?>
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);