0

When i insert this type of array values directly into Mysql database, I got error like this

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':23:09Z, 36840bd430637, Success, 85.0, 11457922, 10.02, USD, X, M, 59106737WV831' at line 1

and myquery is

 INSERT INTO `transaction`(TIMESTAMP, CORRELATIONID, ACK, VERSION, BUILD, AMT, CURRENCYCODE, AVSCODE, CVV2MATCH, TRANSACTIONID) VALUES (2014-06-26T02:23:09Z, 36840bd430637, Success, 85.0, 11457922, 10.02, USD, X, M, 59106737WV831451U)

Mycode is

$columns = implode(", ",array_keys($result_array));
$escaped_values = array_map('mysql_real_escape_string', array_values($result_array));
$values  = implode(", ", $escaped_values);
echo $sql = "INSERT INTO `transaction`($columns) VALUES ($values)";
$res =mysql_query($sql);

what are the changes can i do?

1
  • 4
    First, get rid of the echo in echo $sql... then use quotes around your values. That should get you started ;-) Commented Jun 26, 2014 at 2:37

2 Answers 2

1

First of all, you should escape column names (not always required):

$cols = join(',', array_map(function($name) {
    return '`' . str_replace('`', '``', $name) . '`';
}, array_keys($result_array));

Then, keeping in mind that mysql_real_escape_string() doesn't add quoted enclosures:

$vals = join(',', array_map(function($value) {
    return "'" . mysql_real_escape_string($value) . "'";
}, $result_array);

$sql = "INSERT INTO `transaction` ($cols) VALUES ($vals)";

Lastly, using mysql_ functions is deprecated and you should move onto using either PDO or mysqli.

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

Comments

0

What is meaning of echo $sql here? try this way & you can also escape your string firstly.

foreach($singleRow as $key=>$data) //for multiple rows
{
 if(isset($data)){
   $dataArray[$key] = is_string($data) ? mysql_real_escape_string($data) : $data;
   }
}

$tableName='transaction';
$keys = implode(',',array_keys($dataArray));
$data_values = ("'".implode("','",array_values($dataArray))."'");
$insertSql = "INSERT INTO ".$tableName." ($keys) VALUES ($data_values)";
$res =mysql_query($insertSql );

use mysqli_* and PDO anyway

1 Comment

Why did you throw away the mysql_real_escape_string()?

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.