0

I have this PHP Code:

$address='';
if($_POST["address1"] > '') {
    $address.=$_POST["address1"];
}
if($_POST["address2"] > '') {
    $address.=$_POST["address2"];
}
if($_POST["address3"] > '') {
    $address.=$_POST["address3"];
}
if($_POST["town"] > '') {
    $address.=$_POST["town"];
}
if($_POST["county"] > '') {
    $address.=$_POST["county"];
}
if($_POST["postcode"] > '') {
    $address.=$_POST["postcode"];
}

It then inserts a row into a database using the $address variable

How can i ensure there is a non-html line break for each address line?

3
  • You probably meant != instead of >? Commented Oct 3, 2014 at 18:00
  • stackoverflow.com/questions/2902888/… Commented Oct 3, 2014 at 18:00
  • Barmar answer should work, or just append . "\n"; to the end of each address line. Commented Oct 3, 2014 at 18:01

2 Answers 2

1

Put the address fields in an array, then use implode() to combine them with newlines:

$addr_array = array();
foreach (array('address1', 'address2', 'address3', 'town', 'county', 'postcode') as $field) {
    if ($_POST[$field] > '') {
        $addr_array[] = $_POST[$field];
    }
}
$address = implode("\n", $addr_array);
Sign up to request clarification or add additional context in comments.

1 Comment

im getting a syntax error on your second line - i cannot seem to find it
0

While others have suggested a way to implode the address, I would like to suggest saving the address in a structured way in the database. That is important also because not all countries follow the same order when representing the address: for example, certain European countries put the postal code before the city name, etc.

You can store structured data into a MySQL database using for example JSON (more efficient than XML and cross-platform unlike PHP's serialize() ).

<?php
$address = array();
$fields = array('address1', 'address2', 'address3', 'town', 'county', 'postcode');
foreach($k in $fields) {
    if(!empty($_POST[$k])) {
        $address[$k] = $_POST['k'];
    }
}
// Store this single variable in the database
$store = json_encode($address);
?>

(IMPORTANT: in your code it seems like you're not filtering/validating the input from the user. I strongly suggest you to do that, removing HTML codes, checking for valid Unicode, etc! By filtering the user input properly you protect your code from 80% of the common hacks)

Then, when you read the contents from the database you can simply re-obtain your array with:

<?php
$result = // ... Obtain the data from the database
$result['address'] // This variable contains your address

$address = json_decode($result['address'], true);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.