display last 10 months based on a specific date - cakephp-3.0

I have a cakephp code. in that i store a specific date from database into a var $endate. I store the value of $endate in another variable.
Ex:$date = $endate;
The below loop displays repeated months
for ($l = 0; $l < 10; $l++) {
$month[] = date("Y-M", strtotime($date . " -$l months"));
}
output:
[0] => 2017-Mar
[1] => 2017-Mar
[2] => 2017-Jan
[3] => 2016-Dec
[4] => 2016-Dec
[5] => 2016-Oct
[6] => 2016-Oct
[7] => 2016-Aug
[8] => 2016-Jul
[9] => 2016-Jul
How do i display the last 10 months based on my fetched date?

EDIT: Ah, didn't see that your sequence/output not was correct :-) Deleted part of answer.
I'd recommend using Cake's Date class but that doesn't seem to be directly relevant to your question.
Example using Cake's Time class:
$now = new \Cake\I18n\FrozenTime();
$monthsToGoBack = 10;
$months = [];
for ($i = 0; $i <= $monthsToGoBack; $i++) {
$months[] = $now->subMonths($i)->firstOfMonth()->hour(0)->minute(0)->second(0);
}
Output: https://gist.github.com/Spriz/a21e6771f71cef0ad659e356737996a0

Related

Check SQL schema for reserved words and find suitable replacement

