phpmysqlsqlzerofill

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


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.


Solution

  • 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)