PaulB12345 PaulB12345 - 6 months ago 37
PHP Question

PHP/HTML - Setting a cap on a input using a variable in php?

I'm looking for a way to limit the amount of an input like this:

<?php
$Maximum = 10;
?>
<form action="" method="post">
Quantity: <input type="number" value="0" min="0" max=$Maximum step="0" data-number-to fixed="2" data-number-stepfactor="100" name="Quantity" />
<input type="submit">
</form>


But the Maximum would change depending on the database so it could be anywhere from 1 to 1000+ etc. Is there any possible way I could do this just limiting in the HTML or would I have to just use a PHP
if
statement after the number is submitted?

Answer

Assuming you are getting $maximum value from the DB. You can try to use maxlength attribute. No need to use JS. If you wanna be on the secure side that you gotta do another check on server side with the if statement as you mentioned above.

Try this:

<?php $Maximum = 10; ?>
<form action="" method="post">
Quantity: <input type="number" value="0" min="0" maxlength="<?php echo $Maximum; ?>" step="0" data-number-to fixed="2" data-number-stepfactor="100"  name="Quantity" />
<input type="submit">
</form>

ref: http://www.w3schools.com/tags/att_input_maxlength.asp