0

I have the following array...

Array
(
    [ID] => 10
    [code] => KA
    [rol] => B
    [pr] => 
)

what I want is when I insert to the MySQL all the empty array key filled with NULL...

here is what I tried...

foreach ($array as $key => $value) {
    $value = trim($value);
    if (empty($value))
        $value .= NULL;

    else
        echo $value;
    } 

or in different way...like this..

$value = implode("', '",array_values($array));
$val = ($value == ' ') ? NULL : "$value";

and insert to table..

$sql = "INSERT INTO table VALUES('$val')";

But it seems I am not getting the NULL value in my fields... what did I do wrong?

In short, how do I add Null to the empty array key...[pr]???

MR.Internet
  • 547
  • 4
  • 19

2 Answers2

1

You could do:

$sql = array();
foreach ($array as $key => $value) {
    $value = trim($value);
    $sql[] = empty($value)?'NULL':"'".addslashes($value)."'";
}
$sql = 'INSERT INTO table VALUES('.implode(",", $sql).')';

echo $value; will not help you if you want to use it as a query.

But: Don't do it! Use prepared statements instead.

Example: http://codepad.org/lZfgVwIL

Christoph Diegelmann
  • 2,004
  • 15
  • 26
  • that is the echo from query.....INSERT INTO table VALUES('','','','','NULL','NULL','NULL','') as you see all the value are lost....some thing wrong? – MR.Internet Sep 11 '13 at 14:55
  • @MR.Test probably your php version doesn't include mysql_real_escape_string() another reason to use prepared statements. – Christoph Diegelmann Sep 11 '13 at 15:00
  • @MR.Test Edited my post and created an example on codepad. Should work now. If you still need this than your using prepared statements the wrong way. They are meant to seperate query and data. – Christoph Diegelmann Sep 11 '13 at 15:02
1

I think you should use double quotes 'NULL' or 'null' instead of NULL.

$val = ($value == ' ') ? 'NULL' : $value;
Sriram G
  • 369
  • 3
  • 14