2

I've got the following array:

$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
    )
);

and I want to insert $dati["data"]['location'] in database. How can I fix

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

?

Fabio97
  • 91
  • 1
  • 2
  • 10
  • Change `$dati[data][location]` to `$dati['data']['location']` ? – Maximus2012 Jul 25 '16 at 21:07
  • What happens currently? – chris85 Jul 25 '16 at 21:07
  • 1
    To begin, use [mysqli](http://stackoverflow.com/questions/8891443/when-should-i-use-mysqli-instead-of-mysql) – devlin carnate Jul 25 '16 at 21:07
  • It says: error @Maximus2012 – Fabio97 Jul 25 '16 at 21:09
  • **WARNING**: If you're just learning PHP, please, do not use the [`mysql_query`](http://php.net/manual/en/function.mysql-query.php) interface. It’s so awful and dangerous that it was removed in PHP 7. A replacement like [PDO is not hard to learn](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/) and a guide like [PHP The Right Way](http://www.phptherightway.com/) explains best practices. Your user parameters are **not** [properly escaped](http://bobby-tables.com/php) and there are [SQL injection bugs](http://bobby-tables.com/) that can be exploited. – tadman Jul 25 '16 at 22:30

3 Answers3

0

At first, use proper variable interpolation:

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

Secondly, mysql_ extension is deprecated, use MySQLi or PDO_MySQL instead.

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

PHP's parser is not greedy, and multi-dimensional arrays in double-quoted strings will NOT parse properly. e.g.

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

will print Array[b], not c as you expect, because PHP stops parsing for arrays after the first [] key.

You have to use the {} extended notation:

echo "{$arr['a']['b']}"; // prints c as expected
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

Use somthing like below

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

Note: mysql_ extension is deprecated, use MySQLi or PDO_MySQL instead.

Vinie
  • 2,983
  • 1
  • 18
  • 29