K
K
kirigili2021-07-25 14:19:09
PHP
kirigili, 2021-07-25 14:19:09

Write array to database?

Please tell me how to write an array to the database. It seems to me)) I'm doing everything right, but unfortunately it only writes the last line of the array. Somewhere I'm dumb.

$coin_name_id = file_get_contents_data();

foreach ($coin_name_id as $id){
    var_dump($id);
    $sql = "INSERT INTO coins_info_table (coin_name_id) VALUES ('".$id."')";
}
if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);


The file_get_contents_data() function returns an array of the form:

Array (
[0] => bitcoin
[1] => ethereum
[2] => tether
[3] => binancecoin
....
[398] => dao-maker
[399] = > boringdao-[old] )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-07-25
@kirigili

The most kosher option, according to the PHP documentation

$stmt = $mysqli->prepare("INSERT INTO coins_info_table (coin_name_id) VALUES (?)");
$stmt->bind_param("s", $id);

foreach ($coin_name_id as $id) {
    $stmt->execute();
}

Try PHP code online

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question