Executing stored procedure with IN and OUT parameters in PHP - php

I want to execute a stored procedure into my PHP code, this stored procedure has an IN and an OUT parameter. The stored procedure is this:
USE [phl_pmx]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[PMX_SP_RecreateSynonymsOfSourceDb]
#sourceDb = phl
SELECT 'Return Value' = #return_value
GO
And I already wrote the following code, but it keeps giving errors that he can't execute it, or he just won't show a thing.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include_once 'DBC.php';
$link = mssql_connect('server', 'sa', 'password');
if (isset($_POST['StoredProcedure']))
{
mssql_select_db($id,$link);
$a = new TableOutput();
$a->getTables ("PMX_SP_RecreateSynonymsOfSourceDb","phl");
mssql_close($link);
}
elseif (isset($_POST['Value']))
{
$query =mssql_query("UPDATE [phl].[dbo].[PMX_EXDB] set ExtraDb='phl_pmx'");
mssql_close($link);
}
?>
This is the function for it.
<?php
class TableOutput {
function getTables($procname, $parameter) {
$stmt = null;
$data = null;
$vars = null;
$num = null;
$con = mssql_connect('server', 'sa', 'password');
if
(!$con) {
die('Could not connect: ' . mssql_error());
}
mssql_select_db("phl",$con);
$this->setStmt(mssql_init($procname, $con));
mssql_bind($this->getStmt(), '#sourceDb', $parameter, SQLINT2, false, false);
if ($rtn != 0) {
echo ("Errors happened when executing the stored procedure");
}
$exec = mssql_execute($this->getStmt());
$data = array();
$i = 0;
while ($row = mssql_fetch_assoc($exec)) {
$data[++$i] = $row;
}
unset($con);
unset($stmt);
return $data;
}
function setStmt($a_stmt) {
$this->stmt = $a_stmt;
}
function getStmt() {
return $this->stmt;
}
}
?>`
Does anyone know how to correct the code, because it keeps showing me the following error:
Warning: mssql_execute(): stored procedure execution failed in /var/www/mssql/management/DBC.php on line 24 Warning: mssql_fetch_assoc() expects parameter 1 to be resource, boolean given in /var/www/mssql/management/DBC.php on line 27

I don't know MSSQL stored procedures, so I can't analyse your stored procedure. If your proc is returning multiple resultsets you need to use mssql_next_result:
do {
while ($row = mssql_fetch_row($exec)) {
$data[++$i] = $row;
}
} while (mssql_next_result($exec));
Maybe this helps.

Related

setting php boolean to FALSE not working

I have no records in a table called assessment
I have a function:
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
I call the function thus:
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
However my function is printing out nothing when I was expecting FALSE. It prints out true when there's a record.
When I get the result in $thereisdata I want to check for if its TRUE or FALSE but its not working.
I looked at the php manual boolean page but it didn't help
It seems that you are passing the database connection as an object using the variable $c in your function parameter. This tells me that you would greatly benefit by creating a class and using private properties/variables. Also, there are many errors in your code that shows me what you are trying to achieve, some errors are the way you are closing your db connection using the wrong variable, or how you place the close connection method after the return, that will never be reached.
Anyway, I would create a database class where you can then call on specific functions such as the check_assessment_record() as you wish.
Here's how I would redo your code:
<?php
class Database {
private $conn;
function __construct() {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$this->conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
function check_assessment_record($p_id, $a_id) {
$sql = "SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
echo '<p>set $de = true</p>';
$de = TRUE;
} else {
echo '<p>set $de = false</p>';
$de = FALSE;
}
return $de;
}
function __destruct() {
$this->conn->close();
}
}
$p_id = 1;
$a_id = 2;
$db = new Database();
$record = $db->check_assessment_record($p_id, $a_id);
var_dump($record);
?>
are you using PDO's correctly?
A call for me would normally look like;
$aResults = array();
$st = $conn->prepare( $sql );
$st->execute();
while ( $row = $st->fetch() ) {
//do something, count, add to array etc.
$aResults[] = $row;
}
// return the results if there is, else returns null
if(!empty($aResults)){return $aResults;}
if you didnt want to put the results into an array you could just check if a column is returned;
$st = $conn->prepare( $sql );
$st->execute();
if(! $st->fetch() ){
echo 'there is no row';
}
Here is the code
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
You can check the return value using if else condition as
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
if($thereisdata){ print_f('%yes data is present%'); }
else{ print_f('% no data is not present %'); }
The reason is , sometime function returning Boolean values only contain the true value and consider false value as null , that's why you are not printing out any result when data is not found.
Hope this will help you. Don't forget to give your review and feedback.

In PHP, SQLite3Result object has not been correctly initialised

I have that piece of code in my php file (correctly working):
$db = new Database();
$stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
$stmt->bindValue(":gid", $_SESSION['group_id'], SQLITE3_INTEGER);
if (($result = $stmt->execute()) === false) {
echo "bad";
}
$bills = $result;
while ($bill = $bills->fetchArray()) {
do stuff....
}
Then I try to put all database related code in function:
function getBillsByGID($gid) {
$db = new Database();
$stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
$stmt->bindValue(":gid", $gid, SQLITE3_INTEGER);
if (($result = $stmt->execute()) === false) {
return null;
}
return $result;
}
And in the original file:
$bills = getBillsByGID($_SESSION['group_id']);
while ($bill = $bills->fetchArray()) {
do stuff...
}
That gives me message: "Warning: SQLite3Result::fetchArray(): The SQLite3Result object has not been correctly initialised in line 61" (line with while($bill = $bills->fetchArray()))
var_dump($bills) after calling the function gives object(SQLite3Result)#10 (0) { }
So how do I make a function which will work properly?
Are you closing the statement in your getBillsByGID? Calling $stmt->close() invalidates the result you got from $stmt->execute(). After that, calling $result->fetchArray() will give the error "The SQLite3Result object has not been correctly initialised in ...".
I think you need to fetch data in your function and then return your variable
function getBillsByGID($gid) {
$db = new Database();
$stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
$stmt->bindValue(":gid", $gid, SQLITE3_INTEGER);
if ($stmt->execute() === false) {
return null;
}
$array = array();
while($data = $stmt->fetchArray())
{
$array[] = $data;
}
return $array;
}
Now assign the function to a variable and loop throw to get your array's data
$bills = getBillsByGID($_SESSION['group_id']);
foreach($bills as $data) {
//do stuff with $data
}

PHP MySQLi select function not execute

I'm trying to call my function, but she's wrong.
I believe it is in connection variable.
Connection:
$conn = mysqli_connect('','','', '');
if(mysqli_connect_errno()) {
header("Location: error.php");
exit();
}
Function:
function t_car($id) {
global $conn;
$s_t_car = "SELECT *
FROM t_car
WHERE session='$id'";
$s_t_car_return = mysqli_query($conn, $s_t_car) or die("Erro SQL.".mysqli_error());
return $s_t_car_return;
}
Call Function:
$s_t_car_return = t_car($conn, $_SESSION['session_client']);
if(mysqli_num_rows($s_t_car_return )!=0) {
while($r_t_car = mysqli_fetch_array($s_t_car_return )) {
}
}
Error:
Catchable fatal error: Object of class mysqli could not be converted to string
At first you need to enter your settings from your MySQL server (mysql db).
$connection = mysqli_connect("HOSTNAME","USERNAME", "PASSWORD","DATABASE");
You can then use an if statement to check if the connection to the server has been made, if so, continue execution of following code, otherwise die();
If you want to fetch the data see below here:
$res = $connection->query("SELECT finger FROM hand WHERE index = 3");
while($row = $res->fetch_array())
{
print_r($row);
}
mysqli_query() returns a result. You have to fetch the result to do something with it.
$res = mysqli_query($conn, $s_t_car) or die("...");
$s_t_car_return = mysqli_fetch_row($res);

how to execute sql server stored procedure on php?

i want to know why i cannot call any stored procedure on php file
it always return false
but when i call it on sql server directly, it shows my data
here is my php:
include ($_SERVER['DOCUMENT_ROOT'] . '/simda/classes/koneksi.php');
global $conn;
$kon = new koneksi();
$conn = $kon->bukaKoneksi();
$params = array();
$query = "EXEC dbo.RptSPJ_Pengeluaran '2013','1','1','1','0','1','1'";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$rs_test = sqlsrv_query($conn, $query, $params, $options);
if ($rs_test != NULL) {
$num_rows = sqlsrv_num_rows($rs_test);
echo $num_rows;
}
else {
echo 'wrong';
}
if i echo the query and execute it on sql server, it shows my data
is there anything wrong?
please help me
thank you

PHP using PDO to store session in DB doesnt produce the errors i expected

SOLVED :
answer is in the 2nd post
i try to store session in DB using PDO, but it doesn't produce errors i expected, please read my code.
here's the code for my session handler class:
class MySessionHandler implements SessionHandlerInterface
{
protected $conn = NULL;
public function open($savePath, $sessionName)
{
if(is_null($this->conn))
{
$dsn = 'mysql:host=localhost;dbname=php_advanced';
$username = 'root';
$password = 'password';
try
{
$this->conn = new PDO($dsn, $username, $password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in open function ' . $e->getMessage());
}
}
return TRUE;
}
public function close()
{
echo '<p>close</p>';
$this->conn = NULL;
return TRUE;
}
public function read($id)
{
echo '<p>read</p>';
$query = 'SELECT data FROM session_table WHERE session_id = :id';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->execute();
// Kalo query berhasil nemuin id..
if($pdo->rowCount() == 1)
{
list($sessionData) = $pdo->fetch();
return $sessionData;
}
return FALSE;
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in read function => ' . $e->getMessage());
}
}
public function write($id, $data)
{
echo '<p>write</p>';
$query = 'REPLACE INTO session_table(session_id, data) VALUES(:id, :data)';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->bindValue(':data', $data);
$pdo->execute();
// return the value whether its success or not
return (bool)$pdo->rowCount();
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in write function => ' . $e->getMessage());
}
}
public function destroy($id)
{
echo '<p>destroy</p>';
$query = 'DELETE FROM session_table WHERE session_id = :id LIMIT 1';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->execute();
$_SESSION = array();
return (bool)$pdo->rowCount();
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in destroy function => ' . $e->getMessage());
}
}
public function gc($maxLifeTime)
{
echo '<p>garbage collection</p>';
$query = 'DELETE FROM session_table WHERE DATE_ADD(last_accessed INTERVAL :time SECOND) < NOW()';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':time', $maxLifeTime);
$pdo->execute();
return TRUE;
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in gc function => ' . $e->getMessage());
}
}
}
$SessionHandler = new MySessionHandler();
session_set_save_handler($SessionHandler);
session_name('my_session');
session_start();
i remove the session_write_close on purpose. This probably sounds stupid, but i want to get the session error to learn more..
here's session script(using the book's code):
require('session_class.php');
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DB Session Test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
// Store some dummy data in the session, if no data is present:
if (empty($_SESSION)) {
$_SESSION['blah'] = 'umlaut';
$_SESSION['this'] = 3615684.45;
$_SESSION['that'] = 'blue';
// Print a message indicating what's going on:
echo '<p>Session data stored.</p>';
} else { // Print the already-stored data:
echo '<p>Session Data Exists:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
}
// Log the user out, if applicable:
if (isset($_GET['logout'])) {
session_destroy();
echo '<p>Session destroyed.</p>';
} else { // Otherwise, print the "Log Out" link:
echo 'Log Out';
}
// Reprint the session data:
echo '<p>Session Data:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
// Complete the page:
echo '</body>
</html>';
// Write and close the session:
// session_write_close() <<<<<--- I REMOVE THIS ON PURPOSE TO GET ERROR
?>
but i dont get any error, then i try to use book's mysqli script to connect db and it produces error i expected because i removed the session_write_close()..
can anyone explain why if im using PDO it doesn't generate error? i'm even dont use
register_shutdown_function('session_write_close');
in my session class destructor (on purpose)
NOTE : I'm doing this on purpose because i want to learn more.
the error im expecting is like when im using mysqli connection(connection closed by php at the end of script then session try to write and close but no connection available) :
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 66
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 66
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 67
Warning: mysqli_close() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 33
update 1
i recently figured it out that mysqli needs database connection everytime it uses mysqli_real_escape_string() and mysqli_query and because of but what im thinking is my pdo also needs db connection when the script ends -> db connection closed -> MySessionHandler will try to write and close, but there's no db connection since pdo has been closed by php, but no error produced..
update 2
i just tried to pass session_set_save_handler function callback and it produces the errors
<?php
$conn = NULL;
function open_session()
{
echo '<p>open session</p>';
global $conn;
$_dsn = 'mysql:host=localhost;dbname=php_advanced';
$_username = 'root';
$_password = 'password';
$conn = new PDO($_dsn, $_username, $_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return TRUE;
}
function close_session()
{
echo '<p>close session</p>';
global $conn;
$conn = NULL;
return TRUE;
}
function read_session($sid)
{
echo '<p>read session</p>';
global $conn;
$query = 'SELECT data FROM session_table WHERE session_id = :sid';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->execute();
if($pdo->rowCount() == 1)
{
list($session_data) = $pdo->fetch();
echo '<pre>';
print_r($session_data);
echo '</pre>';
return $session_data;
}
else
{
return '';
}
}
function write_session($sid, $data)
{
echo '<p>write session</p>';
global $conn;
$query = 'REPLACE INTO session_table(session_id, data) VALUES(:sid, :data)';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->bindValue(':data', $data, PDO::PARAM_STR);
$pdo->execute();
return $pdo->rowCount();
}
function destroy_session($sid)
{
echo '<p>destroy session </p>';
global $conn;
$query = 'DELETE FROM session_table WHERE session_id = :sid';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->execute();
// clean the session array;
$_SESSION = array();
return (bool)$pdo->rowCount();
}
function clean_session($expire)
{
echo '<p>clean session</p>';
global $conn;
$query = 'DELETE FROM session_table WHERE DATE_ADD(last_accessed, INTERVAL :expire SECOND) < NOW()';
$pdo = $conn->prepare($query);
$pdo->bindValue(':expire', $expire, PDO::PARAM_INT);
$pdo->execute();
return $pdo->rowCount();
}
session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session');
session_name('my_session');
session_start();
but still when im passing MySessionHandler class , it doesn't produce error because of no connection.
SOLUTION
sorry guys my mistake actually its a pretty easy answer why MySessionHandler class doesnt produce error wihtout session_write_close() in the end of script,
session_set_save_handler() by default will register session_write_close() to register_shutdown_function()
so if u want to make your own shutdown function for session then use :
session_set_save_handler($SessionClass, FALSE) , if u do this then u must provide session_write_close() in your class destructor
source : http://php.net/manual/en/function.session-set-save-handler.php
thanks for the tips and your attention

Categories