Trying to get a query string into a variable but only if it's an integer.
Code is probably a bit more complicated than it should be but this is where I'm up to-
//get page number. default is 1. check is not empty and is a number
if (empty($_GET['pag'])) {$page = 1;}
else if (is_int($_GET['pag'])){$page = $_GET['pag'];}
else {$page = 1;}
Where am I going wrong?
You probably want is_numeric() instead - is_int() doesn't test to see if a string is a numeric string.
if (empty($_GET['pag'])) {$page = 1;}
else if (is_numeric($_GET['pag'])){$page = (int) $_GET['pag'];}
else {$page = 1;}
I would suggest, type cast the value to an integer:
$page = empty($_GET['pag']) ? 1 : (int) $_GET['pag'];
Although, if I remember well, type casting something that is not an integer will make it a 0, but you should check anyways if the $page is in between bounds before doing anything with it, because the user might as well type in ?pag0 in your URL.
$page = ((isset($_GET['pag']) && is_numeric($_GET['pag'])) ? (int)$_GET['pag'] : 1;
Related
For a variable like the following $p = $_GET['page']
In conditions like the following
if ($p > 0)
if ($p < 0)
if ($p >= 0)
if ($p <= 0)
if ($p == 0)
does it work same as
if (ctype_digit($p)){//Logic}
//or...
if (is_numeric($p)){//Logic}
My suggestion is pass in the right datatype for the job. So if you need number pass that to this code.
If you cannot control what is being passed in then check what it is first. This makes you take a second look when code starts to break. I would use is_numeric because it know negatives and floats unlike ctype_digit
is_numeric("-10"); //TRUE
ctype_digit("-10"); //FALSE
is_numeric("12.10"); //TRUE
ctype_digit("12.10"); //FALSE
So in the end you would want to do something like:
$p = $_GET['page'];
if(is_numeric($p)){
$p = (int)$p;
//Do stuff with an int
} else {
//Not sure what should happen here...
}
PHP is super flexible with casting for us but when it comes to trying to find a bug in your code it becomes hard to find when you act like everything is coming in good ie if($p>0){} seems like you know you have a number and I would keep looking elsewhere.
I am working on a project and in that project I have two objectives
I receive data from user
I check if the data sent by the user is an interger or in case is an integer, if is less than 1
So I wrote this code
<form action="" method="get">
<input type="text" name="quantity" value="2"/>
<input type="submit"/>
</form>
<?php
if (!is_int($_GET['quantity']) || $_GET['quantity'] < 1){
$_GET['quantity'] = 1;
}
echo $_GET['quantity'];
The problem, I am facing is that, the program always echo 1 even if the data is less than 1 or is not an integer at all.
Help me solve this problem please
Try replacing
if (!is_int($_GET['quantity']) || $_GET['quantity'] < 1){
with
$quantity = (int) $_GET['quantity'];
if ($quantity < 1) {...}
This casts it to an integer, and if not an integer, casts it as being assigned 0. Then it compares whether it is < 1 or not, and should have the desired result that you are looking for.
The problem is, 'quantity' is actually a string. So when you call
is_int($_GET["quantity"))
it will always return false, because it is of type string.
The easiest solution would be to convert 'quantity' to an int.
is_int((int) $_GET["quantity")
Hope this will help you
$quantity = $_GET['quantity'];
if (!is_numeric($quantity) || $quantity < 1)
{
$quantity = 1;
}
echo $quantity;
try this it will work
<?php
if (is_numeric($_GET['quantity']) || $_GET['quantity'] < 1){
$_GET['quantity'] = 1;
}
echo $_GET['quantity'];
You can just create a function to get the integer value of the input.
function strtonumber($string = "") {
$num = intval($string);
if ($num === 0) {
$num = preg_replace("/[^0-9]/", "", $string);
$num = intval($num);
}
return $num;
}
$quantity = strtonumber($_GET["quantity"]);
if ($quantity < 1) {
$quantity = 1
}
intval returns the integer value of the input.
echo intval("12ab"); // 12
but if the digits come after a letter, it returns 0.
echo intval("ab12"); // 0
In that case, to get the 12 from "ab12", we remove any non-digit character and get the integer value again.
The function will always return an integer so you don't need to check if the input is an integer or not.
I have checked a bunch of posts on stackoverflow and on articles on google but none of them were able to answer my question. Here is my code (i've simplified it instead of posting my code)
$first = 10;
$second = 0; //comes from db row count
$total = !is_int($first/$second) ? 0 : $first/$second;
problem is when i do this I keep getting the Division by zero error. I have a bunch and $second isnt always 0, it can be any number. But it does come out to 0 since the row counts for whatever query it comes out as 0. Is there a safe way of checking to see if $first can be divided by $second without giving an error? I have tried # before the !is_int and that just breaks all other statements.
Try this:
$total = ($second == 0) ? 0 : $first / $second;
You can't divide by 0 it is undefined. If you want to handle division by 0 just check if the divisor isn't equals to 0. Or a safer way, chack if it is a positive integer:
$first = 10;
$dbRowCount = dbFunction();
if ($dbRowCount > 0) {
$total = $first / $dbRowCount;
} else {
//Error handling
}
The ternary structure can accept more than one condition. and it will work just as any other if condition, and won't try the second condition if the first fails.
So, just add it
$total = ($first!==0 && $second!==0 && !is_int($first/$second)) ? 0 : $first/$second;
You might want to try checking if your $Second variable is 0.
Something like:
$First = 10;
$Second = $row['table_column'];
if ($Second == 0) {
echo "Oops this will be an error";
}
else
$First/$second = $me;
I am trying to send data from a database to an app based on what was send from the app to the server like so:
$search_bp=$_POST['search_bp'];
$search_trig = 0;
if(strcmp($search_bp,"1")==true){
//decisions that could set search_trig = 1;
//eg
if(strcmp($_POST['EStype'],'Event')){
if(strcmp($_POST['type'],'Any')==false){
if(strcmp($_POST['type'],$row["type"])==false){
$search_trig=1;//doesnt match specs
}
}
}
}
if($search_trig == 0){
$event["pid"] = $row["pid"];
$event["name"] = $row["name"];
$event["longitude"] = $row["longitude"];
$event["latitude"] = $row["latitude"];
$event["pavement"] = $row["pavement"];
$event["traffic"] = $row["traffic"];
$event["environment"] = $row["environment"];
$event["image_b64"] = $row["image_b64"];
$event["date"] = $row["date"];
$event["time"] = $row["time"];
$event["type"] = $row["type"];
// push single product into final response array
array_push($response["events"], $event);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
What is going wrong is that it strcmp($search_bp,"1") seems to always be false even though I am sending it as
params.add(new BasicNameValuePair("search_bp", Integer.toString(search_bp)));
Where I know search_bp=1, I just don't know too much about php so I'm pretty sure it is just my syntax.
Thank you in advance,
Tyler
strcmp returns an integer not a boolean.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Technically, you should simply be checking as if ($search_bp == "1") {
If we were to dissect your statement in php's loose type world you can see your mistake.
`strcmp` will return 0 because they do match.
0 = false
1 = true
so if(strcmp($search_bp,"1")==true){ solves to if(0==true){, then if(0==1){ which would not meet the condition.
Please Note That strcmp not return true or false:
It return as follow
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
You need to change something like below:
if(strcmp($search_bp,"1")==0){
//
}
In your case you can also use == operator.
Please Note : == only returns true or false, it doesn't tell you which is the "greater" string
I am trying to compare two values but when I do it does not appear to work. I know what the values are so it should be reporting true. Even worse, if I take either one of the variables out and put the number in it works.
$data = simplexml_load_file('xml/heroes/hero.xml')
or die("Error: Cannot create object");
$hme = $data->hes->he->maxen;
$hce = $data->hes->he->curen;
$hac = $data->hes->he->lastac;
echo $hce . ' should not be greater than ' . $hme;
if($hce > $hme){
echo 'should be working';
}
Outputs:
773 should not be greater than 20
I think your variable are like this
$hce = "773";
$hme = "20";
Before comparing them do intval
if(intval($hme)>intval($hce))
Cast your strings to integers:
$hme = (int)$data->hes->he->maxen;
$hce = (int)$data->hes->he->curen;
$hac = (int)$data->hes->he->lastac;
I think you took them as strings.I think you need to convert them to integer.
Simple function to do that:
int atoi(char *s)
{
int val = 0;
while (*s)
{
val *= 10;
val += (*s) - '0';
s++;
}
return val;
}