0

i would like to store data from a form into 2D array but it seems to have problem inserting data into the array. if i were to echo $orderArray[0][$count2] it seems to work but if i were to echo $orderArray[1][$count2] there will be error

$dateArray = array();
$orderArray = array(array());
$amountArray = array(array());
$count = 0;
$count2 = 0;
foreach ($_POST['export'] as $date){ 
    $dateArray[$count] =  $date;
    include "/storescript/connect_to_mysql.php"; 
    $sql = mysql_query("SELECT * FROM ordera WHERE orderDate = '$date' ORDER BY     orderid ASC");
    $productCount = mysql_num_rows($sql); // count the output amount
        if ($productCount > 0) {
            while($row = mysql_fetch_array($sql)){ 
                $orderArray[$count][$count2] = $row["orderAmount"];
                $amountArray[$count][$count2] = $row["itemAmount"];
                $count2++;

            }
        }
            $count++;
    }
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • that depends on your data bu first you can try by moving `$count++;` to your `if ($productCount > 0) {` block, because if your product count is 0 you don't add any element to your arrays – Vytautas Apr 16 '13 at 06:24
  • Can you be more explicit on what you want ? By the way , your inputs are not safe ... – ibi0tux Apr 16 '13 at 06:29
  • You don't need to include the connection file so many times. – hjpotter92 Apr 16 '13 at 06:30
  • Welcome to Stack Overflow! [Please, don't use `mysql_*` functions](http://stackoverflow.com/q/12859942/1190388) in new code. They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the red box? Learn about prepared statements instead, and use [tag:PDO] or [tag:MySQLi]. – hjpotter92 Apr 16 '13 at 06:33

1 Answers1

0

I would reduce the code to this:

// connect here
include "/storescript/connect_to_mysql.php"; 

// make date list safe for querying
$dates = join(',', array_map(function($date) {
    return sprintf("'%s'", mysql_real_escape_string($date));
}, $_POST['export']);

// run query    
$sql = "SELECT * FROM ordera WHERE orderDate IN ($dates) ORDER BY orderid";
$res = mysql_query($sql) or die("Error in query");

// collect results
while ($row = mysql_fetch_array($res)) {
    $orders[$date][] = $row['orderAmount'];
    $amounts[$date][] = $row['itemAmount'];
}

// do stuff with results
foreach ($orders as $date => $orderAmounts) {
    print_r($orderAmounts);
    print_r($amounts[$date]);
}

Also, please learn about PDO or mysqli; the old mysql_ functions are deprecated.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309