Different hash comes out with fn_md5 - php

so i have a very weird issue that its been quite sometime now and am still figuring out why it is is. i have a function in sql server called fn_md5 that accepts 2 parameters and then return it as a varbinary.
but if the function is called via a the php script in my web, the hash is different when you directly call it from the ssms, and all of my ideas are out anymore. all i know is that the fn_md5 function when called directly in the ssms outputs the correct hash that i want it to be.
soo this is my fn_md5 function:
USE [master]
GO
/****** Object: UserDefinedFunction [dbo].[UFN_MD5_ENCODEVALUE] Script Date: 5/17/2022 4:41:16 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ЗФјцён : UFN_MD5_ENCODEVALUE()
-- і»їл : ЖЇБ¤№®АЪї­°ъ АОµ¦Ѕєё¦ АМїлЗПї© MD5 °ЄА» »эјє
ALTER FUNCTION [dbo].[fn_md5]
(
#btInStr VARCHAR(10),
#btInStrIndex VARCHAR(10)
)
RETURNS VARBINARY(16)
AS
BEGIN
DECLARE #btOutVal VARBINARY(16)
EXEC master..XP_MD5_EncodeKeyVal #btInStr, #btInStrIndex, #btOutVal OUT
RETURN #btOutVal
END
and this is my php script:
$xodbc_connect = odbc_connect('Driver={ODBC Driver 17 for SQL Server};SERVER=WIN-6QBM0ALD4G1\SQLEXPRESS', 'sa', 'superpasszz');
$statement = "select [dbo].fn_md5('passpass', 'useruser')";
$exec = odbc_exec($xodbc_connect, $statement);
$result = odbc_result($exec, 1);
$password = $result;
//var_dump($password);
# insert data
$data = array(
'username' => $username,
'password' => $password,
'name' => $username,
'serial' => $this->_defaultAccountSerial,
'email' => $email
);
# query
$query = "INSERT INTO "._TBL_MI_." ("._CLMN_USERNM_.", "._CLMN_PASSWD_.", "._CLMN_MEMBNAME_.", "._CLMN_SNONUMBER_.", "._CLMN_EMAIL_.", "._CLMN_BLOCCODE_.", "._CLMN_CTLCODE_.") VALUES (:username, :password, :name, :serial, :email, 0, 0)";
now if i do this script in the ssms:
select [dbo].fn_md5('passpass', 'useruser');
it will give me this, which should be the correct hash:
0x0634DF7B99E2CF2344C3362F8CB76729
but if i use the registration process via my web it will give me this instead:
0xE5E892FA86C13BB1DF93630458E7DC31
the more weirder is that i cannot see what is wrongg and my head is going to blow. am still constantly learning both languages please bare with me and i hope you can help me out :<

Related

MySQL returning incorrect row with PDO

I am relatively new to MySQL and PHP, so bear with me. The following code:
$query = $pdo->prepare("SELECT `id` FROM `Logins` WHERE `username`=:u AND `hash`=SHA2(CONCAT(salt,:p),512)");
$id = $query->execute([
'u' => $_POST['user'],
'p' => $_POST['pass']
]);
seems to always return 1 for the id, no matter what username or password is put into the form, whether it's valid for id 3 or completely invalid. This makes me think it's an error from MySQL or something, but the above command works when I use it directly in a connection to the MySQL server.
I have verified that the data is correct from the form and PDO doesn't throw any errors with this, so maybe this isn't the code doing it, but I'm not sure what else it could be. The rest of the PHP file is just a login screen html, which has worked in the past, and the stuff to create the connection, which also seems to work.
Thanks in advance.
execute returns true or false signifying whether the query succeeded or not.
In order to get the id back from the query, you'll need to fetch it. E.g.:
$query = $pdo->prepare("SELECT `id` FROM `Logins` WHERE `username`=:u AND `hash`=SHA2(CONCAT(salt,:p),512)");
$success = $query->execute([
'u' => $_POST['user'],
'p' => $_POST['pass']
]);
if ($success) {
$result = $query->fetch(PDO::FETCH_ASSOC);
$id = $result['id'];
}

Oracle procedure does't executes calling from PHP

I'm facing with problem executing Oracle Procedure from PhP. Actually, I am using Doctrine to execute it.
What is interesting is the fact of any other Queries can be executed/fetched, but procedures.
Below, you can find the codes I managed to use, this Select works wonderfully:
$connection = $this->getApplication()->getDataSourceManager()->getEntityConnection();
$stmt = $connection->prepare("SELECT SYSDATE FROM DUAL"); //or any other select works nice
$stmt->execute();
However, any procedure wont work, this is one of them:
$connection = $this->getApplication()->getDataSourceManager()->getEntityConnection();
$stmt = $connection->prepare("call prc_nutr_values('$cdfil', '$cdserice', '001', '0000000036', 'S', '$selectdt', '$selectdt')");
$stmt->execute();
The procedure above, doesn't surge any changes in DB. It doesn't his procedure
Error found!
The main problem was that PhP doesn't throw any error (I don't know why. However, I made the transaction in a different way, creating a clean new connection and it threw the error, as following:
$entitiesPath = realpath(__DIR__."/../src/");
$isDevMode = true;
$entity_metadata_config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array($entitiesPath), $isDevMode);
$connection_params = array(
'driver' => 'oci8',
'user' => 'user',
'password' => 'pwd',
'host' => 'IP',
'port' => 'port',
'dbname' => 'ORCL',
);
$entity_manager = \Doctrine\ORM\EntityManager::create($connection_params, $entity_metadata_config);
$conn=$entity_manager->getConnection();
$sql ="CALL FUNCTION_NAME('$param1', '$param2', '$param3', '$param4', '$param5', $param6, $param7)";
$outputMeta = $conn->exec($sql);
Connecting through this way, I could receive the error detailed:
it was $param6 and $param7 (non-formatted dates)
to solve this...
I just replace $param6 and $param7 with TO_DATE('$param6', 'DATE-FORMAT') and TO_DATE('$param7', 'DATE-FORMAT')
where 'DATE-FORMAT' is the used date format ('MM/DD/YYYY', or other used date formats)

Accessing MySQL stored procedure output in Zend Framework 2

I have a simple MySQL stored procedure that takes two parameters and inserts a row into a table. I can execute it just fine from Zend Framework 2 like this:
$result = $this->dbAdapter->query('CALL sp_register_user(?, ?)', array('username', 'password'));
I can also access any result sets returned from my stored procedure.
What I want now is to have an output value from my stored procedure as a third parameter, so something like this:
DELIMITER //
CREATE PROCEDURE sp_register_user(IN username VARCHAR(50), IN password VARCHAR(128), OUT code INTEGER)
NOT DETERMINISTIC
COMMENT 'Registers a user'
BEGIN
INSERT INTO user VALUES (username, password);
SET code = 123;
END //
The question is how I can access this output variable from PHP (ZF2). I have only been able to find examples of how to do it directly through PDO, which I am using. Example 4 on this page shows how to do it through PDO directly. My concern is that if I use the PDO object directly, I am losing some abstractions and I am thereby assuming that I will always be using PDO.
Still, I tried to make it work with PDO directly, like this:
$username = 'my_username';
$password = 'my_password';
$code = 0;
$stmt = $this->dbAdapter->createStatement();
$stmt->prepare('CALL sp_register_user(?, ?, ?)');
$stmt->getResource()->bindParam(1, $username);
$stmt->getResource()->bindParam(2, $password);
$stmt->getResource()->bindParam(3, $code, \PDO::PARAM_INT, 3);
$stmt->execute();
However, I get an error saying that the statement could not be executed.
The ideal solution would be one where I could make use of ZF2's abstraction layer, but any ideas on how to access the output parameter are welcome and appreciated.
this must work, because i m using it :
$str = "DECLARE #Msgvar varchar(100);DECLARE #last_id int;
exec CallEntry_Ins $CallLoginId,".$this->usrId .",#Msg = #Msgvar OUTPUT,#LAST_ID = #last_id OUTPUT;
SELECT #Msgvar AS N'#Msg',#last_id AS '#LAST_ID'; ";
$stmt = $db->prepare($str);
$stmt->execute();
$rtStatus = $stmt->fetchAll();
$rtStatus[0]["#LAST_ID"] //accessing Op para

Inserting data to MySQL via PDO, trying to include a timestamp along with data using an array - getting errors?

I have a set of data stored in variables, and I want a page to write that data to a MySQL database, I'd like to include the time of insertion, here's my method:
$username="username"; $password="password";
try {
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO table01
(
Time,
variable1,
variable2,
)
VALUES
(
:Time,
:variable1,
:variable2,
)');
$stmt->execute(array(
':Time' => NOW(),
':variable1' => $var1,
':variable2' => $var2,
));
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
On loading this page, the css is stripped from the page, I get a sort of garbled output of what the page should look like (white screen, plain text some images), additionally on checking the database nothing has been written to it.
Without the Time variable in there, all works perfectly.
Any advice? Thanks in advance
Sorry, took me moment to re-read that. You are using the nysql function now() to do the work, and as such you don't need to set it as a param and therefore don't need to bind it at all. Just write it into your query.
$stmt = $pdo->prepare('INSERT INTO table01
(
Time,
variable1,
variable2,
)
VALUES
(
now(),
:variable1,
:variable2,
)');
$stmt->execute(array(
':variable1' => $var1,
':variable2' => $var2,
));
Edit Re Comment
The : in a query denotes it as a parameter in a prepared query. That means you must then bind it via the bind() command. However if you are inserting the data from within the database (such as using a built in function, or pulling the data in from another row) you don't need to declare it in the initial query with : and therefore you can't pass it to the query in the bound params array.

Newbie Question: PDO and MYSQL INSERT Query problem

I'm attempting to be more secure and start using PDO and prepared statements. This had been recommended to me and I've read up on these two websites:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
and
http://webdevrefinery.com/forums/topic/1272-your-mysql-code-sucks
I've hit a brick wall and I can't understand why the following doesn't work. I am trying to insert a row (to log a 404 error). I have read up about named and unnamed placeholders and I think the named placeholder method will be easier to maintain. I've also tried using "try" and "catch" for the first time. All of this is completely new to me, so please be kind! I don't get any errors but the code doesn't update the database- I get zero rows returned.
Here is the code:
$referer = $_SERVER['HTTP_REFERER'];
$domainName = "http://domain.com";
$_dtNow = date("d-m-Y H:i:s");
$_referer = $domainName.$_SERVER['REQUEST_URI'];
$_thisPage = $domainName.$url;
$_ip = $_SERVER['REMOTE_ADDR'];
$_host = $_SERVER['REMOTE_HOST'];
if(isset($_SERVER['HTTP_USER_AGENT'])) {$_ua = $_SERVER['HTTP_USER_AGENT'];} else {$_ua = "unset";}
$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = 'databaseName';
$username = 'username';
$password = 'password';
// Construct the DSN, or "Data Source Name". Really, it's just a fancy name
// for a string that says what type of server we're connecting to, and how
// to connect to it. As long as the above is filled out, this line is all
// you need :)
$dsn = "mysql:host=$host;port=$port;dbname=$database";
try {
// Connect!
$db = new PDO($dsn, $username, $password);
$data = array(
'dateTime' => $_dtNow,
'referer' => $_referer,
'page' => $_thisPage,
'ip' => $_ip,
'host' => $_host,
'ua' => $_ua
);
$statement = $db->prepare("INSERT INTO 404s (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Are you sure of the table name is 404s it sound like an incorrect identifier.
INSERT INTO 404s (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)
Try :
INSERT INTO `404s` (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)
Use backquote around `404s`
Note
Keep in mind that construct such as :
create table `404` ( `33` integer);
Are valid .
When you build complex request use of ` is very useful to avoid some kind of painful SQL errors especially when you format request from an introspection algorithm.
Like table, columns and database have to be protected.
In addition to #Dave Kiss, the SQL statement has a small typo at 'value'. It should be 'VALUES'.
INSERT INTO 404s (dateTime, referer, page, ip, host, ua) VALUES (:dateTime, :referer, :page, :ip, :host, :ua)
Maybe that is all.
BTW: Using leading numbers in identifiers (like your table name 404s) is bad style. You may use them, but you have to but the table name in backticks:
INSERT INTO `404s` (dateTime, referer, page, ip, host, ua) VALUES (:dateTime, :referer, :page, :ip, :host, :ua)
Resources:
http://dev.mysql.com/doc/refman/5.6/en/insert.html
http://dev.mysql.com/doc/refman/5.6/en/identifiers.html
Try adding the colons to your keys in the data array.
/* Execute a prepared statement by passing an array of insert values */
$data = array(
':dateTime' => $_dtNow,
':referer' => $_referer,
':page' => $_thisPage,
':ip' => $_ip,
':host' => $_host,
':ua' => $_ua
);
$statement = $db->prepare("INSERT INTO 404s (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)");
$statement->execute($data);

Categories