I need some help with this one guys. I made a small script that inputs only numbers with 4 digits. Now the trick is that I need to input only numbers higher than 0 (ranged from 1 to 9999). Easy enough, I said, if I only make this rule: $val<=0. But the problem here is that if I input the number 01 or 001 or 0001, it is submitted to the query. I could do this: $val<=1, but then I would need the number 1 to be submitted so this didn't get me very far. Is there a way around this!? Thanks.

6 Years
Discussion Span
Last Post by diafol

you could do an intval() on the input?

check this:

$int = '0001';
echo intval($int);

Edited by diafol: n/a

if($val > 0 && $val <= 9999){
$val = str_pad($val, 4, "0", STR_PAD_LEFT);
//bla bla bla submit to query

unsure about why,
sql will strip the leading zeros and process only the value of the column anyway,
not valid as a verification tool, to ensure no lost chars once the post is already made
to verify that 4 digits have been input a javascript on the browser may be more valuable validating the length of the input field (dont use this I dont thing it wourl work, its an idea

<input name='val' onchange="JAVASCRIPT:if(self.value.length = 4) { document.getElementById('submit').disabled=false}else{document.getElementById('submit').disabled=true}">
<input id='submit' type='submit' disabled='disabled'>

or I might be totally missing the ball,

Edited by almostbob: n/a


Ok I found the answer. Because if I input 001, it is considered as 0.001 so the solution is to use the round function like this:

$val1 = $_POST['quantity1'];

if($val1 != ''){$val1 = round($val1);}


echo 'Select values higher than 0';


Re-reading the question, you need input validation.

$x = intval($_POST['field']);
$options = array(
    'options' => array('min_range' => 1,'max_range' => 9999)
if (filter_var($x, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "$x is valid between 1 and 9999";
    //do sql query 
    echo "$x is not a valid integer";

intval() sets all text inputs to 0, so text inputs will fail anyway (< 1). However, it has unexpected results sometimes. 0034 and similar numbers are fine (34). Floats are truncated at the decimal point (3.98 = 3). Mixed numbers/text (78shywej = 78), (shy45 = 0).
You can use a js validator to *try* and ensure that an integer is passed. You still have to validate server-side though.

I've never used str_pad - looks interesting. Shall fiddle with it. Thanks.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.