Get data from a table in Azure database - php

I want to get data from the table I have created in Microsoft Azure.
$conn = sqlsrv_connect($server, array("UID"=>$user, "PWD"=>$pwd, "Database"=>$db));
When I connect with the code above, it works. Because I put conditions
if($conn === false){
die(print_r(sqlsrv_errors()));
}
if($conn == true){
echo "hi!";
}
and it returns true and prints "hi!".
But when I try to get data from the table course, it fails.
$cek=sqlsrv_query($conn, "SELECT ID FROM course");
Because after the $cek query, I put such control;
echo "<pre>";
print_r($cek);
echo "</pre>";
if(!$cek)
{echo "Fail!";}
and it gives such error;
Resource id #2
Fail!
How can I manage this problem?
Thank you for your help.

The sqlsrv_query function returns a statement resource.
Returns a statement resource on success
So we need to extract the data from the resource using a function like sqlsrv_fetch_array
$data = sqlsrv_fetch_array($cek);
var_dump($data);

Related

my php code doesn't check data with database

I want this code to check if $name and $password from form login is in database, if it true it shows echo "Hello ".$name; if not echo "You are not in database";, but the problem is it always shows the truth.
Thanks for your answer and sorry for my english)
include "db.php";
$db = db();
/*print_r($db);*/
$name = $_POST["name"];
$password = $_POST["password"];
$qur = "SELECT * FROM login WHERE name ='".$name."' AND password = '".$password."'";
$data_from_table = $db->query($qur);
if($data_from_table == true)
{
echo "Hello ".$name;
}
else
{
echo "You are not in database";
}
$data_from_table is not true but the result object from the query. But it will be false if the user is not in the db because there is no result.
change it to
if($data_from_table!==false) {
some well meant advice: never save passwords in real text in databases, i mean like ever. Here is some php function that will get you on track:
https://www.php.net/manual/de/function.password-hash.php
According to the documentation the PDO::Query function returns a PDOStatement object or false, if it didn't work well. Why did you was true. Documentation
Why do you check it with true, try checking it with false instead so if it is not false, you can catch your $name
The new version of mysql in PHP is no longer maintained,use PDO::Query function
Check the returned data of $data_from_table, is a data set

Calling Stored Procedure and Display Output in Php MS Sql

i have a problem to display the output of the stored procedure after success run the procedure...i hope everyone can help me....here my stored procedure..
$sql = "EXEC [dbo].[sp_mRetailerRegInfo_Add] '$var1','$var2','$var3','$var4','',''";
This my sample data in my SP
EXEC sp_mRetailerRegInfo_Add 'asdf','asdf','bacc#abc.com','123', #RetailerId output, #ErrorCode output
and this is my sample code ..i can run the procedure but it's not display the output
<?php
$serverName = "localhost";
$connectionInfo = array( "Database"=>"db", "UID"=>"user", "PWD"=>"pass");
$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));
}
//-----------------------------------------------
// Perform operations with connection.
//-----------------------------------------------
$sql = "EXEC [dbo].[sp_mRetailerRegInfo_Add] '$var1','$var2','$var3','$var4','',''";
$result = sqlsrv_query($conn, $sql);
if (!$result) {
echo 'Your code is fail.';
}
else {
echo 'Success!';
echo $result;
}
?>
the output will be like this (ID0001) and but i get the output like this
Connection established.
Success!Resource id #3
With a stored procedure, you would use an OUTPUT parameter that you would assign a value to within the procedure. When the procedure finishes, you would access that parameter and use the contents of it however you need.
You can read through Return Data from a Stored Procedure on the MSDN site to get an idea of how to write a stored procedure.
You will want to take a look at this already answered question that gives some details on how to access the OUTPUT parameter from PHP. You would want the second answer there:
The second param of execute needs to be true, rather than conn. This
should work:
$conn = mssql_connect('server', 'user', 'pass');
mssql_select_db('db', $conn);
$procedure = mssql_init('usp_StoredProc', $conn);
$tmpVar1 = 'value';
$tmpVar2 = 'value2';
$outVar1 = '';
$outVar2 = '';
mssql_bind($procedure, "#var1", $tmpVar1, SQLVARCHAR, false, false);
mssql_bind($procedure, "#var2", $tmpVar2, SQLVARCHAR, false, false);
mssql_bind($procedure, "#outVar1", $outVar1, SQLVARCHAR, true);
mssql_bind($procedure, "#outVar2", $outVar2, SQLVARCHAR, true);
mssql_execute($procedure,true);
print($outVar1);
print($outVar2);
If you could provide the definition for your stored procedure, I could elaborate more specifically on how to set up your PHP call.
Well, it's possible. There's a function called mssql_bind for binding the value to a PHP variable
To Call the SP and to store the Output. Try something like this
DECLARE #appout int; -- variable to hold the data returned by SP.
EXEC checkFollowing 10,20, #output = #appout OUTPUT; -- This is how i will call a SP.
#appout - will hold the data returned by the procedure.
So you can do execute your output parameter as below :
$outVar1 = '';
mssql_bind($procedure, "#appout", $outVar1, SQLVARCHAR, true);
mssql_execute($procedure,true);
print($outVar1);

mysql_query connection NULL result, but I've connection successfully

