Azure Mobile Service, making HTTP calls via PHP - php

I have created a demo app, "todo" app. I am using mobile service of windows azure. Hence I have a database called "todo" and tables inside it. Now I can access this database from android java code(as seen in tutorials). But now I have a website that need to access this database created by android app. Can PHP access this mobile service database anyhow?
Thanks in advance.

The database created as part of the Windows Azure Mobile Services creation is 'just' a Windows Azure SQL database instance meaning you could use the SQL Server Driver for PHP to connect to it.
See how to article here, an extract -
<?php
$serverName = "tcp:ProvideServerName.database.windows.net,1433";
$userName = 'ProvideUserName#ProvideServerName';
$userPassword = 'ProvidePassword';
$dbName = "TestDB";
$table = "tablePHP";
$connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);
sqlsrv_configure('WarningsReturnAsErrors', 0);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if($conn === false)
{
FatalError("Failed to connect...");
}
CreateTable($conn, $table, "Col1 int primary key, Col2 varchar(20)");
$tsql = "INSERT INTO [$table] (Col1, Col2) VALUES (1, 'string1'), (2, 'string2')";
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt === false)
{
FatalError("Failed to insert data into test table: ".$tsql);
}
sqlsrv_free_stmt($stmt);
$tsql = "SELECT Col1, Col2 FROM [$table]";
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt === false)
{
FatalError("Failed to query test table: ".$tsql);
}
else
{
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC))
{
echo "Col1: ".$row[0]."\n";
echo "Col2: ".$row[1]."\n";
}
sqlsrv_free_stmt($stmt);
}
sqlsrv_close($conn);
function CreateTable($conn, $tableName, $dataType)
{
$sql = "CREATE TABLE [$tableName] ($dataType)";
DropTable($conn,$tableName);
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
FatalError("Failed to create test table: ".$sql);
}
sqlsrv_free_stmt($stmt);
}
function DropTable($conn, $tableName)
{
$stmt = sqlsrv_query($conn, "DROP TABLE [$tableName]");
if ($stmt === false)
{
}
else
{
sqlsrv_free_stmt($stmt);
}
}
function FatalError($errorMsg)
{
Handle_Errors();
die($errorMsg."\n");
}
function Handle_Errors()
{
$errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
$count = count($errors);
if($count == 0)
{
$errors = sqlsrv_errors(SQLSRV_ERR_ALL);
$count = count($errors);
}
if($count > 0)
{
for($i = 0; $i < $count; $i++)
{
echo $errors[$i]['message']."\n";
}
}
}
?>

The Azure web site has a dedicated PHP section. Check out the link below to find some examples.
http://www.windowsazure.com/en-us/develop/php/

Related

Executing stored procedure in php laravel

I am using Laravel 7 and I want to show the results from the stored procedure. My code is given below. When I execute the stored procedure with parameters in SQL Server, it's showing data. But in Laravel application data is not showing.
Please, help me to find the problem.
$serverName = env("DB_HOST");
$connectionInfo = array( "Database"=>env("DB_DATABASE"), "UID"=>env("DB_USERNAME"), "PWD"=>env("DB_PASSWORD") );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$tsql= " EXEC USP_Daily_TA_Punching_Detailswith_OT '$employee','$datefrom','$dateto'";
$getResults= sqlsrv_query($conn, $tsql);
$data = array();
if ($getResults == FALSE)
{
echo '';
}
else {
//$data[] ='';
do
{
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC))
{
$data[] = $row;
}
}
while (sqlsrv_next_result($getResults));
}
if(count($data)>0){
sqlsrv_free_stmt($getResults);
$total_row = count($data);
}
Always try to use parameters in your statements to prevent possible SQL injection issues. As an additional note, use unambiguous date format, when you pass date values to SQL Server:
Example using PHP Driver for SQL Server:
<?php
// Connection
$serverName = env("DB_HOST");
$connectionInfo = array(
"Database"=>env("DB_DATABASE"),
"UID"=>env("DB_USERNAME"),
"PWD"=>env("DB_PASSWORD")
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
// Statement
$employee = '000010993';
$datefrom = '20200601';
$dateto = '20200610';
$tsql = "EXEC USP_Daily_TA_Punching_Detailswith_OT ?, ?, ?";
$params = array($employee, $datefrom, $dateto);
$getResults = sqlsrv_query($conn, $tsql, $params);
if ($getResults === false) {
die(print_r(sqlsrv_errors(), true));
}
// Results
$data = array();
do {
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
$data[] = $row;
}
} while (sqlsrv_next_result($getResults));
// End
sqlsrv_free_stmt($getResults);
sqlsrv_close($conn);
$total_row = count($data);
?>
Example using Laravel:
<?php
...
$employee = '000010993';
$datefrom = '20200601';
$dateto = '20200610';
DB::select("SET NOCOUNT ON; EXEC USP_Daily_TA_Punching_Detailswith_OT ?, ?, ?", array($employee, $datefrom, $dateto));
...
?>
Try the below to call the store procedure in laravel
DB::select("call USP_Daily_TA_Punching_Detailswith_OT('".$employee."','".$datefrom."','".$dateto."')");

