I am learning the php game - and am in need of completing two tasks in one .php file. What I need is
1) Connect To Server
2) Execute Stored Procedure (runs an insert into statement)
3) When stored proc fully executes run select statement against table
4) Echo the results
This is my syntax -> and I get an error that the table tablecreatedfromproc does not exist. Is the Select statement firing before the stored proc fully executes? If I run the stored procedure manually, it executes as it should (meaning it is valid syntax) - but when I try to run it from my php file I get the error.
How should this syntax be updated so that it executes as I need it to?
//connection string
$hostname = 'hostname';
$dbname = 'dbname';
$username = 'username';
$password = 'password';
$dbh = new PDO("dblib:host=$hostname;dbname=$dbname","$username","$password");
//Parsing the passed in data
$passedparams = implode(',',$_REQUEST['passedparams']);
//Capturing the dates from passed in data
$d1 = $_REQUEST['d1'];
$d2 = $_REQUEST['d2'];
//Run Stored Procedure To Create Table
$proc = mssql_init('HoldingPattern',$conn);
mssql_bind($proc,'#d1',$d1,SQLVARCHAR);
mssql_bind($proc,'#d2',$d2,SQLVARCHAR);
//Create Query String to query newly created table
$sql = "SELECT ".$passedparams." FROM tablecreatedfromproc";
$stmt = $dbh->prepare($sql);
$stmt->execute();
you are using PDO to connect, in the same time that you are trying to execute another function mssql_* -which is removed in php7-
use PDO to execute your procedures ,
$stmt = $dbh->prepare("HoldingPattern");
$stmt->bindParam(/* your required parameters goes here */);
$stmt->execute();
as mentioned here:
If you need to get Output variable from MSSQL stored procedure, try this :
-- PROCEDURE
CREATE PROCEDURE spReturn_Int #err int OUTPUT
AS
SET #err = 11
GO
$sth = $dbh->prepare("EXECUTE spReturn_Int ?");
$sth->bindParam(1, $return_value, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$sth->execute();
print "procedure returned $return_value\n";
Related
I need some help in relation to PHP PDO MSSQL Stored Procedure.
I have a Stored Procedure which is called with two parameters userId and pwd, the Stored Procedure then returns two values status and token (using SELECT #status as status, null as token in the Stored Procedure to return the value)
When I try to call the Stored Procedure from PHP (ver. 7.0) using PDO I don't receive any return values
This is the PHP code:
$conn = new PDO("sqlsrv:server=".$host.";Database=".$db_name,
$username,$password);
$userId = "2465";
$pwd = "460";
$query = "exec sp_getToken #userId=:userId, #pwd=:pwd";
$stmt = $conn->prepare($query);
$stmt->bindValue(':userId', $userId);
$stmt->bindValue(':pwd', $pwd);
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
var_dump($result);
}
Can anyone tell what to do?
It is almost the same, but you may try with this:
<?php
$host = 'server\instance,port';
$db_name = 'database';
$username = 'user';
$password = 'password';
# Connection
try {
$conn = new PDO("sqlsrv:server=".$host.";Database=".$db_name, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die("Error connecting to SQL Server: ".$e->getMessage());
}
# Stored procedure
try {
$query = "{call sp_getToken(#userId=?, #pwd=?)}";
$userId = "2465";
$pwd = "460";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $userId, PDO::PARAM_STR);
$stmt->bindParam(2, $pwd, PDO::PARAM_STR);
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
var_dump($result);
echo"</br>";
}
} catch(PDOException $e) {
die("Error executing stored procedure: ".$e->getMessage());
}
$stmt = null;
#
$conn = null;
?>
Problem solves :)
By adding "SET NOCOUNT ON" to my stored procedure. Obviously the problem was related to the facts, that a stored procedure returns two results, the first result containing the number of rows affected and the second result containing the actual data.
Thanks to everybody for trying helping me :)
Stored procedures are stored in the database schema I believe.
If you add the schema to your query SQL server should know where to "look" for your stored procedure.
$query = "EXEC [dbo].[sp_getToken] #userId=:userId, #pwd=:pwd";
Also when binding the parameters it might help defining the type. I've had issues with SQL server where defining the parameter typed resolved the issue.
$stmt->bindValue(':userId', $userId, PDO::PARAM_STR);
$stmt->bindValue(':pwd', $pwd, PDO::PARAM_STR);
Also, make sure that the user that PHP logs into the database has the Execute permission in SQL Server.
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/grant-permissions-on-a-stored-procedure?view=sql-server-2017
In Object Explorer, connect to an instance of Database Engine and then expand that instance.
Expand Databases, expand the database in which the procedure belongs, and then expand Programmability.
Expand Stored Procedures, right-click the procedure to grant permissions on, and then click Properties.
From Stored Procedure Properties, select the Permissions page.
To grant permissions to a user, database role, or application role, click Search.
In Select Users or Roles, click Object Types to add or clear the users and roles you want.
Click Browse to display the list of users or roles. Select the users or roles to whom permissions should be granted.
In the Explicit Permissions grid, select the permissions to grant to the specified user or role. For a description of the permissions, see Permissions (Database Engine).
Selecting Grant indicates the grantee will be given the specified permission.
Selecting Grant With indicates that the grantee will also be able to grant the specified permission to other principals.
I have the below REST web service that I am using to get user information from User table:
$name = htmlentities($_GET["name"]);
$name = strtoupper($name);
$dbh = new PDO("oci:dbname= $dbhost", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("select * from Users where username =:name");
$sth->bindParam(':name', $name);
$sth->execute();
$result = array();
$result["User"] = $sth->fetchAll((PDO::FETCH_ASSOC));
print_r ($result); //returns no data
When I print out the results, no data is returned. If I hard code a username value instead of using :name, then data comes back:
$sth = $dbh->prepare("select * from Users where username ='TESTUSER'");
I am not sure what I am doing wrong with the binding of the variable that is causing the SQL to run incorrectly. I tried using bindValue and bindParam and still returns no data. I am not recieving any errors, just no data.
UPDATE: It looks like the syntax is correct. Is there anything on the Oracle side that would prevent a prepared statement from being run?
I figured out why data wasn't returning on the query. The database has the username field set as a CHAR(8) and usernames that were being passed only had 7 characters so it was failing. I need to append a blank space at the end of the string for it to match.
I am using procedure first time.How can I fetch data using procedure.I created this procedure in sql file.
CREATE PROCEDURE `GetUserProfile`(IN p_user_id INT, IN p_enabled BIT)
READS SQL DATA
BEGIN
# prepare init params
if p_user_id = 0 then
set p_user_id = null;
end if;
select parent_user_id
,user_id
,Last_name
,First_name
,email as Email_address
,mobile as Phone
from app_users
where app_user_id = IFNULL(p_user_id, user_id)
and enabled = IFNULL(p_enabled, enabled);
then How can I fetch the user detail through PHP like First_name,Last_name etc.
thanks
Do you can use sqlsrv_connect function to connect to SQL Server db, use sqlsrv_prepare function to call tsql function and $params args and, at last, use one of the sqlsrv_fetch_* function to retrieve data.
see instruction on this page:
http://technet.microsoft.com/en-us/library/cc793139(v=sql.90).aspx
You can use PDO to execute a mysql stored procedure and access the results.
See the examples on this page from the PHP Documentation. In particular example #4
<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $return_value\n";
?>
and example #5
<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
?>
If you haven't used PDO before I'd suggest browsing through the documentation, creating a new PDO object to manipulate a dabase is as simple as:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
I'm looking to produce the last inserted id using SQLSRV. I need to use a prepared statement though. I've seen an answer on here (see link after the code below) showing how to do it, but the statement isn't prepared for anti-sql injection purposes.
//Prep the variables for insert
$p1 = $_POST['description'];
$p2 = intval($_POST['visible']);
$p3 = strval($_POST['whoToShow']);
//Build an array with those variables
$params = array(&$p1, &$p2, &$p3);
//Build the SQL
$sql = "INSERT INTO notifications (description, visible, whoToShow) VALUES (?, ?, ?)";
//Execute the sql using a prepared statement, passing the variables in an array
$stmt = sqlsrv_prepare($conn, $sql, $params) or die(FormatErrors(sqlsrv_errors()));
Please review Microsoft´s sqlsrv driver for PHP not returning any result when querying "SELECT SCOPE_IDENTITY() AS id" on Stack Overflow for details on getting the last inserted ID using a non prepared statement.
Thank you in advance for your support.
Consider using a stored procedure instead of a direct INSERT statement. Using a stored procedure is better as you can return a recordset from the stored procedure which would include the ID of the inserted record.
I'm using Microsoft SQL Server with my PHP. I am using the mssql_query library to connect to SQL server.
Not sure if it makes a difference, but I see you're using a different library to connect. Every query we do is through stored procedures. Its far more efficient and definitely more secure.
$myServer = "xxxxxxx";
$myUser = "xxxxxxxx";
$myPass = "xxxxxxx";
$myDB = "myDatabase";
//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
$query = "exec eCommerce.dbo.cart_GET_Detail #sid = ".$_SESSION['sid']." , #cc = '".$_SESSION['cc']."'";
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
$hasItems = (($numRows == 0) ? 'N' : 'Y');
while ($RSLoop = mssql_fetch_array($result)) {
//var_dump($RSLoop); //var_dump will show you everything in the recordset
echo '<tr><td colspan=6 width=720 class=cartDivider> </td></tr>';
echo '<form name=frmProduct'.$idx.' method=POST action=_action.asp>';
echo '<input type=hidden name=pid value="'.$RSLoop['product_id'].'">';
}
That was a call to a stored procedure to get the contents of the shopping cart stored in a SQL table.
Doing an insert on a stored procedure is similar. You should be able to find some code samples on SQL Server stored procedures.
I have a little (and stupid) problem: I'm building a PHP application using mysqli and a MySQL server. When the application is loaded, a variable called $database is initialized using
$database = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
This, of course, works perfectly. If I create an statement to do a query:
$stmt = $database->prepare('SELECT a, b, c FROM table WHERE a = ?');
This still works. But, if I try to create another statement without closing the previous one, sometimes works, and sometimes now. The error I get when the creation of the statement fails is:
Fatal error: Call to a member function bind_param() on a non-object
And my question is: why? What should I do, open a connection (new mysql(...)) every time I want to create a new statement (and I have another open)?
Example
$stmt = $database->prepare('SELECT a, b, c FROM table WHERE a = ?');
$stmt->bind_param('i', $aValue);
$stmt->execute();
/* do some other operations, without closing $stmt */
$stmt2 = $database->prepare('INSERT INTO table2 (e, f) VALUES (? ,?)');
// Now, $stmt2 isn't initialized, so when the next line is run, the app fails
$stmt2->bind_param('ss', $someValue, $anotherValue);
If, before the
$stmt2 = $database->prepare('INSERT INTO table2 (e, f) VALUES (? ,?)');
I add a simple
$stmt->close();
All works without any problems. So, what is the problem?
You cannot run another query until you have fetched all the results from the previous. Otherwise you will have to make a separate connection.
Did you remember to bind_param & execute ? :
$stmt->bind_param("s", $string);
$stmt->execute();
//etc..
OR
$stmt->bind_param("i", $int);
$stmt->execute();
//etc..
IF you want multiple queries : check out multi_query