I've problem with mysql. I've PHP script, which returned array into json data from datebase.
I've message from 'echo' about successfully connection, but my result is equals which null of array.
In result on Explorer I've:
Connected successfully
query: SELECT name,id FROM rz_DWzZ'
result:
RESULT:[]
This is this script.
$conn = mysql_connect($servername, $username, $password);
mysql_select_db($database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$return_arr = array();
$qstring = "SELECT name,id FROM rz_DWzZ";
$result = mysql_query($qstring,$conn);
echo "<br>query: ".$qstring."<br>";
echo "<br>result: ".$result."<br>";
while ($row = mysql_fetch_assoc($result))//loop through the retrieved values
{
$row['name']=htmlentities(stripslashes($row['name']));
$row['id']=(int)$row['id'];
array_push($return_arr,$row);
}
mysql_close($conn);
echo "<br>RESULT:".json_encode($return_arr);
You didn't check for failure properly. mysql_*() functions return boolean FALSE on failure, which echo will print as a zero-length/invisible string.
You have to explicitly test for it:
$result = mysql_query(...) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^--method #1
if ($result === false) { // method #2
die(mysql_error());
}
And of course, you should NOT be using those functions anyways. They're obsolete/deprecated, and your code is now useless in newer versions of PHP. You should be using mysqli or PDO for any new development.
As well, you have numerous other bugs:
if ($conn->connect_error) {
the mysql_*() function library has NEVER been object-oriented. It's purely procedural, and has absolutely NO object support whatsoever. Therefore this connection test will always fail, as $conn->connect_error will always evaluate to null, which converts to boolean false as well, meaning you get a false positive for success.

Invalid object name [UserInfo_Table_Azure]

I'm using mobile service of Windows Azure to store data which retrieved from my windows phone application. In my project, I need to generate a pdf when a user needs on website. So I'm using PHP to generate a PDFs which I need to get data from a table in mobile service.
However, when I try to get data, I always receive this error from Windows Azure (SQL server?).
MySql Connected [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'UserInfo_Table_Azure'. Failed to query test table: SELECT Username FROM [UserInfo_Table_Azure]
This is my code
$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...");
} else {
echo "Sql Connected \n";
}
$tsql = "SELECT Username 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";
}
sqlsrv_free_stmt($stmt);
}
It always shows "Sql connected" but can't get data from the table.
Do you guys have any idea?
Thank you.
try the following code
if($conn == "false") {
FatalError("Failed to connect...");
} else {
echo "Sql Connected \n";
}
it will be 100% guarantee about connection success
Finally, I can find the solution. The problem is the schema of mobile service is not a default schema. The schema of tables in mobile service is set according to your mobile service name. For example, if my mobile service name is "School", what I have to do to get data in this mobile service is to use [School].[a table name] instead of just [a table name].

Insert data into MySql table strange exception

I am using this code to insert some values in MySql table:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("bib");
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query);
// Display an appropriate message
if ($result)
echo "<p>Product successfully inserted!</p>";
else
echo "<p>There was a problem inserting the Book!</p>";
mysql_close();
?>
After running it into browser, the following error occurs:
"Apache HTTP Server has encountered a problem and needs to close. We are sorry for the inconvenience."
It seems that mysql_select_db("bib") statement causes it. Database is create , also table...
I am running php 5.3 and mysql 5.1 on windows xp sp 2.
Please any ideas are welcomed...
Thanks...
Any of the mysql_* functions can fail for various reasons. You have to check the return values and if a function indicates an error (usually by returning FALSE) your script has to react appropriately.
mysql_error($link) and mysql_errno($link) can give you more detailed information about the cause. But you don't want to show all the details to just any arbitrary user, see CWE-209: Information Exposure Through an Error Message.
If you don't pass the connection resource returned by mysql_connect() to subsequent mysql_* functions calls, php assumes the last successfully established connection. You shouldn't rely on that; better pass the link resource to the functions. a) If you ever have more than one connection per page you must pass it anyway. b) If there is no valid db connection the php-mysql modules tries to establish the default connection which is usually not what you want; it only takes up more time to fail ..again.
<?php
define('DEBUGOUTPUT', 1);
$mysql = mysql_connect("localhost","root","root");
if ( !$mysql ) {
foo('query failed', mysql_error());
}
$rc = mysql_select_db("bib", $mysql);
if ( !$rc) {
foo('select db', mysql_error($mysql));
}
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query, $mysql);
// Display an appropriate message
if ($result) {
echo "<p>Product successfully inserted!</p>";
}
else {
foo("There was a problem inserting the Book!", mysql_error($mysql), false);
}
mysql_close($mysql);
function foo($description, $detail, $die=false) {
echo '<pre>', htmlspecialchars($description), "</pre>\n";
if ( defined('DEBUGOUTPUT') && DEBUGOUTPUT ) {
echo '<pre>', htmlspecialchars($detail), "</pre>\n";
}
if ( $die ) {
die;
}
}
try this to connect to database:
$mysqlID = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Unable to connect to database");
mysql_select_db(DB_DATABASE) or die("Unable to select database ".DB_DATABASE);
also, try this as your insert query:
$query = "INSERT INTO carte (id, title) values ('".$id."', '".addslashes($titlu)."')
$result = mysql_query($query) or die(mysql_error());
By using die(), it will tell you where it has failed and why

Categories