It is currently Thu Feb 23, 2012 7:21 am

All times are UTC + 2 hours [ DST ]




Post new topic Reply to topic  [ 2 posts ] 
Author Message
 Post subject: implode() function problem
PostPosted: Fri Jan 27, 2012 8:37 pm 
Offline

Joined: Fri Jan 27, 2012 8:26 pm
Posts: 2
Hello all i have here my code :
Code:
<?php
$insertValues = array(); //Temp array to store values
foreach($array as $id => $record)
{
    $name  = $record[0];
    $age    = $record[1];
    $addr   = $record[2];
    $weight = $record[3];
    $height = $record[4];

    $insertValues[] = "('{$name}', '{$age}', '{$addr}', '{$weight}', '{$height}')";
}

//Create/run insert quer
$query = "INSERT INTO table_name
              (`name`, `age`, `address`, `weight`, `height`)
          VALUES " . implode(', ', $insertValues);
$result = mysql_query($query);
?>


The code works fine but have problems when a field contain quotes, double quotes and commas.
Ex : when $addr = "address 1, sample's street."

This would cause an error when i try to save it into the database. the query string would give me this. Please see below


Code:
<?php
/* for example the implode results would be ('thomas','17','5 feet','60 kilograms','address 1, sample's street.') */
$query = "INSERT INTO table_name
              (`name`, `age`, `height`, `weight`, `address`)
          VALUES ('thomas','17','5 feet','60 kilograms','address 1, sample's street.');
  ?>


as you can see the string on Values has an error since the bold information has a wrong format.. Please see below

Code:
<?php VALUES ('thomas','17','5 feet','60 kilograms','address 1, sample's street.'); ?>


can someone help me modify the code so that i could save my information whether or not it has a comma, quote and double quote?

thanks guys


Top
 Profile  
 
 Post subject: Re: implode() function problem
PostPosted: Mon Jan 30, 2012 9:18 pm 
Offline

Joined: Sun May 02, 2004 11:34 pm
Posts: 6510
Location: toronto, canada
user mysql_real_escape_string or try using prepared statements with PDO or MySQLi functions

Code:
//Create/run insert quer
$query = "INSERT INTO table_name
              (`name`, `age`, `address`, `weight`, `height`)
          VALUES " . implode(', ', " . mysql_real_escape_string($insertValues));

//echo out the query to ensure that you have the whole thing correctly quoted
echo $query;

$result = mysql_query($query);

_________________
Lostboy

Cat, the other other white meat

Please read Posting Etiquette before posting

You can always try Google


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC + 2 hours [ DST ]


Who is online

Users browsing this forum: Google [Bot] and 0 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
Jump to:  
cron