Skip adding to array if it exists in PHP - php

I am using in_array function to skip adding the same addresses to an array.
Code:
$addresses_list = array();
$stmt_select_address_result = $databaseManager->connect()->prepare("SELECT lat,lng,address FROM api_order where userid=683;");
$stmt_select_address_result->execute();
while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {
if (!in_array($row, $addresses_list)) {
array_push($addresses_list, $row);
}
}
I want to skip adding to the arrays if $row['address'] is the same as an address of $addresses_list['address'].

You can create a temporary variable to store the value of address already stored in the $addresses_list array. Whenever, you are storing a $row in the $addresses_list array, you can store the address key value in the temporary variable.
Now, everytime you need to check against the temporary variable, whether the key value already exists or not.
Note that even PHP documentation recommends using [] operator against array_push(). So I have changed your code to use [] instead.
Note: If you use array_push() to add one element to the array, it's
better to use $array[] = because in that way there is no overhead of
calling a function.
Try below (explanation in comments):
$addresses_list = array();
$temp_addresses = array(); // Create a temp array
$stmt_select_address_result = $databaseManager->connect()->prepare("SELECT lat,lng,address FROM api_order where userid=683;");
$stmt_select_address_result->execute();
while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {
// check in temporary variable instead
if (!in_array($row['address'], $temp_addresses)) {
// add to temp array to avoid duplicate entry in next loop
$temp_addresses[] = $row['address'];
$addresses_list[] = $row;
}
}
If you really want unique address values only, and there is no other use of the duplicate rows. You can rather solve this problem at the SQL query end itself. You can simply use GROUP BY on address. This will optimize the data packet being transferred from database server to PHP application. Moreover, additional array operations can be done way with.
$addresses_list = array();
// It is a good practice to have query string in a separate variable
$sql = "SELECT lat,lng,address
FROM api_order
where userid=683
GROUP BY address;"
$stmt_select_address_result = $databaseManager->connect()->prepare($sql);
$stmt_select_address_result->execute();
while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {
// No need for any checks, as you are getting unique addresses only
$addresses_list[] = $row;
}

Related

How to fetch data using loop PHP statement from mysql to ios?

My system is composed of 3 components.
ios - php - mysql
If ios users select multiple 'id's,
then, ios app posts these selected 'id' request to server,
and, the server finds the data based on selected 'id's in MySQL.
and finally, the server passes these data to ios app.
These are the PHP statements I tried.
<?php
$id_0 = $_POST['0'];
$id_1 = $_POST['1'];
$id_2 = $_POST['2'];
$id_3 = $_POST['3'];
...
$id_n = $_POST['n'];
$conn = mysqli_connect('address', 'user', 'password', 'database');
$sql = "SELECT * FROM firstname WHERE id = '$id_0'";
if ($result = mysqli_query($conn, $sql)) {
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($resultArray, $tempArray);
}
} else {
}
mysqli_close($conn);
?>
To get multiple 'id' data, I found that I need to use loop statement.
But the problem is, the number of selected id are variable.
I think that in this code, I need two loop statement.
To get multiple data based on multiple id(the number of id are variable)
To append these data into array
I don't know how to use loop statement when the range is not defined.
How can I use loop statement in PHP, and how can I rearrange these codes?
I'm sure this question is a duplicate but I can't find an exact source.
Your current method means you need to run a whole MySQL query for each iteration.
As the query results will never change what the iteration contains, therefore; you can simply rework it to use MySQL IN to load all of your variables at once:
Step 1) Take all the values and place them in a single array.
$new = []; //new array
foreach ($_POST as $key=>$id){
// Check it is a numeric key
// Check id value is valid to avoid importing other POST values
if((int)$key == $key && (int)$id == $id){
$new[] = $id;
}
}
The above code block is nessecary to stop using values from $_POST['button'] or other posted data that should not be included. This step can be removed if you can clarify your posted data, such as saving all ids to a $_POST['id'] array itself.
Step 2) Empty the array of null/void or repeated values.
$new = array_unique($new);
Step 3) Turn the array into a string, inside the SQL
$arrayString = implode(',',$new);
Step 4) Plug the string into the SQL IN clause:
$sql = "SELECT * FROM firstname WHERE id IN (" . $arrayString . ") ORDER BY id";
Simplified and reduced:
$new = []; //new array
foreach ($_POST as $key=>$id){
if((int)$key == $key && (int)$id == $id){
$new[] = $id;
}
}
$new = array_unique($new);
$sql = "SELECT * FROM firstname WHERE id IN (" .
implode(',',$new) . ") ORDER BY id";
The SQL query above will give you an array of arrays, each one a different row. You can the order them, sort them and output them in PHP as you wish.
See also: This Q&A.
BUT
As expressed by others, you really, REALLY should be using Prepared Statements with MySQLi.
See also here, here and here to see further how to do it and WHY you should do it.
Top Tips:
Numerical columns (typical of id columns) in MySQL do not need the ' quotes.
Until you're using Prepared Statements you can typecast the variables to integers ((int)$var) to limit risk.
It is better to specify the columns you need rather than to use the * catch-all.
Your $_POST data should be an array $_POST['ids'][...].
Eat five different pieces of fruit or veg' a day.
Never trust user input!

