0

$ct is my array: array(4) { ["a"]=> int(1) ["b"]=> int(2) ["z"]=> int(2) ["c"]=> int(1) }

I need to put it in a two column database where "item" is col1 and "count" is col2 where the first row has an "a" in col1 and 1 in col2, 2nd row has a "b" in col1 and 2 in col2, etc.

What do I put after VALUES ($result = mysql_query("INSERT INTO test2(item,ct) VALUES ???) or die(mysql_error())

or do I need to use another approach?

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by niche1
0
<?php
$ct = array (
             "a" => 1,
             "b" => 2,
             "z" => 2,
             "c" => 1
            );

$con = mysql_connect('localhost','david','mypwd');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("daniweb", $con);

foreach($ct as $item => $count){
    $sql = "INSERT INTO test2(item,ct) VALUES ('$item', $count)";
    if ($result = mysql_query($sql)) {
        echo "One row inserted for $item\n";
    }
    else {
        echo "Failed to insert $item\n";
    }
}

mysql_close($con);
?>
0

Thanks to d5e5. I was slowly coming to a similar answer. You helped me solve the question much faster.

Niche

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.