views:

163

answers:

2

I was talking to a person today who mentioned he used arrays when calling parameters or for other reasons when pulling data from the database etc.

Basically my question is: how would you use arrays in web development?

For example:

If you had a url like this (a social dating site)

http://www.example.com/page.php?sid=1&agefrom=30&ageto=40&sex=female&loccation=los angeles

How I would query the browse page (when showing a list of users) is

$id = mysql_real_escape_string($_GET['id']);
$agefrom = mysql_real_escape_string($_GET['agefrom']);
$ageto = mysql_real_escape_string($_GET['ageto']);
$sex = mysql_real_escape_string($_GET['sex']);
$location = mysql_real_escape_string($_GET['location']);

mysql_query("select from table where id = '$id' and  agefrom='$agefrom' [.....the rest of the query]")

Can this be done with arrays? What if a location wasn't selected or the age wasn't entered? If i did the query it might fail.

I hope my question is more clear now.

+2  A: 

Arrays make it easy to hold a set of values, or key => value pairs, inside a variable. It also makes it easy to iterate over a set of values.

foreach ($myarray as $key => $value)
{
  // do something with this key and value
}

If you are passing a large number of values to a function, and this set of values could be thought of as a list or a lookup table, then you would use an array.

Please consult the PHP manual on arrays for more information.

Edit:

I think I see what you mean now. It can be helpful to sort of 'abstract' your database calls by creating a function that accepts values as an array. For example:

function editrecord($recordid, $values)
{
  // SQL is generated by what is in $values, and then query is run
  // remember to check keys for validity and escape values properly      
}

That's an extreme simplication of course.

thomasrutter
+1  A: 

Arrays are an important feature of any language, they have O(1) (constant time) random access and can be used as a base data structure to make more complex types.

Specifically talking about PHP, the arrays are used VERY often, the language itself uses them for example to grab the GET and POST parameters.

To get data, you can also make use of arrays in PHP.

You can use mysql_fetch_assoc, this will retch a result row from the database as an associative array, each index of the array will represent a column of data of the current row:

//...
$sql = "SELECT id as userid, fullname, userstatus 
        FROM   sometable
        WHERE  userstatus = 1";

$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    // Here, the $row variable is an associative array.
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}
CMS