Jump to content
Larry Ullman's Book Forums

Recommended Posts

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

				}
			}

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...