0

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

2 Answers 2

2

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 "."!

Sign up to request clarification or add additional context in comments.

Comments

1

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

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.