Im trying to turn a array that haves another array from a SQL select into a unique variable to send it for users by PHPMailer, I tried to place the array on variable of PHPMailer so didnt works, thats why Im trying this way that looks a little bit difficult
public static function getUsersByEmail($email) {
$sql = DB::prepare(
"SELECT username FROM users WHERE email=:email ORDER BY id LIMIT 10"
);
$sql->bindParam('email', $email);
$sql->execute();
$accounts = $sql->fetchAll(PDO::FETCH_ASSOC);
return $accounts; // its array
}
public function recoverUsername($email) {
if (User::emailHasAccounts($email) == true) {
$accounts = [User::getUsersByEmail($email)];
$str = implode(",", $accounts); // imploding array
$mail = new Mail([
'email' => $email,
'subject' => SITENAME,
'template' => 'accountslist',
'variables' => json_encode([
'email' => $email,
'accountList' => $str,
'date' => date('d/m/y h:i')
]),
'time' => time(),
'next_attemp' => time(),
'attemps' => 0,
'status' => 0
]);
// $mail->dbInsert();
return true;
} else {
echo "erro";
return false;
}
}
Solution (for PHP 5.5 <)
$accounts = getAccounts();
$rr = array_column($accounts, 'username');
$array = implode(',', $accounts);
$getaccounts = array_map(function ($accounts) {
return $accounts['username'];
}, $accounts);
$var = implode('<br>', $getaccounts);
Related
i'm new to Google Sheets API,
currently i am develop a system to send data to google sheets.
And while im trying to send the data, it shows error like: Invalid values [0][0]
Below is my code line.
`
$client = getClientAuth();
$spreadsheet_ID = $this->spreadsheet->spreadsheetId;
$range = "Sheet1";
$values = $this->sheetData;
$this->service = new Sheets($client);
$body = new ValueRange([
'majorDimension' => 'ROWS',
'values' => [array_map(function($nv) {
return (is_null($nv)) ? "" : $nv;
},$values)]
]);
$params = ['valueInputOption' => 'RAW'];
$insert = ['insertDataOption' => 'INSERT_ROWS'];
//executing the request
$data = $this->service->spreadsheets_values->append($spreadsheet_ID, $range,
$body, $params, $insert);
return $data;
`
From your error message and your showing script, I thought that in your situation, $values might be a 2-dimensional array. I think that if $values is a 1-dimensional array, your script works. And also, please include 'insertDataOption' => 'INSERT_ROWS' in $params. So, in this case, how about the following modification?
From:
$body = new ValueRange([
'majorDimension' => 'ROWS',
'values' => [array_map(function($nv) {
return (is_null($nv)) ? "" : $nv;
},$values)]
]);
$params = ['valueInputOption' => 'RAW'];
$insert = ['insertDataOption' => 'INSERT_ROWS'];
//executing the request
$data = $this->service->spreadsheets_values->append($spreadsheet_ID, $range,
$body, $params, $insert);
To:
$body = new ValueRange([
'majorDimension' => 'ROWS',
'values' => array_map(function($row) {
return array_map(function($col) {
return (is_null($col)) ? "" : $col;
}, $row);
}, $values)
]);
$params = ['valueInputOption' => 'RAW', 'insertDataOption' => 'INSERT_ROWS'];
$data = $service->spreadsheets_values->append($spreadsheet_ID, $range, $body, $params);
or
$body = new Google_Service_Sheets_ValueRange([
'majorDimension' => 'ROWS',
'values' => array_map(function($row) {
return array_map(function($col) {
return (is_null($col)) ? "" : $col;
}, $row);
}, $values)
]);
$params = ['valueInputOption' => 'RAW', 'insertDataOption' => 'INSERT_ROWS'];
$data = $service->spreadsheets_values->append($spreadsheet_ID, $range, $body, $params);
Note:
When the arrow function is used, I think that the following modification can be used.
From
'values' => array_map(function($row) {
return array_map(function($col) {
return (is_null($col)) ? "" : $col;
}, $row);
}, $values)
To
'values' => array_map(fn($row) => array_map(fn($col) => (is_null($col)) ? "" : $col, $row), $values)
I'm working on my REST API responses with PHP.
Here is my backend that generates the responses:
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r(json_encode($obj));
and with that I have the following response: an array of json objects
[
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
]
What I would like to do is return a new object, something like this:
{
"apiVersion": "2.0",
"data": {
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
}
}
Does anyone have any idea how I could implement this? thanks!
You can easily have a class or function to do that for you. Some thing like below should help,
// provided you are using php > 7 . otherwise parmas
// can become $data, $apiversion ( without typecasting )
function api_reponse(array $data, string $apiVersion)
{
return json_encode([
'apiVersion' => $apiVersion,
'data' => $data
])
}
You can then use,
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r( api_response($obj, '2.0') );
I have this code :
public function changeProfile ($first_name, $last_name, $email, $phone, $password,
$bank_name, $bank_account_number, $bank_account_name,
$gender, $birthday, $address, $area, $default_type) {
$this->connect();
$data = array ('first_name' => $this->escapeString($first_name),
'last_name' => $this->escapeString($last_name),
'email' => $this->escapeString($email),
'phone' => $this->escapeString($phone),
'password' => $this->escapeString($password),
'bank_name' => $this->escapeString($bank_name),
'bank_account_number' => $this->escapeString($bank_account_number),
'bank_account_name' => $this->escapeString($bank_account_name),
'gender' => $this->escapeString($gender),
'birthday' => $this->escapeString($birthday),
'address' => $this->escapeString($address),
'area' => $this->escapeString($area),
'default_type' => $this->escapeString($default_type));
$this->update('user', $data, 'email = "'.$email.'" AND phone = "'.$phone.'"');
$res = $this->getResult();
}
Now, I have a problem like this :
I want to 'skip' some variables on the function, for example $birthday and $gender, so that it won't be processed on SQL UPDATE and let the current data as it is.
I mean, if $birthday and $gender data doesn't exist, then don't update existing data on the table. because when I tried to use NULL as variables on the function, my data replaced with empty data.
how to manage this situation without having multiple if to check each variables?
thank you
If you have the option, you should replace your function's argument list with an array of arguments, for example:
public function changeProfile($variables)
{
$this->connect();
$data = array();
foreach ($variables as $key => $value) {
$data[$key] = $this->escapeString($value);
}
// Validation?
if (!isset($data['email'], $data['phone'])) {
die('Required fields missing.');
}
$this->update('user', $data, 'email = "' . $data['email'] . '" AND phone = "' . $data['phone'] . '"');
$res = $this->getResult();
}
This assumes that the SQL query is static. You could also add some more fields to it if you needed to.
You'd then call it like this:
$test->changeProfileUpdated([
'first_name' => 'john',
'last_name' => 'doe',
'email' => 'example#example.com',
'phone' => 12345,
'password' => 'password1',
'bank_name' => 'ANZ',
'bank_account_number' => '123-456',
'bank_account_name' => 'J DOE',
'gender' => 'M',
'birthday' => '1/2/13',
'address' => '12 Fake St',
'area' => 'Area 51',
'default_type' => 'Some default'
]);
Here's a demo comparing your code, this example and a validation failure.
If you cannot change the method signature to take an array instead you can naturally check each value with isset() or empty() depending on your data needs like:
if (!empty($gender) {
$data['gender'] => $this->escapeString(escapeString);
}
However this is tedious. A better way would be to take an array as an input and then have an array of valid and or required keys. Something like this:
class MyClass
{
private $valid_keys = [
"first_name", "last_name", "email", "phone", "password",
"bank_name", "bank_account_number", "bank_account_name",
"gender", "birthday", "address", "area", "default_type"
];
public function changeProfile($profile)
{
// Return valid keys
$profile = array_filter($profile, function ($key) {
return in_array($key, self::$valid_keys);
} , ARRAY_FILTER_USE_KEY);
// Escape values
$profile = array_map(function ($value) {
// .. your escape function
}, $profile);
// Do your stuff
$this->update('user', $profile, 'email = "'. $profile['email'].'" AND phone = "'.$profile['phone'].'"');
$res = $this->getResult();
}
}
That way you'll only set valid data and you have a way of escaping it generically.
Oh yeah and of course only the values in $profile will get send to your update function.
If you cannot change the method signature you can look into using func_get_args().
public function changeProfile($first_name, $last_name, $email, $phone, $password,
$bank_name, $bank_account_number, $bank_account_name,
$gender, $birthday, $address, $area, $default_type)
{
$args = func_get_args();
$profile = [];
// Important: $valid_keys should be the same as your function parameters and in the same order for this to work. If you want to go further you can look at `ReflectionMethod` to get the names through reflection.
foreach ($args as $index => $value) {
$key = self::$valid_keys[$index];
$profile[$key] = $this->escapeValue($value);
}
// Do your stuff
$this->update('user', $profile, 'email = "'. $profile['email'].'" AND phone = "'.$profile['phone'].'"');
$res = $this->getResult();
}
check if it is null or not then save it in an array as given below
function changeProfile ($first_name, $last_name,$email,$phone) {
$this->connect();
$data=array();
if($first_name!=""){
$data['first_name']= $this->escapeString($first_name);
}
if($last_name!=""){
$data['last_name']=$this->escapeString($last_name);
}
if($email!=""){
$data['email']=$this->escapeString($email);
}
if($phone!=""){
$data['phone']=$this->escapeString($phone);
}
$this->update('user', $data, 'email = "'.$email.'" AND phone = "'.$phone.'"');
$res = $this->getResult();
}
I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1
I am trying to declare a function parameter inside my array, but I'm having trouble getting it to work. I've trimmed it down for simplicity purposes, and I have something like:
function taken_value($value, $table, $row, $desc) {
$value = trim($value);
$response = array();
if (!$value) {
$response = array(
'ok' => false,
'msg' => "This can not be blank."
);
} else if (mysql_num_rows(
mysql_query(
"SELECT * FROM $table WHERE $row = '$value'"))) {
$response = array(
'ok' => false,
'msg' => $desc." is already taken."
);
} else {
$response = array(
'ok' => true,
'msg' => ""
);
}
echo json_encode($response);
}
Notice the function parameter $desc trying to be used in the array here:
'msg' => $desc." is already taken.");
The whole function works fine EXCEPT when I try to add the $desc to the array results.
How could this be done?
Do you have an open resource handle to your database? You are not passing one to the query function.