SQL Server SQL Authentication - php

I want to connect to a sql Server.. Only it won't work.
I granted a user and role enough permissions. But what am I doing
<?php
$serverName = "LERAARSKAMER01\SQLEXPRESS";
$database = "sqlservertest";
// Get UID and PWD from application-specific files.
$uid = "sqlAdmin";
$pwd = "tester";
try {
$conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
$query = 'select * from dbo.users';
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
print_r( $row );
}
// Free statement and connection resources.
$stmt = null;
$conn = null;
?>
This is a screenshot of the server...
What is wrong?

After searching for a while I found I have to set sql Authentication on.
Microsoft SQL Managment Studio --> Database (right click-> properties->security)
Then I enabled sa, changed the password and settings with this (password policy,...).
It works also with sqlAdmin (the other user). Just with the same code..
USE Master
GO
ALTER LOGIN test_must_change WITH PASSWORD = ‘samepassword’
GO
ALTER LOGIN test_must_change WITH
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF;

Related

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.

stored procedure parameters in 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();
?>

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

Having problems connecting to mssql server

Code I'm using to test connection:
$serverName = 'host\sqlexpress';
$database = 'dbname';
// Get UID and PWD from application-specific files.
$uid = 'username';
$pwd = 'password';
try {
$conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
$query = 'select * from tablename';
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
print_r( $row );
}
// Free statement and connection resources.
$stmt = null;
$conn = null;
?>
The error I'm getting when running this file is just, "Error connecting to SQL Server"
Any clue why this may not be working? Any way I can get a more detailed error report?

Categories