Wasted many hours troubleshooting my DB which included maxValue as a column name. I've since discovered it was a reserved word.
I've used type and timestamp with both MySQL and MariaDB without issues, but I've learned my lesson, and will never do so again (MySQL shows both as being reserved, yet MariaDB only shows timestamp and even says its still okay to use).
Is there some sort of online tool which will check the schema using the SQL dump or create SQL for reserved words?
Is there any resource or strategy showing typical replacement words. I suppose I can make them plural but doing so goes against my personnel standard.
For what it is worth, here is a tool...
Note that mysql.help_keyword is not being supported with MariaDB 10.2.7, and I had to hardcode the reserved words.
<?php
error_reporting(E_ALL);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
openlog('API', LOG_NDELAY, LOG_LOCAL2);
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['database'])) {
$db=parse_ini_file(__DIR__.'/../config.ini',true)['mysql'];
$pdo=new PDO("mysql:host={$db['host']};dbname={$db['dbname']};charset={$db['charset']}",$db['username'],$db['password'],array(PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_OBJ));
$error=['tableHelper'=>[],'columnHelper'=>[],'tableMdbReserved'=>[],'columnMdbReserved'=>[],'tableMdbException'=>[],'columnMdbException'=>[]];
$stmt=$pdo->query('SELECT name FROM mysql.help_keyword');
$reserved=$stmt->fetchAll(PDO::FETCH_COLUMN);
$mdbReserved=['ACCESSIBLE','ADD','ALL','ALTER','ANALYZE','AND','AS','ASC','ASENSITIVE','BEFORE','BETWEEN','BIGINT','BINARY','BLOB','BOTH','BY','CALL','CASCADE','CASE','CHANGE','CHAR','CHARACTER','CHECK','COLLATE','COLUMN','CONDITION','CONSTRAINT','CONTINUE','CONVERT','CREATE','CROSS','CURRENT_DATE','CURRENT_TIME','CURRENT_TIMESTAMP','CURRENT_USER','CURSOR','DATABASE','DATABASES','DAY_HOUR','DAY_MICROSECOND','DAY_MINUTE','DAY_SECOND','DEC','DECIMAL','DECLARE','DEFAULT','DELAYED','DELETE','DESC','DESCRIBE','DETERMINISTIC','DISTINCT','DISTINCTROW','DIV','DOUBLE','DROP','DUAL','EACH','ELSE','ELSEIF','ENCLOSED','ESCAPED','EXISTS','EXIT','EXPLAIN','FALSE','FETCH','FLOAT','FLOAT4','FLOAT8','FOR','FORCE','FOREIGN','FROM','FULLTEXT','GENERAL','GRANT','GROUP','HAVING','HIGH_PRIORITY','HOUR_MICROSECOND','HOUR_MINUTE','HOUR_SECOND','IF','IGNORE','IGNORE_SERVER_IDS','IN','INDEX','INFILE','INNER','INOUT','INSENSITIVE','INSERT','INT','INT1','INT2','INT3','INT4','INT8','INTEGER','INTERVAL','INTO','IS','ITERATE','JOIN','KEY','KEYS','KILL','LEADING','LEAVE','LEFT','LIKE','LIMIT','LINEAR','LINES','LOAD','LOCALTIME','LOCALTIMESTAMP','LOCK','LONG','LONGBLOB','LONGTEXT','LOOP','LOW_PRIORITY','MASTER_HEARTBEAT_PERIOD','MASTER_SSL_VERIFY_SERVER_CERT','MATCH','MAXVALUE','MEDIUMBLOB','MEDIUMINT','MEDIUMTEXT','MIDDLEINT','MINUTE_MICROSECOND','MINUTE_SECOND','MOD','MODIFIES','NATURAL','NOT','NO_WRITE_TO_BINLOG','NULL','NUMERIC','ON','OPTIMIZE','OPTION','OPTIONALLY','OR','ORDER','OUT','OUTER','OUTFILE','PARTITION','PRECISION','PRIMARY','PROCEDURE','PURGE','RANGE','READ','READS','READ_WRITE','REAL','RECURSIVE','REFERENCES','REGEXP','RELEASE','RENAME','REPEAT','REPLACE','REQUIRE','RESIGNAL','RESTRICT','RETURN','REVOKE','RIGHT','RLIKE','ROWS','SCHEMA','SCHEMAS','SECOND_MICROSECOND','SELECT','SENSITIVE','SEPARATOR','SET','SHOW','SIGNAL','SLOW','SMALLINT','SPATIAL','SPECIFIC','SQL','SQLEXCEPTION','SQLSTATE','SQLWARNING','SQL_BIG_RESULT','SQL_CALC_FOUND_ROWS','SQL_SMALL_RESULT','SSL','STARTING','STRAIGHT_JOIN','TABLE','TERMINATED','THEN','TINYBLOB','TINYINT','TINYTEXT','TO','TRAILING','TRIGGER','TRUE','UNDO','UNION','UNIQUE','UNLOCK','UNSIGNED','UPDATE','USAGE','USE','USING','UTC_DATE','UTC_TIME','UTC_TIMESTAMP','VALUES','VARBINARY','VARCHAR','VARCHARACTER','VARYING','WHEN','WHERE','WHILE','WITH','WRITE','XOR','YEAR_MONTH','ZEROFILL'];
$mdbExceptions=['ACTION','BIT','DATE','ENUM','NO','TEXT','TIME','TIMESTAMP'];
$stmt=$pdo->prepare('SELECT UPPER(TABLE_NAME) tn, UPPER(COLUMN_NAME) cn from information_schema.columns WHERE table_schema = ?');
$stmt->execute([$_POST['database']]);
while($rs=$stmt->fetch()) {
if(in_array($rs->tn,$reserved)) {
$error['tableHelper'][]=$rs->tn;
}
if(in_array($rs->cn,$reserved) && !in_array($rs->cn,$error['columnHelper'])) {
$error['columnHelper'][]=$rs->cn;
}
if(in_array($rs->tn,$mdbReserved)) {
$error['tableMdbReserved'][]=$rs->tn;
}
if(in_array($rs->cn,$mdbReserved) && !in_array($rs->cn,$error['columnMdbReserved'])) {
$error['columnMdbReserved'][]=$rs->cn;
}
if(in_array($rs->tn,$mdbExceptions)) {
$error['tableMdbException'][]=$rs->tn;
}
if(in_array($rs->cn,$mdbExceptions) && !in_array($rs->cn,$error['columnMdbException'])) {
$error['columnMdbException'][]=$rs->cn;
}
}
echo('<pre>'.print_r($error,1).'</pre>');
}
else {
echo <<<EOT
<form method="post">
Database Name: <input type="text" name="database"><br>
<input type="submit">
</form>
EOT;
}
Output:
Array
(
[tableHelper] => Array
(
)
[columnHelper] => Array
(
[0] => TYPE
[1] => NAME
[2] => TIMESTAMP
[3] => OFFSET
[4] => VALUE
[5] => STATUS
[6] => PORT
)
[tableMdbReserved] => Array
(
)
[columnMdbReserved] => Array
(
[0] => MAXVALUE
)
[tableMdbException] => Array
(
)
[columnMdbException] => Array
(
[0] => TIMESTAMP
)
)

foreach on json data

