Skip to content

Instantly share code, notes, and snippets.

@javedbaloch4
Last active August 18, 2017 12:39
Show Gist options
  • Save javedbaloch4/b71fc203c391516c1874683b5851b673 to your computer and use it in GitHub Desktop.
Save javedbaloch4/b71fc203c391516c1874683b5851b673 to your computer and use it in GitHub Desktop.
A great use of php Implode
<?php
/*
* By Muhammad Javed Baloch
** You can process data via $_POST or $_GET
** You could add secuirty functionalties suchas Escaping
*/
$data = array(
'name' => 'Javed',
'email' => 'mjavedahmed@live.com',
'message' => 'Hello Javed, How are you?',
'telephone' => '0340 24176--',
'postCode' => 'xxxx',
'cnic' => 'xxxx-xxxx'
);
$sql_fields = '`'. implode('`, `', array_keys($data)). '`';
$sql_values = '\''.implode('\', \'', $data). '\'';
$query = "INSERT INTO `users` ($sql_fields) VALUES ($sql_values)";
echo $query;
?>
@azeemhassni
Copy link

The variables are not being used elsewhere why don't you inline them?

    $data = array(
        'name'      => 'Javed',
        'email'     => 'mjavedahmed@live.com',
        'message'   => 'Hello Javed, How are you?',
        'telephone' => '0340 24176--',
        'postCode'  => 'xxxx',
        'cnic'      => 'xxxx'
    );

    $sql_fields = '`'. implode('`, `', array_keys($data)). '`';
    $sql_values = '\''.implode('\', \'', $data). '\'';
    
    $query = "INSERT INTO `users` ($sql_fields) VALUES ($sql_values)";
    echo $query;

@javedbaloch4
Copy link
Author

javedbaloch4 commented Aug 18, 2017

Right good idea, Thank you for contribution.
It has been updated.

@azeemhassni
Copy link

This can be interesting too.

/**
 * Wrap array items into html elements
 *
 * @param array $items
 * @param string $tag
 * @return string
 */
function wrap($items, $tag = 'li')
{
    return sprintf('<%1$s>%2$s</%1$s>', $tag, implode("</$tag> <$tag>", $items));
}

$items = ['One', 'Two', 'Three'];

echo wrap($items);
// output
// <li>One</li> <li>Two</li> <li>Three</li>

echo wrap($items, 'div');
// output
//<div>One</div> <div>Two</div> <div>Three</div>

@javedbaloch4
Copy link
Author

Yeah, Fabulous i like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment