PHP Zip Code Losing Leading Zero - php

I am storing zip codes in a MySQL database as varchar(10). For some reason storing it in one table is not working like the other one. The only difference between the fields is that one is varchar(10) Nullable, and one is varchar(10). The Nullable column is saving the zip code without a leading zero so '05415' becomes 5415. This is working in the other table just fine. I think they are being stored on the same page, but I can't seem to find the problem. I'm not very good with PHP, so I would really appreciate some help here.
This is the function for registration on the site....the registration table in the db is saving the zip code with the leading 0, so I assume that this works.
$Zip = strip_tags(trim($_POST['MembersZip']));
if (strlen($Zip = trim($Zip)) == 0) {
$isError = true;
print "<script>$('#MembersZip').addClass('error');</script>";
print '<div class="errors">Please enter zip / postal code</div>';
}
if (strlen($Zip = trim($Zip)) < 5) {
$isError = true;
print "<script>$('#MembersZip').addClass('error');</script>";
print '<div class="errors">Zip code must be at least 5 digits</div>';
}
$sql = "INSERT INTO tbl_ecommerce_addresses (
ead_postal_code
) VALUES (
'" . addslashes($Zip) . "'
)";
This is what the process looks like for the orders. This is the table where the leading zero gets deleted before it gets inserted.
$fieldName = "BillingZip";
$fieldValue = strip_tags($_POST[$fieldName]);
if (!$fieldValue || strlen($fieldValue = trim($fieldValue)) == 0) {
$isError = true;
print "<script>$('#{$fieldName}').addClass('error');</script>";
print '<div class="errors">Please enter billing zip / postal code</div>';
} else {
$this->fields[$fieldName] = $fieldValue;
$this->record->eod_billing_postal_code = $fieldValue;
}
$Zip = $this->record->eod_billing_postal_code;
if (strlen($Zip = trim($Zip)) < 5) {
$isError = true;
print "<script>$('#BillingZip').addClass('error');</script>";
print '<div class="errors">Billing Zip Code must be at least 5 digits</div>';
}
It looks like this line
$newId = $this->record->insert();
is doing the insert, but when I do a var_dump of $this->record, the zip code still shows the leading 0. The only other thing I can think of is that the payment gateway is changing it somehow.
$paymentType = urlencode("Authorization"); // 'Sale' or 'Authorization'
$firstName = urlencode($this->fields["BillingFirst"]);
$lastName = urlencode($this->fields["BillingLast"]);
$creditCardType = urlencode($this->fields["CardType"]);
$creditCardNumber = urlencode($this->fields["CardNumber"]);
$padDateMonth = urlencode(str_pad($this->fields["CardMonth"], 2, '0', STR_PAD_LEFT));
$expDateYear = urlencode($this->fields["CardYear"]);
$cvv2Number = urlencode($this->fields["CardCode"]);
$address1 = trim(urlencode($this->fields["BillingAddress"]));
$address2 = urlencode($this->fields["BillingAddress2"]);
$city = urlencode($this->fields["BillingCity"]);
$state = urlencode($this->fields["BillingState"]);
$zip = urlencode($this->fields["BillingZip"]);
$country = urlencode($CountryCode); // US or other valid country code
$amount = urlencode($this->fields["PurchasedTotal"]);
$currencyID = urlencode($this->siteConfig->cy_code);
$ipAddress = $main->getIP();
$invoice = substr($this->fields["CardNumber"],-4,4) . substr($this->fields["BillingZip"],0,4) . substr($this->fields["PurchasedTotal"],0,2);
$nvpStr = "&PAYMENTACTION=$paymentType&IPADDRESS=$ipAddress&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&INVNUM=$invoice&FIRSTNAME=$firstName&LASTNAME=$lastName".
"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=USD";
To get the zip code to display correctly, I updated the code with this, and the 0 showed up:
$zip = str_pad($order->eod_shipping_postal_code, 5, '0', STR_PAD_LEFT);