Parameterized Query PHP/SQL Server

I have a web form that enters event details into a database to be listed on a website. The form captures the name of a photo, event title, a date to unlist the event, a sort number, a description, and a bit flag "Mass".
The description field is a plain text field. I know that I should probably change the field to rich text, but that is for a day when I have time to explore how to do that. Anyways... I've been adding HTML characters into my text to format it. I find that the slash of closing characters like < / strong> is being treated as an escape character rather than part of the text. How do I tell my code to not escape?
The code:
//connect to the database.
$serverName = "livedata";
$connectionInfo = array( "Database"=>"administration", "UID"=>"User", "PWD"=>"PASSWORD", "LoginTimeout"=>60 );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
/* Set up the parameterized query. */
$tsql = "insert into tblevents (Photo, title, Unlist, Sort, Description, Par_num, mass ) values(?,?,?,?,?,?,?)";
/* Set parameter values. */
$dt = $_POST['unlist'];
if ($dt == ""){
$dt = null;
}
$Sort = $_POST['sort'];
if ($Sort == "" ){
//query to get the max of sort in the database items
//+1 sort
$sql2 = "SELECT tblevents.Par_Num, Max(tblevents.Sort) AS MaxOfSort FROM parishevents.dbo.tblevents GROUP BY tblevents.Par_Num HAVING (((tblevents.Par_Num)=" . $_POST['par_num'] . "));";
//echo "SQL2: " . $sql2 . "<br><br>";
$stmt2 = sqlsrv_query( $conn, $sql2);
if( $stmt2 === false ) {
die( print_r( sqlsrv_errors(), true));
}
$result2 = sqlsrv_query($conn, $sql2);
while($row2 = sqlsrv_fetch_array($result2)) {
$Sort = $row2['MaxOfSort'] +1;
}
if(isset($_POST['mass'])){
if($_POST['mass'] == "on"){
$mass = -1;
}
else{
$mass = 0;
}
}else{
$mass = 0;
}
$params = array($_POST['photo'], $_POST['title'], $dt, $Sort, $_POST['description'], $_POST['par_num'], $mass);
/* Prepare and execute the query. */
$stmt = sqlsrv_query($conn, $tsql, $params);
/* Free statement and connection resources. */
sqlsrv_free_stmt($stmt);
}

php page to insert data to sql not working

