I am using the following code for reading a String from a mysql function:
<?php
print_r($_POST);
try {
$dbh = new PDO("mysql:dbname=mydb;host=myhost", "myuser", "mypass" );
$value = $_POST['myLname'];
print $value ;
//print $dbh ;
$stmt = $dbh->prepare("CALL check_user_exists(?)");
$stmt->bindParam(1, $value, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 50);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
echo "PDO connection object created";
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
This is not reading the returned value , however if I read the value usimg mysql* like :
<?php
$dbhost='myhost';
$dbuser='mydb';
$dbpassword='mypass';
$db='mydb';
$con=mysql_connect($dbhost, $dbuser, $dbpassword) or die("Could not connect: " . mysql_error()); ;
mysql_select_db($db,$con);
$qry_str = "select check_user_exists('chadhass#hotmail.com')";
$rset = mysql_query($qry_str) or exit(mysql_error());
$row = mysql_fetch_assoc($rset);
mysql_close($con);
foreach($row as $k=>$v)
{
print $k.'=>'.$v;
}
?>
This returns correctly . ANy idea wha am I missing ?
function :
CREATE
FUNCTION `check_user_exists`(in_email
VARCHAR(100)) RETURNS varchar(1) CHARSET utf8
READS SQL DATA
BEGIN
DECLARE vcount INT;
DECLARE vcount1 INT;
SELECT COUNT(*) INTO vcount FROM USERS
WHERE USEREMAIL=in_email;
IF vcount=1 then
SELECT COUNT(*) INTO vcount1 FROM USERS
WHERE USEREMAIL=in_email and isactive=1;
if vcount1=1 then
return('1');
else
return('0');
end if;
ELSE
RETURN('2');
END IF;
END
code that worked for PDO ::
<?php
//print_r($_POST);
try {
$dbh = new PDO(PDO("mysql:dbname=mydb;host=myhost", "myuser", "mypass" );
$value = $_POST['myLname'];
$result = $dbh->prepare("select check_user_exists(?) as retval");
$result->bindParam(1, $value, PDO::PARAM_STR, 2);
$result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
$result->execute();
$obj = $result->fetch();
print($obj->retval);
echo "PDO connection object created";
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
The reason is, you aren't fetching the results from the query.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Related
I got this simple PHP code to print a Column from a database and it isn't working unfortually. Any ideas on what to do right?
I've tried to work on the while loop I have in the if statement but no luck
What im trying to get array to print like :
<?php
$input = $_POST['input'];
$servername = "localhost";
$username = "hawk_manager";
$password = "hawk_eyes";
try {
$pdo = new PDO("mysql:host=$servername;dbname=HawkCenter", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
if ($input == "RoomNumber") {
$query = 'SELECT RoomNumber FROM rooms';
$statement=$pdo->prepare($query);
$statement->execute();
$roomnumbers=$statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
while( $roomnumbers=$statement->fetchAll(PDO::FETCH_ASSOC)){
echo "{$statement['RoomNumber']}";
}
}
$conn = null;
?>
You are doing it wrong, it should be
1. Selecting multiple rows
$data = $pdo->query("SELECT RoomNumber FROM rooms")->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo $row['RoomNumber ']."<br />\n";
}
2. Prepared Statements::
$stmt = $pdo->prepare("SELECT RoomNumber FROM rooms WHERE id=?");
$stmt->execute([$id]);
$user = $stmt->fetch();
OR
$stmt = $pdo->prepare("$stmt = $pdo->prepare("SELECT RoomNumber FROM rooms LIMIT :limit, :offset");
$stmt->execute(['limit' => $limit, 'offset' => $offset]);
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row['RoomNumber']."<br />\n";
}
I'am trying to perform simple SELECT query from PHP PDO to MSSQL database. While query contains cyrillic symbols in WHERE condition, result is empty (if not contains, result return successfully). What can I do to correct query?
putenv('ODBCSYSINI=/etc/');
putenv('ODBCINI=/etc/odbc.ini');
$configODBC = config('database.odbc');
try {
$this->pdo = new PDO('odbc:'. $configODBC['default']['source'], $configODBC['default']['username'], $configODBC['default']['password']);
} catch (PDOException $e) {}
...
$statement = $this->pdo->prepare("SELECT * FROM [DB].[dbo].table WHERE policy_num LIKE '%cyrillic_symbols%'");
$result = $statement->execute();
if ($result) {
while ($out = $statement->fetch()) {
var_dump($out[0]);
}
}
PS. MSSQL version 2012. Data in UTF-8 encoding.
I'll post this as an answer, because it's too long for comment. UTF-8 all the way through, suggested by #RiggsFolly has all the answers. In your case, you need to convert values from CP-1251 from/to UTF-8 . I've made this simple test case, see if this will help you:
T-SQL:
CREATE TABLE CyrillicTable (
[CyrillicText] varchar(200) COLLATE Cyrillic_General_CI_AS
)
INSERT INTO CyrillicTable
(CyrillicText)
VALUES
('Понедельник'),
('Вторник')
PHP (file is UTF-8 encoded, using Notepad++):
<?php
# Connection info
$hostname = 'server\instance,port';
$dbname = 'database';
$username = 'uid';
$pw = 'pwd';
# Connection
try {
$dbh = new PDO("odbc:Driver={SQL Server Native Client 11.0};Server=$hostname;Database=$dbname", $username, $pw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server. ".$e->getMessage());
}
# Query
try {
echo "Query"."<br>";
$sql = "SELECT * FROM dbo.[CyrillicTable] WHERE CyrillicText LIKE '%".iconv('UTF-8', 'CP1251', 'онед')."%'";
$stmt = $dbh->query($sql);
while ($row = $stmt->fetch( PDO::FETCH_ASSOC )) {
foreach($row as $name => $value) {
echo $name.": ".iconv('CP1251', 'UTF-8', $value)."<br>";
}
}
echo "<br>";
} catch( PDOException $e ) {
die( "Error executing query: ".$e->getMessage());
}
$stmt = null;
# Query
try {
echo "Prepared query"."<br>";
$sql = "SELECT * FROM dbo.[CyrillicTable] WHERE CyrillicText LIKE ?";
$stmt = $dbh->prepare($sql);
$text = 'орни';
$text = "%$text%";
$text = iconv('UTF-8', 'CP1251', $text);
$stmt->bindParam(1, $text, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch( PDO::FETCH_ASSOC )) {
foreach($row as $name => $value) {
echo $name.": ".iconv('CP1251', 'UTF-8', $value)."<br>";
}
}
echo "<br>";
} catch( PDOException $e ) {
die( "Error executing stored procedure: ".$e->getMessage());
}
$stmt = null;
# End
$dbh = null;
?>
Notes:
Consider using parameterized query.
I'm a beginner in PHP programming.
I have an SP in SQL Server with input, output and ReturnValue parameters that returns data from an sample table.
CREATE PROCEDURE [dbo].[sp_PHP]
#in1 int, #in2 int, #out3 int OUTPUT
WITH EXEC AS CALLER
AS
SET #out3 = #in1 * #in2
SELECT * FROM PHP
RETURN #in1 + #in2
This is my PHP code
<?php
try
{
$conn = new PDO("sqlsrv:Server=xxxxx,1433;Database=xxxxxx", "xx", "xx");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $e)
{
die(print_r($e->getMessage()));
}
$query = '{? = CALL sp_PHP(?, ?, ?)}';
$stmt = $conn->prepare($query);
$returnVariable = -1;
$inputVariable1 = 18;
$inputVariable2 = 24;
$outputVariable3 = -1;
$stmt->bindParam(1,$returnVariable, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, 100);
$stmt->bindParam(2,$inputVariable1, PDO::PARAM_INT);
$stmt->bindParam(3,$inputVariable2, PDO::PARAM_INT);
$stmt->bindParam(4,$outputVariable3, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, 100);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row) {
echo $row['PHP_ID'].' '.$row['PHP_Char'].'<br>';
}
echo '<hr>';
echo 'Return value: '.$returnVariable.'<br>';
echo 'Output parameter: '.$outputVariable3.'<br>';
?>
If I remove the line in the SP
SELECT * FROM PHP
and don't read the data received in PHP with following code
$results = $stmt->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row) {
echo $row['PHP_ID'].' '.$row['PHP_Char'].'<br>';
}
I receive the correct values of $returnVariable (42) and $outputVariable3 (432).
But if I read (and show) the data read from the SP, $returnVariable and $outputVariable3 are equal to -1 (the assigned value)
I wanto to read output parameter, ReturnValue and data at the same time.
Is it possible? Where am I wrong?
Thanks!!
Solution:
The value of the output (or input/output) parameter is accessible when you consume all results returned by the stored procedure (PDO and not PDO versions). In your case you need to move throw resultsets with PDOStatement::nextRowset to get the values for the output parameters.
Example:
I've reproduced your example and next code works for me.
<?php
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
try {
$sql = "{? = CALL sp_PHP(?, ?, ?)}";
#$sql = "EXEC ? = sp_PHP(?, ?, ?)";
$stmt = $conn->prepare($sql);
$returnVariable = -1;
$inputVariable1 = 18;
$inputVariable2 = 24;
$outputVariable3 = -1;
$stmt->bindParam(1, $returnVariable, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->bindParam(2, $inputVariable1, PDO::PARAM_INT);
$stmt->bindParam(3, $inputVariable2, PDO::PARAM_INT);
$stmt->bindParam(4, $outputVariable3, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->execute();
do {
echo 'Result set:'."<br>";
while ($row = $stmt->fetch( PDO::FETCH_ASSOC) ){
print_r($row)."<br>";
}
echo "<br>";
echo "<br>";
} while ($stmt->nextRowset());
} catch( PDOException $e ) {
die( "Error executing query" );
}
$stmt = null;
$conn = null;
echo 'Stored procedure return value: '.$returnVariable."</br>";
echo 'Stored procedure output parameter: '.$outputVariable3."</br>";
?>
I have pleasure to work with legacy PHP application using SQL Server via PDO.
How in PHP can I retrieve return value of stored procedure which is using RETURN statement as output channel?
Example procedure
CREATE PROCEDURE [dbo].[mleko_test]
#param INT
AS
BEGIN
RETURN #param * 3;
END
GO
If possible, I would prefer to not modify procedure.
I am aware that there are similar questions, but they don't cover this case
Get RETURN value from stored procedure in SQL
Get Return Value from SQL Stored Procedure using PHP
Execute stored procedure like this: "exec ?=mleko_test(?)".
Working example:
<?php
#------------------------------
# Connection info
#------------------------------
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
#------------------------------
# With PDO
#------------------------------
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $e ) {
die ( "Error connecting to SQL Server" );
}
try {
$sql = "exec ? = mleko_test (?)";
$param = 3;
$spresult = 0;
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $spresult, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->bindParam(2, $param);
$stmt->execute();
} catch ( PDOException $e ) {
die ( "Error connecting to SQL Server" );
}
$stmt = null;
$conn = null;
echo 'Stored procedure return value (with PDO): '.$spresult."</br>";
#------------------------------
# Without PDO
#------------------------------
$cinfo = array (
"Database" => $database,
"UID" => $uid,
"PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if ( $conn === false )
{
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
$sql = "exec ? = mleko_test (?)";
$param = 3;
$spresult = 0;
$params = array(
array(&$spresult, SQLSRV_PARAM_OUT),
array($param, SQLSRV_PARAM_IN),
);
$stmt = sqlsrv_query($conn, $sql, $params);
if ( $stmt === false ) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
echo 'Stored procedure return value (without PDO): '.$spresult."</br>";
?>
Notes:
Tested with PHP 7.1.12 and PHP Driver for SQL Server (pdo_sqlsrv version 4.3.0+9904).
I came to a solution using multi-query but #Zhorov answer is cleaner
<?php
$connection = new PDO($connectionString, $DB_USERNAME, $DB_PASSWORD);
$stmt = $connection->prepare(<<<SQL
DECLARE #a INT;
EXEC #a = mleko_test :in
SELECT #a AS result;
SQL
);
$stmt->execute([":in" => 123]);
echo $stmt->fetch()["result"] . "\n";
I had to change
$sql = "exec ?=mleko_test(?)";
for
$sql = "{?=call mleko_test(?)}";
I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>