An example of arrays being used in web development - php

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.

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.

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"];
}

Related

PHP, MySQL - Return which value was used when input is an array?

I'm running a PDO query, something like:
$inputArr = array(val1, val2, val3, ...);
$qMarks = str_repeat('?,', count($inputArr) - 1) . '?';
$stmt = $db->prepare("SELECT id, name, type, level
FROM table
WHERE name IN ($qMarks)");
$stmt->execute($inputArr);
... parse the rows that have been returned
And this works exactly as expected, no hang-ups or anything.
My problem is that I need to know which value from $inputArr was used to get each row returned.
I've tried
WHERE name IN ($qMarks) AS inputVal
and
WHERE name IN ($qMarks AS inputVal)
but those crash the query.
How can I determine which input array value was used to return each row in the output?
EDIT 1
Yes, I understand that the input search value would be name, for this particular case, but the query above is only for demonstration purposes of how I am putting the search values into the query.
The actual is much more complex, and returns any name value with is close (but not always identical).
The AS keyword is not going to work as you expect it. It's mainly used for aliasing subqueries. You can't (to my knowledge) use it in a WHERE clause.
The scenario you've outlined should have the 'name' in $row['name']. If it was a different variable that you wanted to see, you'd simply add it in your SELECT clause.
Great question, and simple answer:
The WHERE name IN $qMarks)"); part of your code is only obtaining the values in your database that are matching your array, so what you can do is see which values of name are present in the row you fetched. For example:
$rows_fetched = $stmt->fetchAll(PDO::FETCHASSOC);
$inputArray = array();
foreach($rows_fetched as $value)
{
$inputArray[] = $value['name'];
}
print_r($inputArray);//printing the results
Now you have the array $inputArray with all the values used to return each row in the output. Let me know if that worked for you!

Get data from exploded values

I have been trying to get data from exploded values, but I am failing miserably and I am completely clueless despite all the researching I've been doing.
This is how the code looks like:
$array = explode(",", $hos['prop_owner']);
list($a) = $array;
$gu = $db->prepare("SELECT * FROM users WHERE user_id = :id");
$gu->execute(array(':id' => $a));
$dau = $gu->fetch();
echo $hos['prop_name']."<br><small>";
if(end($array)){
echo "<a href='/user/view/".$dau['user_id']."' style='color:#".$dau['user_colour']."'>".$dau['user_name']."</a></small><br>";
} else {
echo "<a href='/user/view/".$dau['user_id']."' style='color:#".$dau['user_colour']."'>".$dau['user_name']."</a>,";
}
Currently, the database field $hos['prop_owner'] contains the values "2,20" which are IDs of users (this field can potentially contain more IDs in the future). What I want to do is get all the user data from the exploded values, in this case 2 and 20, and then echo the information out in order as well.
Re-explanation:
I have a field in my database called prop_owner which is supposed to contain an unlimited number of user IDs, seperated by comma. Format: 1,2,3,4.
I want to take the value from this field, then somehow separate the user IDs and separately retrieve the usernames and echo them out.
Example result: Darren, Eva, Miles, Lisbeth
I hope I explained myself good enough to understand where I am trying to go with this.
Thanks in advance!
First of all the query will be like
SELECT * FROM users WHERE user_id in (2,20)
You need the data of both the users so the query will return all the data of all the ids that are being passed here..
You can directly pass here but you need to take care of security... or may be you can check how to pass values securely in such queries ...

Retrieving the data from an sql statement

I have written this code which in theory i want to loop round an array and for every value use in a select statement to retrieve the applicable information. Then map a particular value id as a key and the value from the sql statement as its associated value. Though i cant seem to figure out how to add it as a value into my array im sure im a word out.
heres my code
/*
* Loop through the hasNewModelIdInYear and retrieve the exterior media paths
* with a mapped id as a key.
*/
$mediapatharray = array();
foreach ($hasNewModelIdInYear as $key => $value) {
$selectMediaPathFromValue = "SELECT `name` FROM `media` WHERE `id`='".$value['img1_media_id']."'";
$res = $mysqli->query($selectMediaPathFromValue);
$mediapatharray[$value['model_id']] = $res;
}
All that array returns is an array full of keys but no values.. With the variable $res do i then have to ->fetch_value? as im not sure on the syntax needed in order to access the data from the query?
regards mike
it is not good writing whan you have query inside loop. you should search based on array of img1_media_id
you can do follwing
$selectMediaPathFromValue = "SELECT `name` FROM `media`
WHERE `id` IN = '$hasNewModelIdInYear'";
array should be following format
$hasNewModelIdInYear = "12,21,22,65";
The result will return false on failure or the results on success. Mysqli result will be returned the first set of array that consist of the array index. You will need to fetch the values and store it in array. Try adding this code.
while($row = $res->fetch_assoc()){
$mediapatharray[$value['model_id']] = $row['name'];
}
Thanks for your responses i was trying to make it more complicated than it needed to be. I done it by putting the whole media table in a multidimension array then looping through them both and comparing values and if mathcing id map the name.
simple connection and sql query to populate the array, then map the id to a key and name as its value. heres my code.
mediaarray is an array with the media table contents populated in it
$mediaIdPAthFromOld = array();
foreach ($hasNewModelIdInYear as $hnkey => $hsvalue) {
foreach ($mediaarray as $mpavalue) {
if ($hsvalue['img1_media_id'] == $mpavalue['id']) {
$mediaIdPAthFromOld[$hsvalue['model_id']] = $mpavalue['name'];
}
}
}
though this has done what i wanted i assume there is a more effient way to do this.
regards mike

