Search code examples
phpsqlsql-serversql-server-2012sqlsrv

Check if string in input box is equal to varbinary(max) in SQL SERVER, PHP | SQL SERVER 2012


I'm having a problem with my login page.

I'm converting my password from string to varbinary(max), my problem now is how can I compare or verify if my string inputted for logging in is equal to the stored data in the table.

Example.

The value of my password before being converted is 12345. After being converted via CONVERT(varbinary(max),'12345'), the data now reflects as 0x3132333435.

How will I be able to verify if my inputted password (12345) in my input box is similar to the value if converted into varbinary(max) 0x3132333435?

I'm using SQL SERVER 2012, XAMPP, and SQLSRV for conncetion.

Thank you so much in advance.

This is my login.php

<?php
    session_start();
    include 'includes/conn.php';

    if (isset($_POST['login'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        $sql = "
SELECT username,cast(password as varchar(max)) as password 
FROM usermasterfile 
WHERE username ='$username'";

        include 'query/sqlsrv_query-global.php';

        if (sqlsrv_num_rows($query) < 1) {
            $_SESSION['error'] = 'Cannot find account with the username';
        } else {
            $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC);
            if ($password == $row['password']) {
                $_SESSION['employeeidno'] = $row['employeeidno'];
            }
            else{
                $_SESSION['error'] = 'Incorrect password';
            }
        }
    }
    else{
        $_SESSION['error'] = 'Input credentials first';
    }

    header('location: index.php');
?>

EDIT: FIXED IT!

SELECT *,cast(password as varchar(max)) as maxpassword 
FROM usermasterfile 
WHERE username ='$username'";````

Solution

  • You can cast your varbinary back to varchar value as

    SELECT cast(0x3132333435 as varchar(max)) as varchar_value
    
    varchar_value
    -------------
    12345
    

    So, use the above casting in your code's comparison part.