I'm trying to add data to my sql server from a Unity game through a php. The php code is given below. The URL I'm testing with is
The SQL server as well as the php file is hosted in Azure, I have been able to add data through standard SQL commands etc(database connection is working properly), and running the following page when tested with the URL http://example.net/filename.php?one=4&two=8 only returns Test84, and no change is made to the table.
I would really appreciate it if someone is able to tell me as to why this is not working
<?php
//
echo"Test";
$data=$_GET[one];
$data1=$_GET[two];
echo $data1;
echo $data;
$conn = new PDO("sqlsrv:server = {}; Database = {}", "{}", "{}");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare ("INSERT INTO registratib_tbl (name,email ) VALUES ( ? , ?)");
$sql->bindParam(1, $data);
$sql->bindParam(2, $data1);
$sql->execute();
//$conn->query($sql);
echo "<h3>Data Inserted!</h3>";
?>
Please try to insert data as shown below:
<?php
$serverName = "tcp:yourserver.database.windows.net,1433";
$connectionOptions = array("Database"=>"yourdatabase",
"Uid"=>"yourusername", "PWD"=>"yourpassword");
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//Select Query
$tsql = "SELECT [CompanyName] FROM SalesLT.Customer";
//Executes the query
$getProducts = sqlsrv_query($conn, $tsql);
//Error handling
if ($getProducts == FALSE)
die(FormatErrors(sqlsrv_errors()));
$productCount = 0;
$ctr = 0;
?>
<h1> First 10 results are : </h1>
<?php
while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC))
{
if($ctr>9)
break;
$ctr++;
echo($row['CompanyName']);
echo("<br/>");
$productCount++;
}
sqlsrv_free_stmt($getProducts);
$tsql = "INSERT SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT INSERTED.ProductID VALUES ('SQL New 1', 'SQL New 2', 0, 0, getdate())";
//Insert query
$insertReview = sqlsrv_query($conn, $tsql);
if($insertReview == FALSE)
die(FormatErrors( sqlsrv_errors()));
?>
<h1> Product Key inserted is :</h1>
<?php
while($row = sqlsrv_fetch_array($insertReview, SQLSRV_FETCH_ASSOC))
{
echo($row['ProductID']);
}
sqlsrv_free_stmt($insertReview);
//Delete Query
//We are deleting the same record
$tsql = "DELETE FROM [SalesLT].[Product] WHERE Name=?";
$params = array("SQL New 1");
$deleteReview = sqlsrv_prepare($conn, $tsql, $params);
if($deleteReview == FALSE)
die(FormatErrors(sqlsrv_errors()));
if(sqlsrv_execute($deleteReview) == FALSE)
die(FormatErrors(sqlsrv_errors()));
?>
For more information, please visit this article.

SELECT_IDENTITY() not working in php

Scenario:
I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})
The data types are correct.
I need to now get the latest IDENTIY which is GradeID.
I have tried the following after consulting MSDN and StackOverflow:
SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
The next thing I tried, SELECT ##IDENTITY Still to no avail.
Lastly, I tried PDO::lastInsertId() which did not seem to work.
What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.
Expected Results:
Just to return the newly inserted row's IDENTITY.
Current Results:
It returns it but is NULL.
[Object]
0: Object
ID: null
This piece pasted above is the result from print json_encode($newID); as shown below.
Notes,
This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.
As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks
Code:
for ($i=0; $i < sizeof($grades); $i++) {
$grade = $grades[$i];
$oldID = $grade->GradeID;
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";
try {
$sqlObject->executeNonQuery($query);
$query = "SELECT SCOPE_IDENTITY() AS ID";
$newID = $sqlObject->executeQuery($query);
print json_encode($newID);
} catch(Exception $e) {
print json_encode($e);
}
$gradesDictionary[] = $oldID => $newID;
}
EDIT #1
Here is the code for my custom wrapper. (Working with getting the lastInsertId())
class MSSQLConnection
{
private $connection;
private $statement;
public function __construct(){
$connection = null;
$statement =null;
}
public function createConnection() {
$serverName = "localhost\MSSQL2014";
$database = "{Fill In}";
$userName = "{Fill In}";
$passWord = "{Fill In}";
try {
$this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
$this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die("Connection Failed, please contact system administrator.");
}
if ($this->connection == null) {
die("Connection Failed, please contact system administrator.");
}
}
public function executeQuery($queryString) {
$results = array();
$this->statement = $this->connection->query( $queryString );
while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
array_push($results, $row);
}
return $results;
}
public function executeNonQuery($queryString) {
$numRows = $this->connection->exec($queryString);
}
public function getLastInsertedID() {
return $this->connection->lastInsertId();
}
public function closeConnection() {
$this->connection = null;
$this->statement = null;
}
}
This is PDO right ? better drop these custom function wrapper...
$json = array();
for ($i=0; $i < sizeof($grades); $i++) {
//Query DB
$grade = $grades[$i];
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$success = $stmt->execute(array($grade->Name,
$grade->Capacity,
$grade->SpringPressure));
//Get Ids
$newId = $conn->lastInsertId();
$oldId = $grade->GradeID;
//build JSON
if($success){
$json[] = array('success'=> True,
'oldId'=>$oldId, 'newId'=>$newId);
}else{
$json[] = array('success'=> False,
'oldId'=>$oldId);
}
}
print json_encode($json);
Try the query in this form
"Select max(GradeID) from dbo.Grades"