PHP/MySQL - how to push additional elements into array in the "while" loop?

I'm pulling the information from an mySQL database, but I need to add additional fields that are not in the database.
The code below works fine, until one of the commented options is enabled:
$sth = mysqli_query($db_connect,$sql);
while($r3 = mysqli_fetch_assoc($sth)) {
//array_push($r3, 'str_close'=>$est_close_time);
//$r3['str_close']=>$est_close_time;
$row_v3_data[]=$r3;
}
Once enabled, the php shows "Error 500"
The simplest way would be to add the other data to $r3 before adding it to the array
$sth = mysqli_query($db_connect,$sql);
while($r3 = mysqli_fetch_assoc($sth)) {
$r3['str_close'] = $est_close_time;
$row_v3_data[] = $r3;
}
This assumes $est_close_time actually exists before using it
you can add a key and an element to an associative array at the same time. the format is just:
$r3['str_close'] = $est_close_time;
no need for an explicit push

While loop to gather data from database until array contains a certain value

I'm trying to create a while loop in PHP which retrieves data from a database and puts it into an array. This while loop should only work until the array its filling contains a certain value.
Is there a way to scan through the array and look for the value while the loop is still busy?
to put it bluntly;
$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($sql)){
//Do stuff
//add it to the array
while($array !=) //<-- I need to check the array here
}
You can use in_array function and break statement to check if value is in array and then stop looping.
First off, I think it'd be easier to check what you're filling the array with instead of checking the array itself. As the filled array grows, searching it will take longer and longer. Insted, consider:
$array = array_merge($array, $row);
if (in_array('ThisisWhatIneed', $row)
{
break;//leaves the while-loop
}
However, if you're query is returning more data, consider changing it to return what you need, only process the data that needs to be processed, otherwise, you might as well end up with code that does something like:
$stmt = $db->query('SELECT * FROM tbl');
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if ($row['dataField'] === 'username')
{
$user = $row;
break;
}
}
WHERE could help a lot here, don't you think? As well taking advantage of MySQL's specific SELECT syntax, as in SELECT fields, you, need FROM table, which is more efficient.
You may also have noticed that the code above uses PDO, not mysql_*. Why? Simply because the mysql_* extension Is deprecated and should not be used anymore
Read what the red-warning-boxes tell you on every mysql* page. They're not just there to add some colour, and to liven things up. They are genuine wanrings.
Why don't you just check each value when it gets inserted into the array? It is much more efficient than iterating over the whole array each time you want to check.
$array = array();
$stopValue = ...
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($sql)){
array_push($array,$row['column']);
if($row['column'] == $stopValue){
// The array now contains the stop value
break;
}

Array not containing values when using "in_array" (php) w/ mysql_query

I continue to struggle with array! This is probably easy to answer.
I'm retrieving a data set from MYSQL w/ PHP. I get an array that has the 1st row (ala the mysql_fetch_array). Typically I would just loop through this and get each value, but in this case I'm already in the middle of a loop and I need to find out if a particular value exists in the full data set (which will be more than 1 row).
I figured I could just loop through and put all the values into an array with something like:
$query = "SELECT MapId FROM Map Where GameId = $gl_game_id";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
$map_set = array();
while($row = mysql_fetch_assoc($result_set)) {
$map_set[] = $row;
}
When I print_r this, I do in fact get the full data set (e.g. all rows of MapId from table Map).
So now, when I go to look in there and see if a value (that is coming out of this other loop) exists, it won't find it.
So my code looks like:
if (in_array($i, $map_set)) {
echo "yes, it's there baby!";
}
But it doesn't work. I tried hard coding the array, and that does in fact work. So there is simply something wrong with the way I'm constructing my array that this function doesn't like it.
if (in_array($i, array(40,12,53,65))) {
echo "yes, it's there baby!";
}
arrrg... I do hate being a noobie at this.
Function mysql_fetch_assoc returned array.
If you make print_r($map_set) then you will see that is 2-dimension array. Sure in_array not worked.
Just replace $map_set[] = $row; by $map_set[] = $row["MapId"]; and then try again.

An example of arrays being used in web development

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

Categories