Charlie
Charlie

Reputation: 39

Creating line breaks without HTML Code in PHP/MySQL

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?

Upvotes: 0

Views: 104

Answers (2)

ItalyPaleAle
ItalyPaleAle

Reputation: 7296

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);
?>

Upvotes: 0

Barmar
Barmar

Reputation: 780723

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);

Upvotes: 1

Related Questions