grahamgr3 Posted July 13, 2015 Share Posted July 13, 2015 In the following code, (I know the if statement isn't complete, I am referring to the part before it) I am unclear why (int) is used, after using php for over a year I have never really understood when I should use (int). Is it to make sure the returned number is changed from a decimal to an integer?? Please explain why it is used in this block of code. It is from chapter 6 in the ipn.php script. if (mysqli_num_rows($r) === 0){ $uid = (isset($_POST['custom'])) ? (int) $_POST['custom'] : 0; $status = escape_data($_POST['payment_status'], $dbc); $amount = (int) ($_POST['mc_gross'] * 100); $q = "INSERT INTO orders (user_id, transaction_id, payment_status, payment_amount) VALUES ($uid, '$txn_id', '$status', $amount)"; $r = mysqli_query($dbc, $q); if (mysqli_affected_rows($dbc) === 1){ } } Link to comment Share on other sites More sharing options...
Larry Posted July 14, 2015 Share Posted July 14, 2015 You use (int)--or any other typecasting function--whenever you want to force data from one type to another. PHP is loosely typed, which means it's not a problem to use a string as an integer, for example. But in the database query, using the wrong type can be problematic. In this particular case, $_POST['custom'] comes from a form, which means it's always going to be a string, even if it's a string with a value of "2". The same goes for the amount. The uses of (int) convert these strings to integers for more precise usage (in the multiplication and in the query). Link to comment Share on other sites More sharing options...
Recommended Posts