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.

Recommended Answers

All 5 Replies

Member Avatar for diafol

you could do an intval() on the input?

check this:

<?php
$int = '0001';
echo intval($int);
?>
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,

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);}

if($val1=='0')
{

echo 'Select values higher than 0';

}

Thanks for the solutions guys :)

Member Avatar for diafol

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 
}else{
    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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.