02.11: Functions
At some point our scripts will grow and become larger than one page. It is helpful for us as programmers to organize our code and make it readable.
How do we prevent our script from becoming a large, multi page file?
How can we re-use the same code without typing it multiple times?
A function is a piece of code that takes input, processes it, and returns a value. Functions also allow us to organize our code an make it easier to read.
<?php # * Functions # * ------------------------------------------------- /* if ($action == "update") { # ** parse info (check lids) and update db. # ** get list of GIDs $sql = "SELECT group_id FROM groups WHERE cust_id = $cid;"; if ($debug) print "sql = $sql\n"; $result = mysql_query ($sql, $connection ) or die( mysql_error()); $num_gids = 0; while( $row = mysql_fetch_row( $result ) ) $group_id[$num_gids++] = $row[0]; # ** for each GID check the post vars for( $i = 0; $i < $num_gids; $i++ ) { $group_name[$i] = $_GET["$group_id[$i]_name"]; $group_desc[$i] = $_GET["$group_id[$i]_desc"]; $sql_update[$i] = "UPDATE groups SET group_name = \"$group_name[$i]\", group_desc = \"$group_desc[$i]\" WHERE cust_id = $cust_id AND group_id = $group_id[$i];"; } for( $i = 0; $i < $num_gids; $i++ ) { $result = sql_query( $sql_update[$i], $connection ); } ... ... ... ... ... } # * ------------------------------------------------- if ($action == "update") { update_db(); } */ # * ------------------------------------------------- function sum( $a, $b ) { $c = $a + $b; return $c; } $result = sum( 10, 6 ); print "$result\n"; ?>