0

So i'm trying to insert data into a MySQL table from an array that contains multiple arrays which hold data for each row of a table using the code below:

if (is_array($tbl_data)){
$sql = "INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values ";  
$arrayValues = array();
foreach ($tbl_data as $row){

    $agent = mysql_real_escape_string($row[0]);
    $event = mysql_real_escape_string($row[1]);
    $data1 = mysql_real_escape_string($row[2]);
    $data2 = mysql_real_escape_string($row[3]);
    $data3 = mysql_real_escape_string($row[4]);
    $data4 = mysql_real_escape_string($row[5]);
    $data5 = mysql_real_escape_string($row[6]);

    $value = "($agent,$event,$data1,$data2,$data3,$data4,$data5)";
    array_push($arrayValues, $value);
}   
$sql .=implode(',', $arrayValues);

Quick check using var_dum($sql) produces the following:

INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values (NONE,QUEUESTART,,,,,)/////

The above Sql is invalid due to the multiple commas here :(NONE,QUEUESTART,,,,,)which are generated by empty fields. How can I insert single quotations inside the query to make it valid ? i.e the correct sql syntax:

INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values (NONE,QUEUESTART,'','','','','')
0

1 Answer 1

2

Either:

$data1 = "'" . mysql_real_escape_string($foo) . "'";

or

$value = "(...,'$data1',...)";

Just don't try both options, which would give you (...,''$data1'',...) and kill the query with syntax errors.

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

4 Comments

Thanks this sort of fixed it but I ran into another error which i'm not to sure about. Why does values (Local/120@disc-agents/n,ADDMEMBER,'','','','','') cause an sql syntax error?
does local/120@disc-agents/n look like a valid field name to you?
I am inserting the string local/120@disc-agents/n it is not a Field Name.
then put quotes around it too. insert ... values (Foo) is telling the db to use whatever value is in the Foo field, which makes no sense, because there's no existing record to get that value from in the first place. insert ... values ('Foo') is just a string that contains the letters F, o, o.

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.