2016-07-25 61 views
2

我有以下數組:如何將數組插入到mysql數據庫中?

$dati = array(
    "data" => array(
     'address_complete'=>$data->results[0]->formatted_address, 
     'address_square'=>$data->results[0]->address_components[1]->long_name, 
     'location'=>$data->results[0]->address_components[2]->long_name, 
     'postal_code'=>$data->results[0]->address_components[7]->long_name, 
     'data_ora'=>$tmp_date 
    ) 
); 

,我想插入$dati["data"]['location'] in database. 如何解決

mysql_query("INSERT into utenti(city) VALUES ('$dati[data][location]')") or die (mysql_error()); 

+0

變化'$ DATI [數據] [位置]''到$ DATI [ '數據'] [ '位置']'? – Maximus2012

+0

目前發生了什麼? – chris85

+1

首先,使用[mysqli的(http://stackoverflow.com/questions/8891443/when-should-i-use-mysqli-instead-of-mysql) –

回答

0

起初,使用正確的可變內插:

mysql_query("INSERT into utenti(city) VALUES ('{$dati["data"]["location"]}')") or die (mysql_error()); 

其次mysql_擴展已過時,使用MySQLiPDO_MySQL代替。

+0

有關SQL注入的任何註釋或已棄用的mysql_ *擴展? –

+0

@devlincarnate,看到我的評論 – RomanPerekhrest

+0

使用'{}'括陣列需要在數組鍵的使用引號,否則你會得到未定義的常量警告。 –

0

PHP解析器是不是太貪心了,多維數組在雙引號字符串將不能正常解析。例如

$arr['a']['b'] = 'c'; 
echo "$arr[a][b]"; 

將打印Array[b],像您期望的不c,因爲PHP停止第一[]鍵後解析爲數組。

您必須使用{}擴展標記:

echo "{$arr['a']['b']}"; // prints c as expected 
0

使用的財產以後像下面

mysql_query("INSERT into utenti(city) VALUES ('".$dati['data']['location']."')") or die (mysql_error()); 

注: mysql_擴展已被棄用,使用的MySQLi或PDO_MYSQL代替。