0

I got an associative array that looks like

$rates = array (
    'AUD' => '0.5',
    'BRL' => '1.2',
    'CAD' => '0.6',
    'CHF' => '0.4',
    'CZK' => '1.5',
 );

I want to put this array in mysql so that i can use the rates to make an currency converter. mine question is how do you do that i tried

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "eurotoforgein";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$table = 'rates';

$keys = implode(', ', array_keys($rates));
$values = "'" . implode("','", array_values($rates)) . "'";

$sql = 'insert into '.$table.'('.$keys.') values ('.$values.')';


if(!$result = $conn->query($sql)){ 

die('There was an error running the query [' . $conn->error . ']'); 

}

else{
echo "Data inserted.";
}

the error i got is There was an error running the query [Unknown column 'AUD' in 'field list'] for the table used

// sql to create table
$sql = "CREATE TABLE eurotoforgein (
COUNTRY VARCHAR(6),
RATES FLOAT(10)

)";

if ($conn->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

any help is welcome thanks

3
  • I'll give you a hint. INSERT INTO eurotoforgein (COUNTRY, RATES) VALUES ('AUD', 0.5), not INSERT INTO eurotoforgein (AUD) VALUES (0.5) Commented May 24, 2016 at 15:45
  • SQL requires string literals to be quoted (same as almost every single programming language that exists).... better yet, enter the 21st centurey and use prepared statements with bind variables using MySQLi or PDO Commented May 24, 2016 at 15:46
  • Note also that money is frequently DECIMAL Commented May 24, 2016 at 17:12

1 Answer 1

2

you can generate an insert for multiple values like this

$pairs = [];
foreach($rates as $key => $value)
{
    $pairs[] = "('$key', $value)";
}
$pairs_str = implode(',', $pairs);

$sql = 'insert into '.$table.' (COUNTRY, RATES) values ' . $pairs_str;
Sign up to request clarification or add additional context in comments.

Comments

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.