Hi i want to insert values into table which is posted from api
json data is
{"questions":{"34":"Yes", "46":"good", "48":"NA", "29":"Yes", "45":"ravi", "49":"Negative", "43":"1 BHK", "35":"Neighbour", "38":"14", "39":"9", "27":"1",
"41":"Married", "52":"vijay#123.com", "47":"good", "31":"Bunglow", "33":"Middle Class", "37":"Owned By Parents", "30":"good", "50":"easy",
"51":"comments", "32":"No", "44":"[MusicSystem,PC,Refrigerator,Airconditioner]"}}
when i convert into array it is
Array
(
[questions] => Array
(
[34] => Yes
[46] => good
[48] => NA
[29] => Yes
[45] => ravi
[49] => Negative
[43] => 1 BHK
[35] => Neighbour
[38] => 14
[39] => 9
[27] => 1
[41] => Married
[52] => ravi#gmail.com
[47] => good
[31] => Bunglow
[33] => Middle Class
[37] => Owned By Parents
[30] => good
[50] => easy
[51] => comments
[32] => No
[44] => [MusicSystem,PC,Refrigerator,Airconditioner]
)
)
how to get this values like
using foreach
$question=34;
$answer= yes;
Try like this.Convert json into array using json_decode().And make a new array with key and value.Then just print the first key and value.
<?php
$json = '{"questions":{"34":"Yes", "46":"good", "48":"NA", "29":"Yes", "45":"ravi", "49":"Negative", "43":"1 BHK", "35":"Neighbour", "38":"14", "39":"9", "27":"1",
"41":"Married", "52":"vijay#123.com", "47":"good", "31":"Bunglow", "33":"Middle Class", "37":"Owned By Parents", "30":"good", "50":"easy",
"51":"comments", "32":"No", "44":"[MusicSystem,PC,Refrigerator,Airconditioner]"}}
';
$array = json_decode($json,TRUE);
//print_r($array);
foreach($array['questions'] as $key=>$value)
{
$arr[] = array('key'=>$key,'value'=>$value);
}
//print_r($arr);
echo "Question:".$arr[0]['key'].PHP_EOL;
echo "Answer:".$arr[0]['value'];
Output:
Question:34
Answer:Yes
To access a single value while having the key, you can do $array["questions"][34] to get the answer yes.
If you want to loop through all of them, you can do this loop:
foreach($array["questions"] as $no => $ans){
echo "Question: $no";
echo "Answer: $ans";
}

Appending one array to another array in the same loop