Assign POST values to an array in a loop and put array into a database

I have an array containing the names of form input names:
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
The names are identical to the corresponding columns in a database. Instead of using an sql query like so:
$bed_min=$_POST['bed_min'];
$bed_max=$_POST['bed_max'];
$rec_min=$_POST['rec_min'];
$rec_max=$_POST['rec_max'];
$bath_min=$_POST['bath_min'];
$bath_max=$_POST['bath_max'];
$value_min=$_POST['value_min'];
$value_max=$_POST['value_max'];
$query = "UPDATE first_page SET bed_min='$bed_min', bed_max='$bed_max', rec_min='$rec_min', rec_max='$rec_max', bath_min='$bath_min', bath_max='$bath_max', value_min='$value_min', value_max='$value_max', WHERE email_address='$email' ";
Is there a way to automate all this into a smaller lump of code? I know the POST values should not be added to the query diectly, so maybe a loop to assign the POST values to a corresponding array of variables using something like:
foreach ($minmax as $var){
$var = $_POST[$var]
}
(nb i dont think this snippet will work but ive added it because I think with a bit of editing it might!)
After the list of variables have been assigned the POST values, do the update in the $query using two arrays, one with the list of values and one with the list of database columns. Again I dont know how this will work, so pointers would be helpful!
You don't really need the $minmax array of form input names since you can get those from the keys of $_POST.
If the values are all numbers, like they seem to be, then you could do it all in one line like this:
$query = "UPDATE first_page SET " . vsprintf(implode("='%d', ", array_keys($sanitized_POST))."='%d'", array_values($sanitized_POST))." WHERE email_address='$email'";
That's assuming you have already sanitized the items from $_POST into a new array named $sanitized_POST. I know you said in the above comment to ignore sanitization, but I thought I'd add it so you know I'm not suggesting to use the values straight from $_POST.
You could sanitize the $_POST array with something like this:
$sanitized_POST = array_map(function($item) {
return mysqli::real_escape_string($item);
}, $_POST);
Honestly though, you should try to come up with a solution that uses prepared statements.
On a side note, if you have the sanitized post array, then this one line will essentially do what Quixrick has done with variable variables in one of the other answers:
extract($sanitized_POST);
If you assume that all of the values in post have the same names (array keys) as your columns, then something like this could work for you:
$query = "UPDATE first_page SET ";
foreach ($_POST as $key => $var){
$query .= " $key='$var',";
}
$query = rtrim($query,',') . " WHERE email_address='$email' ";
You probably want to use 'Variable Variables' here. Basically, you'd use a double dollar sign $$ to create a variable with the name of the array value.
$_POST['bed_min'] = 'Rick';
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
foreach ($minmax as $var){
$$var = $_POST[$var];
}
print "<BR>BED MIN: ".$bed_min;
This outputs:
BED MIN: Rick

mysql query to retrieve every single row of data

$q = "SELECT * FROM user";
$res = mysqli_query($conn, $q) or die(mysql_error());
$userList = "";
while($user = mysqli_fetch_array($res))
{
$userList .= $user['userList'].";;";
}
echo $userList;
I don't understand the while part:
Why assign the mysqli_fetch_array to $user using while?
How can the $user have index of userList?
Why concatenate with ;;?
To answer your questions:
i) mysqli_fetch_array() has two possible return values. It either returns an array of the current row that the database result set pointer points to, then advances the pointer to the next row, or it returns false if you have reached the end of the result set. The while() evaluates the value that is set to $row either continuing the loop if it is an array or stopping the loop if $row equals false
ii) The $user array has both numerical indexes for each field (i.e. 0,1,2,... [#fields - 1]) and associative indexes of the column names for the table (i.e. 'field1', 'field2', etc.). In this case one of the fields in the database is userList, so accessing $user['userList'] returns that column value for the row being worked with. BNote that the query itself would have beeter been written as SELECT userList FROM user since that is the only field you are interested in. There is no reason whatsoever to select and transfer all field data if you have no need for it. It is also rarely useful to use just mysqli_fetch_array(), as you rarely need both numerical and associative indexes on the record.It is usually best to specifically request ther associative or numerical array result depending on which you need.
iii) This code is simply building a string rather than an array of results which might be more common. For whatever reason the code writer decided values in the string should be separated by ;;.

Categories