stored procedure parameters in php - php

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();
?>

Related

PHP7.3 SQLSRV - Format of DateTime different when Query and Store

We have to upgrade our system to use PHP7.3 (change from MSSQL to SQLSRV DB Driver and SQLSRV with PDO)
My problem is, that i dont understand this behavior and how to solve it properly.
When i query a DateTime column from Database i get:
2019-03-26 00:00:00.000
When i try to store the same value into a DateTime column into the database it doesn't work. My Database accept this format for example:
26-03-2019 00:00:00.000
for that reason our existing database layer is not working properly.
i need help to understand this behavior, and how to tell the database to use the same format for Query and INSERT/UPDATE
The Querys we used have no special conversions, Simple SELECT / UPDATE / INSERT.
PHP Version:
PHP 7.3.3-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Mar 7 2019 20:31:49) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.3, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.3-1+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
SQLServer:
MSSQL Server 2014
thx for any hint
1. How to retrieve Date and Time values from SQL Server:
1.1. Retrieve Date and Time values from SQL Server uisng the PDO_SQLSRV version of PHP Driver for SQL Server:
When you use PDO_SQLSRV driver, values from date and time columns are returned as strings before version 5.6.0 of the driver. In this case the only option is to reformat date and time values (from '2019-03-26 00:00:00.000' to '26-03-2019 00:00:00.000' for example). Starting with version 5.6.0, you can change this behavior using PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE connection or statement attribute and retrieve date and time field values as PHP DateTime variable. Then you can easily format this variable as string using DateTime::format.
<?php
// Connection
$server = "server\instanse";
$database = "database";
$username = "username";
$password = "password";
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_SYSTEM);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
// Datetime values as PHP DateTime object
try {
$query = "SELECT GETDATE() AS DateTimeColumn";
$stmt = $conn->prepare($query);
$stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, true);
$stmt->execute();
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["DateTimeColumn"]->format('Y-m-d H:i:s.v') . "<br>";
}
$stmt = null;
// Datetime values as text
try {
$query = "SELECT GETDATE() AS DateTimeColumn";
$stmt = $conn->prepare($query);
$stmt->setAttribute(PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE, false);
$stmt->execute();
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["DateTimeColumn"] . "<br>";
}
$stmt = null;
// End
$conn = null;
?>
1.2. Retrieve Date and Time values of output parameters from SQL Server stored procedure uisng the PDO_SQLSRV version of PHP Driver for SQL Server:
A note from the documentation explains, that PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE connection or statement attribute only applies to regular fetching of date and time types because DateTime objects cannot be specified as output parameters. In this situation, the only possible option is to pass the datetime output parameter of the stored procedure as a PHP string variable. The return value depends on the language environment for the session.
Stored procedure:
CREATE PROCEDURE spReturnDateTime
#datetime datetime OUTPUT
AS
BEGIN
SET NOCOUNT ON
SELECT GETDATE() AS [DateTime]
SET #datetime = GETDATE()
END
PHP:
<?php
// Connnection
$server = "server\instanse";
$database = "database";
$username = "username";
$password = "password";
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_SYSTEM);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
// Output parameters from stored procedure
try {
//
$sql = "
SET LANGUAGE 'English'
EXEC :errcode = spReturnDateTime #datetime = :datetime
";
$errcode = 0;
$datetime = "";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':errcode', $errcode, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->bindParam(':datetime', $datetime, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 50);
$stmt->execute();
do {
while ($row = $stmt->fetch( PDO::FETCH_ASSOC) ){
echo $row["DateTime"]."<br>";
}
} while ($stmt->nextRowset());
$stmt = null;
echo $datetime."<br>";
//
$sql = "
SET LANGUAGE 'Bulgarian'
EXEC :errcode = spReturnDateTime #datetime = :datetime
";
$errcode = 0;
$datetime = "";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':errcode', $errcode, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->bindParam(':datetime', $datetime, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 50);
$stmt->execute();
do {
while ($row = $stmt->fetch( PDO::FETCH_ASSOC) ){
echo $row["DateTime"]."<br>";
}
} while ($stmt->nextRowset());
$stmt = null;
echo $datetime."<br>";
} catch (PDOException $e) {
die ("Error executing query. ".$e->getMessage());
}
// End
$conn = null;
?>
Results:
2021-06-10 10:05:54.580
Jun 10 2021 10:05AM
2021-06-10 10:05:54.580
юни 10 2021 10:05AM
1.3. Retrieve Date and Time values from SQL Server uisng the SQLSRV version of PHP Driver for SQL Server:
By default smalldatetime, datetime, date, time, datetime2, and datetimeoffset types will be returned as PHP DateTime objects, but this behaviour can be changed by setting the 'ReturnDatesAsStrings' option in the connection string or at the statement level:
<?php
// Connection
$server = "server\instanse";
$database = "database";
$username = "username";
$password = "password";
$cinfo = array(
"Database" => $database,
"UID" => $username,
"PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
// Datetime values as PHP DateTime object
$query = "SELECT GETDATE() AS DateTimeColumn";
$options = array('ReturnDatesAsStrings' => false);
$stmt = sqlsrv_query($conn, $query, null, $options);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row["DateTimeColumn"]->format('Y-m-d H:i:s.v') . "<br>";
}
sqlsrv_free_stmt($stmt);
// Datetime values as text
$query = "SELECT GETDATE() AS DateTimeColumn";
$options = array('ReturnDatesAsStrings' => true);
$stmt = sqlsrv_query($conn, $query, null, $options);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row["DateTimeColumn"] . "<br>";
}
sqlsrv_free_stmt($stmt);
// End
sqlsrv_close($conn);
?>
1.4. Retrieve Date and Time values from SQL Server uisng MSSQL PHP extension (the extension was removed in PHP 7.0.0):
When you use MSSQL extension, date and time values are returned as text, but the format depends on mssql.datetimeconvert setting in php.ini file. When this options is ON, date and time values are converted based on SQL server settings, and when is OFF date and time values are converted to YYYY-MM-DD hh:mm:ss format.
<?php
$server = "server\instanse";
$database = "database";
$username = "username";
$password = "password";
$conn = mssql_connect($server);
if ($conn === false) {
echo "Error (mssql_connect): ".mssql_get_last_message();
exit;
}
mssql_select_db($database, $conn);
$query = "SELECT DateTimeColumn FROM OneTable";
$stmt = mssql_query($sql, $conn);
if ($stmt === false) {
echo "Error (mssql_query): ".mssql_get_last_message();
exit;
}
while ($row = mssql_fetch_assoc($stmt)) {
echo print_r($row, true);
}
mssql_free_result($stmt);
mssql_close($conn);
?>
As an additional note, it seems that this setting is ON in your server environment, because you can send dates like '26-03-2019 00:00:00.000' without errors.
2. How to pass Date and Time values to SQL Server:
As a general rule, date and time values can be passed to SQL Server using unambiguous datetime format (yyyymmdd or yyyy-mm-ddThh:mm:ss) and parameterized statement.
2.1. Pass Date and Time values to SQL Server uisng the PDO_SQLSRV version of PHP Driver for SQL Server:
<?php
$server = "server\instanse";
$database = "database";
$username = "username";
$password = "password";
try {
$conn = new PDO("sqlsrv:server = $server; Database = $database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
try {
$query = "INSERT INTO OneTable (DateTimeColumn) VALUES (?)";
$datetime = (new DateTime())->format("Y-m-d\TH:i:s");
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $datetime);
$stmt->execute();
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
$stmt = null;
$conn = null;
?>
2.2. Pass Date and Time values to SQL Server uisng the SQLSRV version of PHP Driver for SQL Server:
With this version of the driver, you may use the extended parameters syntax and pass the datetime value as PHP DateTime object with information about the PHP and SQL Server data types of the parameter.
<?php
$server = "server\instanse";
$database = "database";
$username = "username";
$password = "password";
$cinfo = array(
"Database" => $database,
"UID" => $username,
"PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
$query = "INSERT INTO OneTable (DateTimeColumn) VALUES (?)";
$datetime = new DateTime();
$params = array(
array($datetime, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_DATETIME, SQLSRV_SQLTYPE_DATETIME)
);
// or as usual, pass datetime values as text
//$params = array($datetime->format("Y-m-d\TH:i:s"));
$stmt = sqlsrv_query($conn, $query, $params);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>

Handling MySql 'Too many connections' error on shared hosting

I have a website that uses a MySql database for storing user info for signing in, and also my data. This site is hosted on a shared hosting server. The problem I'm running into is that I'm occasionally getting a SQL too many connections error. My max connections is set at the default 151.
I am using php for all my server side scripts, and using mysqli pdo connections.
Here is some sample code to show how I handle sql connections from my php scripts. I removed anything that wasn't relevant to the issue, such as input filtering, and character escaping.
<?php
require("common.php");
//get POST data
//My database query
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
//set params for prepared statements
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
$miscErr = "Something failed, please try again.";
}
$row = $stmt->fetch();
//do my password hashing, and checking, and sign in user using data in $row
}
?>
Here is my common.php where the error is thrown. I'm not sure what the correct way is to handle it, as i would like the code to try several times before failing.
<?php
$username = "username";
$password = "**************";
$host = "localhost";
$dbname = "mydbname";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$miscErr = "";
try {
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex) {
$miscErr = "Something failed, please try again";
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
I know this has been a while, but here is the solution that I came up with. Since there is no way for me to prevent the errors, i simply handle them with the following code in my common.php file.
$db = ""; // db object
$er = ""; // error object
/*setdb() is the function that actually gets and starts the db connection.
It returns either the db object, or false. The loop will try up to 5 times
to connect with .1 second breaks in between. if that fails then it logs an
error, and the page fails to load. This has not happened in over 5 months on
a live site.*/
for ($i = 0; $i = 5; $i++) { // short loop
if (setdb() !== false) {
$db = setdb(); // if successful breaks
break;
} else {
if ($i = 5) { // after 5 trys, logs error.
file_put_contents('sqlerror.er', $er . "\r\n", FILE_APPEND);
}
}
usleep(100000); // .1second sleep
}
function setdb(){
$username = "my-username";
$password = "***************";
$host = "localhost";
$dbname = "my_database";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$miscErr = "[1040] Too many connections";
try { // try to make connection
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex) {
$er = $ex;
$pos = strpos($ex, $miscErr);
if ($pos !== false) {
return false; //return false on error
}
file_put_contents('sqlerror.er', $ex . "\r\n", FILE_APPEND);
}
return $db; // return true
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
session_start();

IIS, MS SQL and PHP - SQL select in PHP not working

I have a local MS SQL Database, and a web PHP application on IIS on my server.
On IIS I have successfully connected PHP and my MS SQL database (added connection strings and i see my tables)
But, when I use any SQL select in the PHP web application, it does not work. No data is displayed, or any erros, for example :
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$results = mysql_query("SELECT id FROM users");
while($row = mysql_fetch_array($results)) {
$name = $row['id']
?>
<tr>
<td><?php echo '$name'?></td>
</tr>
<?php
}
?>
</tbody>
</table>
follow like this for pdo connection
$sql = $dbh->prepare("SELECT id FROM users");
$sql->execute();
while($result = $sql->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $result['name'];?></td>
</tr>
<?php } ?>
Please follow that code:
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt =
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
$stmt = $pdo->query('SELECT name FROM users');
while ($row = $stmt->fetch())
{
echo $row['name'] . "\n";
}
MS SQL (or SqlSrv) and MySql are not working on the sames drivers. You have to know which one you are using and the find PHP functions ables to deal with it.
Note: PHP Extension for using driver must be installed on your server and activated on php.ini file
For MySql do not use mysql_xxx() deprecated functions, prefer mysqli_xxx() to them.
You can find here docs and samples code for both mysql & mssql php functions :
MySql :
http://php.net/mysqli_connect
php.net/mysqli_fetch_array
SqlSrv :
http://php.net/sqlsrv_connect
php.net/sqlsrv_fetch_array
So what is your database engine ?
Hope that'll helps you, cheers
Mixing the apis would not work - use only PDO methods like this perhaps
/* Connect to a MySQL database using driver invocation */
try {
/* mysql server */
/* $dsn = 'mysql:dbname=dbname;host=localhost'; */
/* MS SQL Server */
$dsn = 'sqlsrv:Database=dbname;Server=localhost';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$sql='select * from users';
$results=$dbh->query( $sql );
if( $results ){
while( $rs=$results->fetch( PDO::FETCH_OBJ ) ){
echo "<tr><td>{$rs->name}</td></tr>";
}
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Now working great also with select, with this code :
<?php
$serverName = "AC-CLOUD"; //serverName\instanceName
$connectionInfo = array( "Database"=>"Data", "UID"=>"sa", "PWD"=>"Masterkey2010");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Code, Name FROM StoreCards";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['Code'].", ".$row['Name']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
How now i set this two values into table? this is last point. thank you for your patience and time.

IONIC: From MYSQL to MSSQL

Am creating an ionic application using php, at the beginning I've linked the login form with a mysql database that I've created using wamp as a server and everything works fine!
then my boss saids that I have to change it to another database which is on a Microsoft sql server, so I've linked the wamp server with MsSQL and the Connection with database on MSSQl established correctly
but I didn't know how to change the syntaxe on login.php
Here are the old and new cofig.php that works fine
(New config.php)
<?php
$serverName = "HAMDI-PC";
$connectionInfo = array ("Database"=>"MAINT","UID"=>"sa","PWD"=>"sql") ;
$conn = sqlsrv_connect( $serverName, $connectionInfo);
?>
(OLD config.php)
<?php
$conn = new mysqli("localhost", "root", "", "MAINT");
?>
And here is the (login.php) that works with mysql database
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if(isset($_GET["username"]) && isset($_GET["password"]) ) {
if( !empty($_GET["username"]) && !($_GET["password"]) ) {
include"config.php";
$username=$_GET["username"];
$password=$_GET["password"];
$query=" SELECT * FROM D_PROTUSERS WHERE PROT_User='$username' AND PROT_Password ='$password' ";
$result = $conn->query($query);
$out="";
if ($rs=$result->fetch_array()) {
if($out != "") {$out .="";}
$out .='{"PROT_User":"'. $rs["PROT_User"] . '",';
$out .='"PROT_Password":"'. $rs["PROT_Password"] . '"}';
}
$out='{"recods":'.$out.'}';
$conn->close();
echo($out);
}
}
?>
So please I want to know what should I change to make it work at the new database'MSSQl) ,
I'll be thankful to everyone who will tries to help :*
Forget about mysql, you're using ms sql.. so you have to use sqlsrv
Here we go.
config.php
$serverName = "HAMDI-PC\SQLEXPRESS";
$dbname = "MAINT";
$uid = "sa";
$pwd = "sql";
global $con;
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$dbname);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
die( print_r( sqlsrv_errors(), true));
}
And
login.php
<?php
session_start();
include"config.php";
$username=$_REQUEST["username"];
$password=$_REQUEST["password"];
$query = " SELECT * FROM D_PROTUSERS WHERE PROT_User='$username' AND PROT_Password ='$password' ";
$result = sqlsrv_query($conn, $query, array() , array(
"Scrollable" => 'keyset'
));
$num = sqlsrv_num_rows($result);
if ($num > 0)
{
$_SESSION["valid_user"] = true;
$_SESSION['username'] = $username;
sqlsrv_close($conn);
}
else
{
echo "Login Failed: Connection could not be established.";
exit();
}
?>

Insert values in table (mssql server) via PhP by using pdo

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");

Categories