This is for a custom Wordpress page but I think the basic array principles should apply. I've not worked with complex arrays before so am a little lost, trial and error hasn't worked yet.
I have a database of Posts, each post has meta_key's of 'shop' and 'expired'.
'expired' is a date (YYYY-MM-DD) which is used to tell the visitor when a Post's content expires and this key is what I'm trying to work with.
If a Post's 'expired' date is before today, they are shown 'Offer expired'
If the 'expired' date is in the future, they are shown 'Offer expires in X days' (this script isn't shown below, not necessary)
Posts are listed in order of their 'expired' date, ASC. The problem is that when a post expires I'd like that post to show at the end rather than stay on top.
Example of what I currently see:
Post 1 | Expired 3 days ago
Post 2 | Expired 1 day ago
Post 3 | Expires in 2 days
Post 4 | Expires in 6 days
And what I'd like to see (note Post X order):
Post 3 | Expires in 2 days
Post 4 | Expires in 6 days
Post 2 | Expired 1 day ago
Post 1 | Expired 3 days ago
This is my array code where I've attempted to merge the two
$postid = get_the_ID();
$meta1 = get_post_meta($postid, 'shop', true);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$today = date('Y-m-d', time());
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'shop',
'value' => $meta1
)
),
'paged' => $paged,
'posts_per_page' => '5',
'meta_key' => 'expired',
'meta_value' => $today,
'meta_compare' => '>',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$args2 = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'shop',
'value' => $meta1
)
),
'meta_key' => 'expired',
'meta_value' => $today,
'meta_compare' => '<',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$final = $args + $args2;
$query = new WP_Query( $final );
while ( $query->have_posts() ) : $query->the_post(); ?>
HTML FOR DISPLAYING POST
endwhile;
At the moment it doesn't seem to take any notice of "$args2" and only displays $args
I'm sure my idea is on the right lines, needing to create two arrays and join them with the "+" rather than array_merge() but that's where I can't get any further.
Can someone kindly shed some light please? Thanks!
Now the solution you are trying to achieve is actually impossible if i understood your requirement properly. Let me explain why this is not achievable.
In your two arrays $args and $args2 most of the values are same leaving two odds , i am picking only one to just illustrate :
//it's in args
'meta_compare' => '>'
//it's in args2
'meta_compare' => '<'
Now what happens when you are trying to merge this two using array_merge($args , $args2):
'meta_compare' => '<'
That means it is taking 'meta_compare' from the later array which is $args2 here. This is the behavior of array_merge function defined in the doc:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one
Now if you are using + array union operator $args+$args2 :
'meta_compare' => '>'
That means it is taking 'meta_compare' from the first array which is $args here. This is the behavior of + array union operator defined in the doc :
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
Why it is happening because in the same level keys have to be unique . So in your situation they are in the same level :
$args = array ('key' => 'value1')
$args2= array ('key' => 'value2')
So only and only one value can exist here as in the merged array 'key' can point only one.
If this was the scenario :
$args [0] = array ('key' => 'value1' )
$args2 [1]= array ('key' => 'value2' )
Then both of the value stored by key will be resrved. This will be the resulting array :
array(2) {
[0]=>
array(1) {
["key"]=>
string(6) "value1"
}
[1]=>
array(1) {
["key"]=>
string(6) "value2"
}
}
Though i am not a geek of WP but as far as i understood from WP_query you can't pass args like this (I am not sure). So that leaves only one way to achieve this. You can pass these two args separately and merge the result as the result most probably (I am not sure) will be a 2D array you can merge them easily.
Hope that helps.
Happy coding :)
You can't just add 2 arrays together using the args+args2 syntax. PHP has no way of knowing what you mean by that. If you want the result to be an array containing both of these arrays, you could do this:
$final = array($args, $args2)
Otherwise I'm not sure how you want these two arrays combined. If you clarify how they need to be combined we might be able to help more.

return only column name values from mysql table

sorry but i didn't knew how to explain the question in on sentence...
actually i have code like this when i do mysql_fetch_array...
[0] => 10
[id] => 10
[1] => 58393
[iid] => 58393
[2] => 0
[ilocationid] => 0
[3] => 38389
[iapptid] => 38389
[4] => 2012-06-30T00:00:00
[ddate] => 2012-06-30T00:00:00
[5] => 1000
[ctimeofday] => 1000
but i want to return something like this
[id] => 10
[iid] => 58393
[ilocationid] => 0
[iapptid] => 38389
[ddate] => 2012-06-30T00:00:00
[ctimeofday] => 1000
i mean without the numeric representatives of the columns. how do i do it...please help...
As explained in the manual for PHP's mysql_fetch_array() function:
The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
Therefore, you want either:
mysql_fetch_array($result, MYSQL_ASSOC);
or
mysql_fetch_assoc($result);
Note however the warning:
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_fetch_array()
PDOStatement::fetch()

PHP don't generate properly array from database (UBUNTU)

I have a little problem.
There are two tables in my database: users and classes. The first one contains info about users, and the second one - about user classes and about access rights.
Now I'm extracting all data from there using this:
SELECT * FROM users NATURAL JOIN classes WHERE users.ID_User = '$id';
The mysql code works and returns a right array.
Now, when I'm doing next:
<?php
$result = mysql_query($sql_above);
$row = mysql_fetch_array($result);
print_r($row);
?>
... i'm getting this:
Array ( [0] => 1 [ID_User] => 1 [1] => John [Name] => John [2] => Doe [Surname] => Doe [3] => ... [16] => Owner [Class] => Owner [17] => [All] => [18] => [CanAuth] => [19] => [CanViewData] => [20] => [CanAddData] => [21] => [CanAlterData] => [22] => [CanDeactivateData] => [23] => [CanDeleteData] => [24] => [CanMgLocatari] => ... )
Columns from 17 till the end are access rights, noted in the database by 1 or 0. And there, they're missing.
Is there any option to enable in PHP configuration to correct this thing? Because on a Windows machine, the code executes properly and rights are working.
PHP Version 5.3.6-13ubuntu3.7 | Apache/2.2.20 (Ubuntu) | MySQL client version: 5.1.62
Please, reply. Thanks!