Check if value exists in array before inserting into database - php

I have an array that is returned from an API although some keys/values are not present all of the time.
example array
Array
(
[example0] => data
[example1] => data
[example2] => data
[example3] => data
)
Now if I use a query such as below
$dbh = $this->database->prepare("INSERT INTO table(example0, example1, example2, example3)VALUES(:example0, :example1, :example2, :example3)");
$dbh->execute(array(
"example0" => $data['example0'],
"example1" => $data['example1'],
"example2" => $data['example2'],
"example3" => $data['example3']
));
It will work fine. But when the API returns an array like
Array
(
[example0] => data
[example1] => data
[example3] => data
)
It will cause an error due to a value not being set, is there a way to just have it enter nothing into the column rather than throw an error? I am using a really big query for this so writing an if/else for each value would not be a good idea (in my opinion, for performance wise)

You have to check if the key is set and eventually is there is a value:
if(isset($array['your_key']) && !empty($array['your_key'])) { }
I cannot make it clear from your code but validate everything before you use it in a query.
[Edit] Example:
$keys = array('example1', 'example2', 'example3', 'example4');
$use_in_query = array();
foreach($keys as $key)
{
if(isset($array[$key]) && !empty($array[$key])) $use_in_query[$key] = $array[$key];
}
Now you can use the $use_in_query var in your query.
$dbh->execute($use_in_query);
[/Edit]

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

Build PHP array from query

I'm currently manually building an array.
$this->array_list = array('Alaska' => 'Alaska',
'Amanda' => 'Amanda',
'America' => 'America',
'Anthea' => 'Anthea',
'Arena' => 'Arena',
'Atlantis' => 'Atlantis'
);
I have a database that i can query this list from, My question is how do I create the array with key and value once getting the list from the query? Key and Value will always be the same. Using mysql and codeigniter.
Query DB for list, create two arrays and use combine? Has to be an easier way?
Here is what I ended up doing. Probably not the best way, feel free to give better way to do this.
$sofa_list2 = $this->get_media_model->get_sofas();
foreach ( $sofa_list2 as $k=>$v )
{
$newkey = $sofa_list2[$k]['collection_name'];
$sofa_list2[$k] ["$newkey"] = $sofa_list2[$k] ['collection_name'];
unset($sofa_list2[$k]['collection_name']);
}
$sofa_list2 = call_user_func_array('array_merge', $sofa_list2);

PHP: most efficient way to update an array that has as its keys correspondent to variables' names

Could please anyone provide some help in finding a way to process user input (from a post), which is held as variables (obviously) and in which variables' names are correspondent with extracted from database array's keys.
I'm asking this question in hope of getting not just a solution but the best (most concise) possible example.
At the moment, I could achieve it by using loops with if/else and implode/explode, but I thought that there is, maybe, a chance of doing it in some better way, for example, using built-in PHP functions made for processing arrays with usage of anonymous functions at the same time?
Code and comments:
// User id to be processed (extracted from a post)
$id = '8ccaa11';
// Posted new (updated) settings about the user above (extracted from a post)
$individuals_read_access = false;
$individuals_write_access = false;
$calendar_read_access = false;
$calendar_write_access = true;
$documents_read_access = true
$documents_write_access = false
// Current records extracted from database
Array
(
[individuals_read_access] => 8ccaa11
[individuals_write_access] => 8ccaa11
[calendar_read_access] => 8ccaa11|00cc00aa
[calendar_write_access] => 8ccaa11
[documents_read_access] => 8ccaa11
[documents_write_access] => 8ccaa11
)
// Expected array to be posted back to database
Array
(
[individuals_read_access] =>
[individuals_write_access] =>
[calendar_read_access] => 00cc00aa
[calendar_write_access] => 8ccaa11
[documents_read_access] => 8ccaa11
[documents_write_access] =>
)
Could anyone please help to find the best and most concise solution to get expected array?
The problem about an solution using anonymous function is that you cannot access your variables. I created two solutions to demonstrate the case:
Version 1 was removed by request of Illis, see post history :)
Version 2. Inputs as array, use can pass them easily to the anonymous function. Read more about closures and array_walk.
<?php
$id = '8ccaa11';
$inputs = [
'individuals_read_access' => false,
'individuals_write_access' => false,
'calendar_read_access' => false,
'calendar_write_access' => true,
'documents_read_access' => true,
'documents_write_access' => false
];
// Current records extracted from database
$records = [
'individuals_read_access' => '8ccaa11',
'individuals_write_access' => '8ccaa11',
'calendar_read_access' => '8ccaa11|00cc00aa',
'calendar_write_access' => '8ccaa11',
'documents_read_access' => '8ccaa11',
'documents_write_access' => '8ccaa11'
];
array_walk($records, function(&$value, $key) use ($inputs, $id) {
if (!isset($inputs[$key])) {
continue;
}
$rights = empty($value) ? [] : explode('|', $value);
$index = array_search($id, $rights);
if (!$inputs[$key] && $index !== false) {
unset($rights[$index]);
} else {
array_push($rights, $id);
}
$value = implode('|', array_unique($rights));
});
var_dump($records);

