If statement to check the number of characters in a textbox - php

when the user adds a contact, it checks to see if the "character" count is 8, then it check the database to see if the username and the NewContact already exist, and if it "false", it inserts the new contact.
the bit that doesn't work is limiting the number of characters to 8
if (intval($s_id) == 8)
{
$db = mysql_connect("at-web2.xxx", "user_xxx", "xxxx");
mysql_select_db("db_xxx",$db);
$result = mysql_query("SELECT * FROM contacts WHERE u_id='$username' and c_id='$s_id'",$db);
$myrow = mysql_fetch_row($result);
if(!$myrow)
{
mysql_query("INSERT INTO contacts(u_id, c_id) VALUES ('$username','$s_id')",$db);
header("Contact Added");
}
else
{
header("Contact Already Exist");
}
}
else
{
header("Incomplete Contact");
}

You need strlen function.
if(strlen($s_id) == 8)

you have to use strlen to get number of characters
if (intval($s_id) == 8)
should be
if (strlen($s_id) == 8)

Try to use strlen with trim function to get accurate length of string.
if(strlen(trim($s_id)) == 8)

Use strlen (stringlength) predefined php function for getting the exact length of the string .
if(strlen($string) == 8)
{
//Statements
}
else
{
//statements
}

Related

if print_r is empty conditional in PHP

I'm trying to get a n else statement working with a print_r such that if there's no value it outputs "no values".
In the code I'm getting values from json converted to an array.
The logic I'm trying to achieve is
IF fieldTag contains "i" THEN output the content associated with it
ELSE says its empty.
Right now blank is outputted as opposed to "no values".
Thanks
for($b=0; $b<count($res['entries'][$i]['bib']['varFields']); $b++) //loop thru the varFields
{
if($res['entries'][$i]['bib']['varFields'][$b]['fieldTag'] == "i")
{
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content']."<br>";
if(count($subfieldText2) > 0) {
print_r($subfieldText2);
} else {
echo "no values";
}
}
}
count() is for arrays, not strings, the way to get the length of a string is with strlen(). And if you want to check for an empty string, just compare it with $var == "", you don't need to get the length.
But you're concatenating "<br>" to the value, so the length will never be zero. You could check the length before concatenating.
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content'];
if($subfieldText2 != "") {
$subfieldText2 .= "<br>";
print_r($subfieldText2);
} else {
echo "no values";
}
And to avoid having to repeat that long expression to access the field, you could use foreach
for($res['entries'][$i]['bib']['varFields'] as $field) {
if ($field['fieldTag'] == "i") {
$subfieldText2 = $field['subfields'][0]['content'];
...
}
}
this worked for me thanks everyone
$subfieldText2="not detected";
echo "ISBN: ";
for($b=0; $b<count($res['entries'][$i]['bib']['varFields']); $b++) //loop thru the varFields
{
if($res['entries'][$i]['bib']['varFields'][$b]['fieldTag'] == "i")
{
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content'];
echo $subfieldText2.", ";
}
}
echo $subfieldText2;

How to compare 2 variable using php like this?

How to compare 2 variable using php like this ?
$aaa = "1234567890qwertyuiopsdflkjwerouioiuweewjkee";
$bbb = "1234567890qwertyuiop";
How to check
if(first char to twenty char of $aaa == $bbb)
{ echo "same"; }
else
{ echo "not same"; }
I assume you are searching for strncmp:
This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.
if(strncmp($aaa, $bbb, 20) == 0) {
# First twenty characters match.
} else {
# First twenty characters don't match.
}
$aaafirst20 = $small = substr($aaa, 0, 20);
if(strcmp($aaafirst20 , $bbb){
}
else{
}
Try this :
You can use strcmp function for the same.
PHP docs # strcmp
if(strcmp($aaa,$bbb)){
echo "same";
} else {
echo "not same";
}
You can use strpos() to check if $bbb is found in $aaa, and starts at position 0.
if (strpos($aaa, $bbb) === 0) {
echo 'Same';
}
else echo 'Not same';
See demo
Your exact solution would be
// first reduce a to its first 20 characters
$trimmed = substr($aaa, 0, 20);
// now compare with b
if($trimmed == $bbb){
// same
}
Or, all in one line
if(substr($aaa, 0, 20) == $bbb){
// same
}

check if numeric php

my problem is, i have a form which i fill blabla and after i submit i need to check if the var '$number' contains only 9 numbers. which means that if it contains at least 1 letter or has less or more than 9 length it should return false, else it should return true;
this is what i got so far:
if (!is_numeric ($number) {
//do
} else {
}
1st problem: This code should take care of the only numbers part but it doesnt, it always returns false.
2nd: do you guys know of any way to take care of the 9 digits only verification?
thanks and sorry for my bad english, not my native language :P
Your number may contain unwanted whitespaces which cause the is_numeric() test not to work properly
So do the following: $number = trim($number); to remove them.
Then indeed this snippet is good to check if your variable is a number:
if (!is_numeric ($number)) {
//do
} else {
}
And for the number digits do a if statement to see if your number is between 100000000 and 999999999
So the full code will be:
$number = trim($number);
if (!is_numeric ($number)) {
//do
} else {
if ($number >= 100000000 && $number <= 999999999) {
// Everything is ok
} else {
}
}
Didn't understood your complete question coz of you native language :p, but i think you want this:
if (is_numeric($number) {
if(strlen($number) == 9){
return true;
} else {
return false;
}
} else {
echo 'Not a number';
}
Check if it contains digits and check whether its exactly contains 9.
$number = '123456789';
if(!preg_match('/^\d{9}$/', $number)) {
echo 'not ok';
} else {
echo 'ok';
}

Function to validate username and password not working [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {

php validate integer

I`m wonder why this not working
echo gettype($_GET['id']); //returns string
if(is_int($_GET['id']))
{
echo 'Integer';
}
How to validate data passing from GET/POST if it is integer ?
Can use
$validatedValue = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
See http://php.net/filter_input and related functions.
The manual says:
To test if a variable is a number or a
numeric string (such as form input,
which is always a string), you must
use is_numeric().
Alternative you can use the regex based test as:
if(preg_match('/^\d+$/',$_GET['id'])) {
// valid input.
} else {
// invalid input.
}
What about intval?
$int = intval($_GET['id']);
To validate form data (string) as an integer, you should use ctype_digit()
It returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
(PHP 4 >= 4.0.4, PHP 5)
Reference: http://php.net/manual/en/function.ctype-digit.php
Try:
if(isNumeric($_GET['id'])) {
$cast_int = (int)$_GET['id'];
}
if(isset($cast_int)) {
echo gettype($cast_int)."<br />\n";
if(is_int($cast_int))
{
echo 'Integer'."<br />\n";
}
} else {
echo gettype($_GET['id'])." was passed<br />\n";
}
function isNumeric($numeric) {
return preg_match("/^[0-9]+$/", $numeric);
}
It sounds like you are checking if a string contains an integer, rather than if that variable is an integer. If so, you should check out php's regex (regular expression) functionality. It allows you to check for very specific patterns in a string to validate it for whatever criteria. (such as if it contains only number characters)
Here's the php page
http://php.net/manual/en/function.preg-match.php
and here's a cheat sheet on regular expressions (to make the $pattern string)
http://regexpr.com/cheatsheet/
I take a slightly more paranoid approach to sanitizing GET input
function sanitize_int($integer, $min='', $max='')
{
$int = intval($integer);
if((($min != '') && ($int < $min)) || (($max != '') && ($int > $max)))
return FALSE;
return $int;
}
To be even safer, you can extract only numbers first and then run the function above
function sanitize_paranoid_string($string, $min='', $max='')
{
$string = preg_replace("/[^a-zA-Z0-9]/", "", $string);
$len = strlen($string);
if((($min != '') && ($len < $min)) || (($max != '') && ($len > $max)))
return FALSE;
return $string;
}
Code from: http://libox.net

Categories