Get Return Value from SQL Stored Procedure using PHP

So I have a php script that uses a stored procedure to interact with my SQL database. The stored procedure works just fine, the problem is I don't know how to get my php to echo the Return Value from the stored procedure. The stored procedure is basically activating an account using an activation key and sets the username and password.
It basically says "if the activation key provided does not have a username yet, set it to the one provided and RETURN 1, if it already has a username RETURN 2, and if the activation key does not exist RETURN 3". It works perfectly in SQL and even give the correct Return Value. Now how can I get my php to echo that? I have tried the following:
$link = sqlsrv_connect($myServer, array('Database' => $myDB, 'UID' => $myUser, 'PWD' => $myPass));
if($link === FALSE) {
die('Could not connect: ' . sqlsrv_errors(SQLSRV_ERR_ALL));
}
$key = $_REQUEST['key'];
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$query = "EXEC Activate_Account";
$query .=" #key = ";
$query .= $key;
$query .=", #user = ";
$query .= $username;
$query .=", #pass = ";
$query .= $password;
$result = sqlsrv_query($link, $query);
while($row = sqlsrv_fetch_array($result))
{
echo $row[0];
}
sqlsrv_close($link);
and
while($row = sqlsrv_fetch_array($result))
{
echo $row['Return Value'];
}
Neither of them echo anything.
To return a value with a stored procedure:
For example:
SQL :
CREATE DEFINER=`user`#`localhost` PROCEDURE `ProcedureName`(IN `Input_Value` INT, OUT `Out_val` INT)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
// Your SQL Code
SET Out_val= Your Value;
SELECT Out_val;
END
PHP Code:
$insert = "CALL ProcedureName(:Input_Value,
#Out_val)";
$bdd = new PDO('mysql:host=localhost;dbname=db-name', 'user', 'password');
$stmt = $bdd->prepare($insert);
$stmt->bindParam(':Input_Value', $an_input_value, PDO::PARAM_STR);
$stmt->execute();
$tabResultat = $stmt->fetch();
$Out_val = $tabResultat['Out_val'];
var_dump($Out_val);
The following example enables you to retrieve the RETURN value from a stored procedure and allows you to retrieve the OUTPUT values.
SQL:
CREATE PROCEDURE [ProcedureName]
#input_parameter as int,
#output_parameter as int out
AS
BEGIN
-- Your SQL code
SELECT #output_parameter = #input_parameter;
RETURN 2
END
PHP:
// Connect.
$link = sqlsrv_connect($myServer, array('Database' => $myDB, 'UID' => $myUser, 'PWD' => $myPass));
$returnValue = 0;
$inputParameter = 10;
$outputParameter = 0;
$parameters = [
[&$returnValue, SQLSRV_PARAM_OUT],
[$inputParameter, SQLSRV_PARAM_IN],
[&$outputParameter, SQLSRV_PARAM_OUT],
];
$sql = "EXEC ? = ProcedureName ? ?";
$stmt = sqlsrv_query($link, $sql, $parameters);
if ($stmt === false)
{
// Throw/Handle Error.
}
// $returnValue and $outputParameter should be updated here because they were passed by Reference.
// Retrieve query rows if any.
$rows = [];
while (($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ?? false) !== false) {
$rows[] = $row;
}
Some more reading about this topic can be found on the following links: How to retrieve input and output parameters using the sqlsrv driver and Sqlsrv query

Categories