Only last value returned in an associative array

Here is my code that I am working on to create an array so the end product will return the following:
$values=user_email => displayname
user_email => displayname
user_email => displayname
I am using the array listed below:
array [0] => std.class Object( [id] = 12
[user_login] = bob
)
[1] => std.class Object( [id] = 15
[user_login] = frank
)
When I run my code that is listed below it only runs on the last value. I have tried using the "." at the variable name but it only seems to add it to the variable instead of the array where I need it.
What I hope to do is:
Run a wp_user_query to return all the personnel in a group
get the results
after I get the results, use the [id] for each user to determine their $displayname and $email
they are then sent into a new array using their email as key
Here is the code that I have been working on, and as of right now it does everything correctly except return every user, it only returns the last user
function show_user_dropdown($values, $field){
if( $field->id == 155 ){
$wp_user_search = new WP_User_Query( array( 'role' => 'Hrrepresentative', 'fields' => array('user_login', 'ID') ) );
$authors = $wp_user_search->get_results();
$value['options']=array();
foreach ($authors as $a) {
$displayname=get_the_author_meta('display_name', $a->ID);
$emailname=get_the_author_meta('user_email', $a->ID);
$validation=array($emailname=>$displayname);
$values['options']=$validation;
$values['use_key'] = true;
}
}
return $values;
}
What do I need to do to fix this?
You have both 'values' and 'value'. I don't think the array notation is working how you think it is. I think you'd be better off doing something like this:
$values[$id]['option'] = $validation;
edit: to elaborate, you only have 1 value for $values (the last run through the foreach loop). You also would be overwriting the previous value in $values['option'] regardless. You need to use a multidimensional array with an index.
To get the array structure you showed, try:
$values['options'][$emailname] = $displayname;
You are reassigning $values['options']=$validation; in your loop.
Use it this way:
$values['options'][]=$validation;

Do I need to write a custom session class for CodeIgniter?

I cannot seem to get CI's session library to function the way I want it to. Essentially, I am storing 2 different categories of data within the sessions. The data within the 2 categories may contain the same value. Right now my attempt to add a key => value pair to the session is failing, as it is only allowing 1 key => value pair to be associated with the array. It overrides itself each time I do a post.
$arr = array(
'favorite_products' => array(),
'viewed_products' => array()
);
$arr["favorite_products"][] = $fav_id;
$this->session->set_userdata($arr);
This is what the array looks when I print_r it:
Array ( [favorite_products] => Array ( [4f1066c2b7fff] => 1648406 ) [viewed_products] => Array ( ))
Am I doing something wrong, or is this just the way CI's session library works?
Make sure you are destroying your session between attempts, but this code should work just fine...
$arr = array(
'favorite_products' => array(),
'viewed_products' => array()
);
$arr["favorite_products"][] = $fav_id;
$arr["favorite_products"][] = 033333; // another id
$this->session->set_userdata($arr);
should give you...
Array (
[favorite_products] => Array (
[0] => 1648406,
[1] => 033333
),
[viewed_products] => Array ()
)
If you are trying to do this between requests...
// if it doesn't already exist in the session, create an empty array.
if( ! ($favorite_products = $this->session->get_userdata("favorite_products")))
{
$favorite_products = array();
}
$favorite_products[] = "new id or info";
$this->session->set_userdata("favorite_products", $favorite_products);

Categories