IONIC: From MYSQL to MSSQL - php

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

Related

Sql server, php [duplicate]

So I keep getting this error when I want to query something to the ms sql server..
The connection is made with the database but the queries seem to fail.
The error log contains this:
PHP Fatal error: Call to undefined function mssql_query()
The code on the php:
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM test WHERE username='".$username."' AND password='".$password."'";
$res = mssql_query ($sql) or die(mssql_error());
if (mssql_num_rows($res) == 1) {
$row = mssql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['Username'];
$_SESSION['afdeling'] = $row['Afdeling'];
$_SESSION['mail'] = $row['Mail'];
header("Location: test.php");
exit();
} else {
echo "Invalid login information. Please return to the previous page.";
exit(); } } ?>
Does anybody knows what the problem is?
Thanks in advance!
connect.php code:
<?php
$serverName = "MTN-TEST"; //serverName\instanceName
$connectionInfo = array( "Database"=>"PROCES_TEST", "UID"=>"blaaa", "PWD"=>"blooo");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "<span style='color:green;'>Connection established.</span><br />";
}else{
echo "<span style='color:red;'>Connection could not be established.</span><br />";
die( print_r( sqlsrv_errors(), true));
}
?>
You don't have the MS SQL Drivers installed.
You can check this with phpinfo();
On Linux you need mssql.so or sybase.so
With debian its apt-get install php5-sybase
For windows take a look here:
http://msdn.microsoft.com/en-US/library/cc793139%28v=SQL.90%29.aspx
Drivers need to be configured for PHP to find the function mssql_...
You could also look at PDO DB classes as they can connect to any DBS, you need the drivers installed tho.
If your connect.php code returns "Connection established.", it's mean you installed MS SQL Drivers correctly.
You have to use sqlsrv_queryfunction instead of mssql_query.
The correct form of this command is:
<?php
$serverName = "serverName";
$options = array( "UID" => "sa", "PWD" => "Password", "Database" => "DBname");
$conn = sqlsrv_connect($serverName, $options);
if( $conn ) {
echo "Connection established.<br />";
$query='select * from test';
$result = sqlsrv_query($conn,$query);
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
you can learn more here:
"PHP Fatal error: Call to undefined function mssql_select_db() in c:\...appscript.php on line 16"
you can use mssql_get_last_message() for mssql errors

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.

My code in php does not display images stored in SQL Server

I make a query to display an image in php with the column type image.
But it does not show anything.
Attach the code and hope someone can help me
$serverName = "localhost";
$uid = "sa";
$pwd = "d1mogodon";
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>"Imagen");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ){
echo "Unable to connect.</br>";
die( print_r( sqlsrv_errors(), true));
}
$fotoquery = "SELECT imagen FROM Imagen";
$stmt = sqlsrv_query( $conn, $fotoquery);
while($result = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$image = $result['imagen'];
}
Header ("Content-type: image/jpeg");
echo $image;
sqlsrv_close($conn);

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

PHP Fatal error: Call to undefined function mssql_query()

So I keep getting this error when I want to query something to the ms sql server..
The connection is made with the database but the queries seem to fail.
The error log contains this:
PHP Fatal error: Call to undefined function mssql_query()
The code on the php:
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM test WHERE username='".$username."' AND password='".$password."'";
$res = mssql_query ($sql) or die(mssql_error());
if (mssql_num_rows($res) == 1) {
$row = mssql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['Username'];
$_SESSION['afdeling'] = $row['Afdeling'];
$_SESSION['mail'] = $row['Mail'];
header("Location: test.php");
exit();
} else {
echo "Invalid login information. Please return to the previous page.";
exit(); } } ?>
Does anybody knows what the problem is?
Thanks in advance!
connect.php code:
<?php
$serverName = "MTN-TEST"; //serverName\instanceName
$connectionInfo = array( "Database"=>"PROCES_TEST", "UID"=>"blaaa", "PWD"=>"blooo");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "<span style='color:green;'>Connection established.</span><br />";
}else{
echo "<span style='color:red;'>Connection could not be established.</span><br />";
die( print_r( sqlsrv_errors(), true));
}
?>
You don't have the MS SQL Drivers installed.
You can check this with phpinfo();
On Linux you need mssql.so or sybase.so
With debian its apt-get install php5-sybase
For windows take a look here:
http://msdn.microsoft.com/en-US/library/cc793139%28v=SQL.90%29.aspx
Drivers need to be configured for PHP to find the function mssql_...
You could also look at PDO DB classes as they can connect to any DBS, you need the drivers installed tho.
If your connect.php code returns "Connection established.", it's mean you installed MS SQL Drivers correctly.
You have to use sqlsrv_queryfunction instead of mssql_query.
The correct form of this command is:
<?php
$serverName = "serverName";
$options = array( "UID" => "sa", "PWD" => "Password", "Database" => "DBname");
$conn = sqlsrv_connect($serverName, $options);
if( $conn ) {
echo "Connection established.<br />";
$query='select * from test';
$result = sqlsrv_query($conn,$query);
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
you can learn more here:
"PHP Fatal error: Call to undefined function mssql_select_db() in c:\...appscript.php on line 16"
you can use mssql_get_last_message() for mssql errors

Categories