user1210460
user1210460

Reputation: 91

Concatenation of string with a specific array elements

the given code below insert data from an array to the mysql table.as its not the full code but what i want to know is available in this code. my question is that there is a field in table named "image_url" but the data in that field only have image name and i want to append http://www.xxxxxx.com at the start of every image name and the replace it with the image name in the field but i dont know how to do that plz help me out

thanks in advance

function putTest($t) {

    //$c = connect();

    foreach ($t as $k => $v) {

         $query = "INSERT INTO test (".implode(',',array_keys($v)).") VALUES ('".implode("','",$v)."')";

         //echo "<pre>";

        // echo  $query;
        $r = mysql_query($query);

    }
    //mysql_close($c);
}

Upvotes: 0

Views: 137

Answers (2)

matzino
matzino

Reputation: 3564

This snippet should do what you want:

if (isset($v['image_url'])) {
    $v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
}

You can concatenate strings with the dot "."!

Upvotes: 2

Vyktor
Vyktor

Reputation: 20997

At first... Is your application protected against SQL injection? If not you should build two methods/functions like this using mysql_real_escape_string():

function sqlSafeKey( $key){
    return '`' . mysql_real_escape_string( $key) . `'`;
}

function sqlSafeValue( $value){
    return "'" . mysql_real_escape_string( $value) . "'";
}

And than use array_map() to escape your values like this:

$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);

About your question... The matzino's answer is correct and whole loop should look like this:

function putTest($t) {

    //$c = connect();

    foreach ($t as $k => $v) {
         $v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
         $keys = array_map( 'sqlSafeKey', array_keys( $v));
         $values = array_map( 'sqlSafeValue', $v);

         $query = "INSERT INTO test (".implode(',', $keys).
                  ") VALUES ('".implode("','",$values)."')";

         //echo "<pre>";

        // echo  $query;
        $r = mysql_query($query);

    }
    //mysql_close($c);
}

Upvotes: 1

Related Questions