PHP check postal code in MySQL Database - php

I am trying to write a script to check someone's details they enter in a HTML form.
I have the code fine but i have realised if they type the postcode in a different format to whats in the database its going to error.
do i just take the POSTed postcode and change the format, if so whats the best way of making whats typed one format?
for example, in the database there is a row with the postal code SS9 5LY but if someone types it as SS95LY or ss9 5ly it wont match

First, take a look to ZIP (POSTAL) Code Validation Regex. Also, try to use a database records in your validation.

Have thousants of approachs to solve your problem.
You can use masked input, you can validate the input text before send to database using
RegularExpression. And many others.

You can use preg_replace() to remove any unwanted characters from the input, convert everything to upper case and finally add the space after the third character using substr():
$postcode = preg_replace("/[^a-zA-Z0-9]+/", "", $postcode);
$postcode = strtoupper($postcode);
$postcode = substr($postcode, 0, 3) . ' ' . substr($postcode, 3);

Related

PHP variables look the same but are not equal (I'm confused)

OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.

Google Distance Matrix API does not return value if I am using variables of Origin and Destination

I am working on a project now which needs to calculate distance between two point (either a latitude and longitude or a specific name of place).
Now, since my origin and destination comes from my database, i need to use a variable where the origin and destination be stored and eventually computed.
My code goes like this:
<?php
//request the directions
$origin="maramag";
$desti="malaybalay";
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=$origin&destination=$desti&alternatives=true&sensor=false'))- >routes;
//sort the routes based on the distance
usort($routes,create_function('$a,$b','return intval($a->legs[0]->distance->value) - intval($b->legs[0]->distance->value);'));
//print the shortest distance
echo $routes[0]->legs[0]->distance->text;
echo $routes[0]->legs[0]->duration->text;
?>
But when I tried running the URL without using variables, such as this:
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=maramag&destination=malaybalay&alternatives=true&sensor=false'))->routes;
It gives me a result of "49.0 km 45 mins" which is the result I wanted to appear.
Can anybody help me format my variable? I think it's the format or syntax of my variable contained in the URL has problem.
I browsed Google and on this site but I had never found a solution for my problem.
Thank you very much!
Use the string concatenation operator to create your URL:
$origin="maramag";
$desti="malaybalay";
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin='.$origin.'&destination='.$desti.'&alternatives=true&sensor=false'))- >routes;
If the strings contain spaces or other characters that are not legal in URLs, URL encode them first.
The answer of #geocodezip above is right but it will trigger an error if the Origin and Destination contains spaces. So we must replace the spaces with "+" to avoid it. The complete answer to this question is below:
$origin="Dologon, Maramag, Bukidnon";
$desti="Malaybalay City, Bukidnon";
//replace the spaces with "+"
$address1 = str_replace(' ', '+', $origin);
$address2 = str_replace(' ', '+', $desti);
//use concatenation as answered by #geocodezip
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin='.$address1.'&destination='.$address2.'&alternatives=true&sensor=false'))->routes;
So instead of making our origin=$origin and our destination=#desti, we must make it origin='.$origin.' and for destination we must make it destination='.$desti.'
Happy coding! Thank you very much for helping!
Using your code I was able to get a proper response with an address containing spaces by using urlencode and making sure that I used double quotes instead of single quotes.
Here is all I did:
$location = urlencode($location); // May contain spaces
$routes = json_decode(file_get_contents("http://maps.googleapis.com/maps/api/directions/json?origin=$userLat,$userLong&destination=$location&alternatives=true&sensor=false"))->routes;
The rest of your code worked perfectly and returns the correct distance and travel time. I had no need to use PHP's string concatenation syntax (ie: "Text ". $var ." more text)
In case anyone is curious, I got the user's latitude and longitude via javascript/PHP using the answer from this post

preg_match php returning text between two search paramaters

if this is a duplicate I apologise but i couldnt find anything on google after hours of searching, im pretty new to string manipulation and dont really know the correct terminology to find the information i want.
Basically I am manipulating this string
Date Time Name IP UniqueID
$line = 02.12.2013 16:00:03: Connor Bergolio (75.13.15.229:5557) fcfd6ba862c7461a88e2b13babc691dd
So I am trying to retreive the name, However as they can choose whatever name they want, it could have 1 space or 10 spaces so explode is out of the question.
Now I was wondering if it is possible to run a pregmatch using 2 variables. that will return the information between
$pattern1 = '$time, $ip';
preg_match($pattern1, $line, $name);
Looking at that, its way off, but I'm pretty much at a loss
Im using `$IPpattern = '/([0-9-():.)]{19,23})/';
to get the IP maybe using that and a search for time together?
Thanks in advance`
The following pattern will work:
preg_match('/^(.{19}): (.+?) +\(([0-9:.]+)\) ([a-f0-9]+)$/', $line, $matches);
$date = $matches[1];
$name = $matches[2];
$ip = $matches[3];
$uniqueId = $matches[4];
Not knowing the vaild characters allowed for a username, or any of the rules governing the format of Date and Time fields, the following should work:
.*(?:\d\d:){3}\s*\K.+(?=\s?\()
EXPLAINED
.*(?:\d\d:){3}\s*\K - Match everything up to Time field then drop it with \K
.+(?=\s?\() - Match anything one or more times up to but not including the first bracket found
It's not efficient though :(
I'm using this regex to retrieve the name:
/[\d{2}.]{2}\d{4}\s(\d{2}:){3}\s(.+)(\s\(.+)/
Have a play, the second result from this is your name.

Different results between print_r($something) and writing the same $something in database

I am parseing a page and saving the retrived data in mysql db. Everything is ok except the price of the product. After extracting price,when i use print_r($price) i get the actual value but while saving the same $price in my database, i get only a part of it.
for example:-
while using print_r($something); //output is 2 458
while saving in database $something, the saved value is only 458.
I think that the problem is due to space between 2 and 4. I can understand that this is a very simple question for most of you, but right now i am not able to solve it.
Thanks a lot ahead for support!
MySQL is pretty permissive about what data you can insert into its fields. In this case you are trying to insert a string that contains two numbers into a numeric field, it's doing its best to extract a single number from that data but is getting it wrong.
All you need to do is remove the space(s) before you insert:
$something = str_replace(' ', '', $something);
or using a regular expression you could remove any non-numeric character:
$something = preg_replace("'[^0-9]'", '', $something);

PHP to Mysql Line break Question

I am having hard time getting a form submitted textarea where people put in line breaks when they hit enter on their address..For example.
<textarea name="address"></textarea>
I am using this to get the post
$address = mysql_real_escape_string(trim($_POST['address']));
They are entering 123 test <return>city,state.
Then after they submit, in the mysql database the address is showing 123 testnrcity state
So how can I handle this?
Thanks!
Use nl2br?
$address = mysql_real_escape_string(trim(nl2br($_POST['address'])));
HTH :)
Have you checked what's in your database field? Just show the database contents with phpMyAdmin or a similar tool. The line break can either be a line break character or two characters: \n. If it's the latter, then your input probably was escaped twice. Or is it just "n". Then there is probably another escaping somewhere along the way. Do you use a database abstraction layer? Maybe it escapes the values too.
I was not able to resolve this the way I wanted to and just settled with using str_replace() to replace all "\r\n" stuff with a space...

Categories