If I had a guess I would assume that somewhere along the way your variable is being stored as an integer, and if that happens then you would definitely lose that leading '0'. A few options to look at could be looking where the variable is stored and making sure it is stored as a string.
Alternatively, you can always make sure it has 5 numbers in php by using this:
str_pad($zip, 5, '0', STR_PAD_LEFT)
See this: http://www.php.net/str_pad
(Though I would advise that you find where it is being stored as a number over 'faking it' in php. but if you can't find it, this would work)

The data type in the database should be char(5) for the zip-code.

Related

removing unwanted characters from string in php

I'm using a database to store variables of user names and then access them using php. A form with post method is used to invoke a php file which access the database, retrieves all the user names and then compares them with the entered values. The user names are stored in $row['name'] variable and the name is stored in $photographer variable.
The problem is that there are some characters attached in string of variable $row['name'] when being accessed from db which I can't get rid of.
I thought using these variables directly might be causing some problems so I saved their values in other two variables. But the problem didn't go away.
Below is the php code:
//pin check module
$connection = mysqli_connect("localhost","root","","members") or die(mysqli_error($connection));
$select_query_pin = "SELECT name, pin FROM members";
$select_query_pin_result = mysqli_query($connection, $select_query_pin) or die (mysqli_error($connection));
$total = mysqli_num_rows($select_query_pin_result);
$pin = $_POST['pin'];
$title = explode(",",$_POST['title']);
$url = explode(",",$_POST['url']);
$photographer = $_POST['photographer'];
$genere = explode(",",$_POST['genere']);
$entry = sizeof($title);
while ($total) {
--$total;
$row = mysqli_fetch_array($select_query_pin_result);
$name_sample = $row['name'];
$test_sample = $photographer;
// chop($name_sample);
// chop($test_sample);
preg_replace( "/\r|\n/", "", $name_sample );
// for ($i = 0; $i < strlen($name_sample); $i++) {
// if ($name_sample[$i] == " ")
// echo 'true';
// }
var_dump($name_sample,$test_sample);
if ($name_sample === $test_sample)
echo 'true<br>';
else
echo "false<br>";}
As you can see, I tried using the chop and preg_replace methods but it didn't work. When I check the strings using var_dump, it gives unequal lengths for equal strings. The html view of above code is this:html output
Is there a way to deal with it?

How to insert two variable value into single field in php?

code:
<?php
if(isset($_POST['add_new']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$field = $_POST['field'];
$message = $_POST['message'];
$comment1 =array($_POST['comment1'],$s_date);
$comment2 = $_POST['comment2'];
$status = $_POST['status'];
$s_date = date('Y-m-d');
$interested_in = $_POST['interested_in'];
$academic_details = $_POST['academic_details'];
$city = $_POST['city'];
$sql = "insert into enquires2(name,email,phone,field,message,comment1,comment2,status,s_date,interested_in,academic_details,city,admin_idd)values('$name','$email','$phone','$field','$message','$comment1','$comment2','$status','$s_date','$interested_in','$academic_details','$city','$admin_id')";
$result = mysqli_query($link,$sql);
if($result == true)
{
$msg .= "<p style='color:green;'>You are successfully add new enquiry</p>";
}
else
{
$msg .= "<p style='color:red;'>Error!</p>";
}
}
?>
In this code I want to pass two value in single variable i.e.
$comment1 = array($_POST['comment1'],$s_date);
which show (array) when I print query ($sql). How can I pass two value into single variable ? please help me.
Another option if you don't want to concatenate , use serialize function make an associative array and serialize it and store to db
for example :
$comment1 =serialize(array("comment"=>$_POST['comment1'],"date"=>$s_date));
and when you get form db ,just use
$data = unserialize($yourDataFromDb);
and you get your values like
$data["comment"] // Your comment
$data["date"] // your date
Simply use concatenation
$comment1 = $_POST['comment1'] . $s_date;
But if you want to parse later and keep sepration between comment and date you can use any format like
$comment1 = $_POST['comment1'] . "--date--" . $s_date;
Later you can simply use print_r (explode("--date--",$str));
Something like multivalue field.
You already record the value of $s_date in a separate "date" field, so there's no need to record it again within the comment field.
If you want to combine them for display or reporting purposes later on, then you can easily do that in the object or UI layer using simple string concatenation. I would advise you not to do this when storing the data as you're attempting - otherwise you're just duplicating the same value twice in the row for no obvious reason, as well as making it more difficult to separate what the user actually wrote from the date you inserted into it.

How to generate voucher code, check the DB if it's unique, generate new one if not

I'm having a loop issue in my script. I've spent a lot of time trying to fix it but I still don't know how to fix the problem. I need your help and suggestions regarding this.
My goal is to create a voucher code generator script where the user enters the number of voucher codes to be generated.
Then, the script will generate the required number of vouchers in the database table, and each voucher code will be checked if it is unique - if not, a new voucher code will be generated and the script will proceed until all vouchers are saved.
The problem is that if voucher already exists in the DB, a new one needs to be generated. This newly generated voucher code needs to be checked again if it's already in the DB, if it's unique it will be saved to the DB and if not, the process will go on again. This is where the loop problem lies. I hope you get what i mean.
By the way, the voucher code is in this format: XXXX-XXXX-XXXX (uppercase letters only)
Here's the current codes that I have:
include 'conn.php';
function WriteCSV($flname,$values) {
$Filename = "./vouchers/$flname.csv";
$fh = fopen($Filename, 'a') or die("can't open file");
$filecontent = $values;
$filecontent .= PHP_EOL;
fwrite($fh,$filecontent);
fclose($fh);
}
function generateCode(){
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "";
for ($i = 0; $i < 4; $i++) {
$res .= $chars[mt_rand(0, strlen($chars)-1)];
}
return $res;
}
function generateVCode(){
$c1 = generateCode();
$c2 = generateCode();
$c3 = generateCode();
$voucher = "$c1-$c2-$c3";
return $voucher;
}
function searchDB($con, $voucher){
$rs = mysqli_query($con,"SELECT count(*) AS cnt FROM vouchers WHERE vouchercode = '$voucher'");
$row = mysqli_fetch_assoc($rs);
$cnt = $row['cnt'];
if($cnt > 0){
return '1';
} else {
return '0';
}
}
function checkVoucher($con, $voucher, $vsource, $expiry, $today, $vnum, $vprice){
$dbres = searchDB($con, $voucher);
if($dbres == '1'){ //voucher found in db
$val = '0';
$voucher = generateVCode(); //generate a new voucher
checkVoucher($con, $voucher, $vsource, $expiry, $today, $vnum, $vprice); //repeat the process
} else { // voucher is unique
mysqli_query($con, "INSERT INTO vouchers (vouchercode, source, price, expires, generated) VALUES ('$voucher', '$vsource', '$vprice', '$expiry', '$today')");
$flname = "$vsource - ".date('d M Y')." ($vnum vouchers)";
WriteCSV($flname,$voucher);
$val = '1';
}
return $val;
}
$vnum = $_POST['vouchernum'];
$vsource = $_POST['source'];
$vprice = $_POST['amt'];
$expdate = $_POST['expdate'];
$expiry = $_POST['voucherexpiry'];
$today = date('Y-m-d');
$expconv = date('Y-m-d',strtotime("$expiry"));
$expfive = date('Y-m-d',strtotime("$expiry +5 years"));
for ($x = 1; $x <= $vnum; $x++) {
$vouchercode = generateVCode();
if($expdate == "no"){
$expiry = $expfive;
} else {
$expiry = $expconv;
}
do {
$result = checkVoucher($con, $vouchercode, $vsource, $expiry, $today, $vnum, $vprice);
} while ($result != '1');
header("location: index.php?s=1");
}
By the way, if you have suggestions on how to generate the voucher codes easier, please feel free to share.
I'm thinking the issue/problem here is on either the do-while statement or the checkVoucher() function.
I'd really appreciate you help and suggestions. Thanks.
I would go completely easier. Set the voucher column in your table to unique. Generate a code PHP side, do your insert, in the error callback function call to generate a new code.
Basically, this will self loop until inserted. Then in your success callback add it to your display. All of this is wrapped in a while loop. Once you get your 5, break the loop.
As far as generating a random string with minimal chance of a repeat, check this thread: PHP random string generator
I would generate the full length string and then just add your hyphens.
Using this approach to generate random unique data, the amount of processing required increases proportionally as more and more codes are generated.
What I would do instead is:
Generate a whole bunch of values (lets say a few thousand) values sequentially and store them in a redis/SQL database
Use a random number to index that record in the database, and remove the record from the table once it has been used
This reduces the processing required greatly, and also gives you a pre determined pool of voucher codes which could be useful for other purposes in your application
Mysql unique constraint may be the solution you are looking for.it ensures a value is always unique. It is like primary key. but unlike primary key a table can have multiple unique values.
Here is the link to w3school explaining this
www.w3schools.com/sql/sql_unique.asp
The best part is it will genrerate a Duplicate Entry error when adding a duplicate entry. so you can use it to add data to csv . add it only when you have no error.
But make sure the unique value is not null.

SimpleXML to get specific data from an XML file

I am making a plugin for JomSocial that will display billing information for a logged-in user, based on an XML file. I have made good headway creating the plugin, I just cant seem to get the syntax right to create php statements so I can populate data in various places on the page. Here is the XML file:
<Inquiry>
<Billing>
<Version>4.5.1</Version>
<startTime><![CDATA[4/15/2014 11:09 PM]]></startTime>
<endTime><![CDATA[4/15/2014 11:12 PM]]></endTime>
<Date>20140415</Date>
<MemberId ID="0ESING">
<BillingInfo>
<StatementEndDate>20140430</StatementEndDate>
<BillingSubAccount>
</BillingSubAccount>
<BalanceForward>628.32</BalanceForward>
<BalanceDue>372</BalanceDue>
<Payments>-300</Payments>
</MemberId>
<MemberId ID="F00421">
</BillingInfo>
<BillingInfo>
<StatementEndDate>20140430</StatementEndDate>
<BillingSubAccount>
</BillingSubAccount>
<BalanceForward>1158.36</BalanceForward>
<BalanceDue>93.45</BalanceDue>
<Payments>-1158.36</Payments>
Here is the PHP so far:
$user =& CFactory::getRequestUser();
$cuser = CFactory::getUser();
$owner = CFactory::getUser($row->user->id);
$ptype = $cuser->getProfileType();
$billingid = $owner->getInfo('FIELD_BILLINGID');
$lastname = $owner->getInfo('FIELD_FAMILYNAME');
$uname = $cuser->username;
$memid = $cuser->id;
$name = $cuser->getDisplayName();
$isMine = COwnerHelper::isMine($cuser->id, $user->id);
$config = CFactory::getConfig();
$source = file_get_contents('data/201404.xml');
$xml = new SimpleXMLElement($source);
$balance = $xml->Billing->MemberId->BillingInfo->BalanceDue;
$BalanceForward = $xml->Billing->MemberId->BillingInfo->BalanceForward;
$Payments = $xml->Billing->MemberId->BillingInfo->Payments;
ob_start();
if( $isMine ) {
if($ptype == '2') {
if(strcasecmp($uname, $billingid) == 0) {
Then, in page to call the fields:
<?php echo "<div>Balance Due: $". $balance ." | Balance Forward: $" . $BalanceForward . " | Payment: $" . $Payments . "</div>"; ?>
This pulls in the first record of the XML file. I was trying something like this for hours:
$source = file_get_contents('data/201404.xml');
$xml = new SimpleXMLElement($source);
$balance = $xml->Billing->MemberId[.$uname.]->BillingInfo->BalanceDue;
$BalanceForward = $xml->Billing->MemberId[.$uname.]->BillingInfo->BalanceForward;
$Payments = $xml->Billing->MemberId[.$uname.]->BillingInfo->Payments;
to no avail. I would like to 'pull' the child node from the XML where the MemberId ID= "yadayada" is equal to the $uname. I hope I am being clear, this is my first post on Stackoverflow!
Using the square bracket notation accesses the attribute by it's name, so you are asking for member[0ESING] which isn't right because the attribute is named ID.
You can iterate of the members to find the match like so:
foreach($xml->Billing->MemberId as $member){
if($member['ID'] == $uname){
$balance = $member->BillingInfo->BalanceDue;
$BalanceForward = $member->BillingInfo->BalanceForward;
$Payments = $member->BillingInfo->Payments;
}
}
Why are you not using simplexml_load_file() instead? It saves you the hassle in loading the file manually and putting it in a simplexml_element instead. Furthermore, I think your issues arrise because the XML file itself is invalid, it need 1 root element but instead seems to contain zero (or multiple, depends on how one would read the file).

Updating a row number which has been randomised

So I currently have a random number being generated in PHP and I want to know how I go about updating the row number in my selected table. Code below:
$sxiq = mysql_query("SELECT * FROM `starting_eleven` WHERE `team_id`=$uid");
$sxir = mysql_fetch_row($sxiq);
$first = rand(1,11);
$stat_changed = rand(11,31);
$up_or_down = rand(1,2);
if ($up_or_down == 1) {
$player_name = explode(" ", $sxir[$first]);
$fn = $player_name[0];
$ln = $player_name[1];
$statq = mysql_query("SELECT * FROM `players` WHERE `first_name`=$fn AND `last_name`=$ln AND `user_id`=".$_SESSION['user_id']);
$statr = mysql_fetch_row($statq);
$stat = $statr[0];
}
I would like to update the row $stat_changed from the database, but I'm not sure if this is possible without doing a long if statement, telling the code if $stat_changed = 13 $stat = pace or something along those lines, but if this is the way it must be done then I'll have to. Just thought I'd see if there was any other simpler ways of doing this.
Thanks in advance
if ($stat_changed == 13) {
//insert UPDATE statement here
}

Categories