MySQL thinks that '2015123' is different from '02015123'

58 views Asked by At

I am trying yto select a column from my DB where the stockid is equal to the inputted stockid from the user. This is my code below:

    $stockid = $_POST['item'];

    //get the current balance of the selected item
    $sqlbal = "SELECT * FROM db.nonperi where nonperi.stockid = '$stockid'";
    $resultbal = $conn-> query($sqlbal);
    if ($resultbal-> num_rows > 0)
    {
        while ($row = $resultbal -> fetch_assoc()) 
        {
            $currbal = $row['bal'];
        }
    }

I know that the code is correct, however, upon checking in DB, the stockid is equivalent to '2015123' but the $stockid that was posted in this page for this code is '02015123'. That is why it returns nothing.

Is there any code/way to force sql to see them as the same/equal? I appreciate any help about this.

2

There are 2 answers

4
Nitek On BEST ANSWER

You are passing the stockid as a string (but want it to behave like an integer). Try

$stockid = intval($_POST['item']);
$sqlbal = "SELECT * FROM db.nonperi where nonperi.stockid = $stockid";

(That also secures your code to prevent SQL injection)

3
Aman Aggarwal On

You can trim leading 0 (zeros) to check the stockId.

SELECT TRIM(LEADING '0' FROM '02454545') 

You command should be:

"SELECT * FROM db.nonperi where nonperi.stockid = TRIM(LEADING '0' FROM '$stockid')";