Re: array problems

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 8/16/06, David Tulloh <david@xxxxxxxxxxxx> wrote:
Chris G wrote:
foreach ($user_input_array as $user_input) {
        $data_member = array(); # Create an empty array

        Do SQL query stuff

        foreach ($sql_results as $sql_member) {
                $data_member[] = $sql_member;
        }

        $data[] = $data_member;
}

You can now do your function call as
$gbarplot = new GroupBarPlot($data);

The downside to this approach is that you'll end up making a SQL call
for each value in the array.  An alternative would be to build a
comma-delimited string of values and use SQL's IN() check.  Example:

[code]
// CAUTION: Validate your data to protect from SQL Injection, like David says!
// Assuming you've done this, $per_ids_array contains valid/clean/safe data
// that was originally submitted through $_GET['per_id'].
// Let's turn that array into a comma-delimited string using implode()
$per_ids_string = implode(',', $per_ids_array);

// Now plug the string into our SQL query:
$query = 'SELECT rep_l_per_id, rep_value_perc FROM report_values WHERE
rep_l_per_id IN (' . $per_ids . ') ORDER BY rep_l_per_id ASC';

// execute
$result = mysql_query($query) or die (mysql_error());

// Before looping through our result set, initialize two variables:
$gbp_data = array();    // this will be the final array to be passed
to GroupBarPlot()
$temp_id = NULL;    // use this to determine the result set has moved
to a new rep_|_per_id
while($line = mysql_fetch_array($result)) {
    // IF $temp_id does not match the current rep_|_per_id,
    // create a new element of $gbp_data as an array.
    // Also, set $temp_id to this rep_|_per_id value to use in the
next iteration.
    if ($temp_id != $line['rep_|_per_id']) {
         $temp_id = $line['rep_|_per_id'];
         $gbp_data[$temp_id] = array();
    }

    // Add rep_value_perc as an array element
    $gbp_data[$temp_id][] = $line['rep_value_perc'];
}

// Now pass to your function:
$gbarplot = new GroupBarPlot($gbp_data);
[/code]

It's all untested, but I *think* will work out of the box.

And now a bit of bonus advice.  The SQL query that you provided earlier
has a giant SQL injection attack problem.  I'd recomend reading a little
about SQL injection attacks and getting it patched up.


Yeah, this cannot be stressed enough!!!

HTH,
John W

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux