printing array containing date php - php

Not as simple as it sounds I believe, but I have the following and trying to print the month name from date provided.
public function convertEngDateToAr($engDate)
{
//SELECT MONTHNAME('2009-05-18');
$connectionInstance = new ConnectionClass();
$connection = $connectionInstance->connectToDatabase();
$monthResult = $connection->query("SELECT MONTHNAME('$engDate')");
//echo "Month: " . $monthResult;
while($row = $monthResult->fetch_assoc())
{
print_r($row);
}
}
The above gets me this output:
Array ( [MONTHNAME('2012-08-21')] => August )
How can I get August alone out of the array and store it in variable? The only weird thing here is that the index in the array is just strange.
Thank

Try changing SELECT MONTHNAME('$engDate')" to SELECT MONTHNAME('$engDate') as monthName"
Then you should see:
Array ( monthName => August )
Then you can use:
while($row = $monthResult->fetch_assoc())
{
$myMonth=$row['monthName'];
}

You can either use SELECT MONTHNAME(xxxx) AS monthName or you could return an indexed array instead of an associative one:
while($row = $monthResult->fetch_row())
echo $row[0] . "\n";

Related

Why is my value not recognized to be in the array?

I'm trying to check if a date string is in an array of dates from a WordPress database.
Currently, there is only one value in the array: 2019-01-02
If I print the array I get this:
Array ( [0] => stdClass Object ( [date] => 2019-01-02 ) )
Why is the value not recognized to be in the array?
<?php
$sql = "SELECT date FROM wp_table";
$result = $wpdb->get_results($sql);
if (in_array('2019-01-02', $result)) {
echo "Yes, the date is in the array!";
}
print_r($result);
?>
The there is no result from the above.
Any help is very much appreciated.
Kresten
This happens because your data structure is an array of objects, and each one of those contains a field called date. To check if a specific date is in that specific array, you should do:
<?php
$sql = "SELECT date FROM wp_table";
$result = $wpdb->get_results($sql);
foreach ($result as $res)
if ($res->date == '2019-01-02') {
echo "Yes, the date is in the array!";
break;
}
print_r($result);
?>
It's not working because in_array is not suited to an associative (key, value) array.
If you had the following array:
array("2019-01-01", "banana", "dog)
...it would work. But it won't work with the keys.
If you are only ever looking for one specific 'key', in this case date, you can amend your scope to be only that 'column':
$dates = array_column( $result, 'date' );
in your code:
<?php
$sql = "SELECT date FROM wp_table";
$result = $wpdb->get_results($sql);
$dates = array_column( $result, 'date' );
if (in_array('2019-01-02', $dates)) {
echo "Yes, the date is in the array!";
}
print_r($result);
?>

What is the convenient way of fetching array from DB to extract it then to vars in PHP?

I'm newbie learning PHP.
I have a MySQL table looking like this:
Working on fetching data from it using PDO.
My task?
I need to make arithmetic calculations between elements of this array. I.e.:
$sel_1_1 + $day, where $sel_1_1 is the first element of column select1
$sel_1_2 + $day, where $sel_1_2 is the second element of column select1
$sel_2_1 + $day, where $sel_1_2 is the first element of column select2
$sel_2_2 + $day, where $sel_1_2 is the second element of column select2
How I try to solve it
I need to fetch data from 4 columns (day, select1, select2, select3) in the form of array and to extract elements of these arrays into separate variables.
This is how I do:
$loged = 'test';
$stmt = $pdo->prepare("SELECT select1, select2, select3, day
FROM day_table
WHERE login=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $key=>$row) {
$sel1 = $row['select1'];
$sel2 = $row['select2'];
$sel3 = $row['select3'];
$day_from_db = $row['day'];
}
echo $sel1; // This fetches only the last element of "Select1" array.
echo $day_from_db; // Also fetches only the last element of "Day" array
echo "<pre>".print_r($res, true)."</pre>";
Output looks like this:
Array (
[0] => Array (
[select1] => 2
[select2] => 2
[select3] => 2
[birthday] => 2018-06-24 )
[1] => Array (
[select1] => 16
[select2] => 10
[select3] => 7
[birthday] => 2018-07-27 )
[2] => Array (
[select1] => 2
[select2] => 2
[select3] => 2
[birthday] => 2018-07-29 )
)
Then I try to extract my big array usung PHP extract:
$e = extract($res);
echo $e;
Returns 0.
And if I try doing in another manner like this:
// Fetch column day:
$sql = "SELECT day FROM day_table WHERE login=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$loged]);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$day0 = $result[0];
$day1 = $result[1];
$day2 = $result[2];
echo $day0."<br>";
echo $day1."<br>";
echo $day2."<br>";
// Fetch column select1:
$sql = "SELECT select1 FROM day_table WHERE login=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$loged]);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$select0 = $result[0];
$select1 = $result[1];
$select2 = $result[2];
echo $select0."<br>";
echo $select1."<br>";
echo $select2."<br>";
Returns desired values, but this is not good approach because:
If there are lots of elements in columns this becomes senselessly,
This is bad, non optimal code.
Can you please help me solving my issue with good, appropriate method?

Echo array from sql in php program

I would like to get all the post IDs from yesterday on wordpress, the SQL query works well when I tried it on phpMyAdmin, it returns all IDs from yesterday. However when I tried to echo the IDs out of the array, the values in the array is 'Array' instead of the ID, which should be numbers. I wonder why did the IDs in the array all turned into the word 'Array'. This is the code I wrote:
$yesterday = strtotime("-1 days");
$day = (int)date("d", $yesterday);
$month = (int)date("n", $yesterday);
$year = (int)date("Y", $yesterday);
$sql = "
SELECT ID
FROM wp_posts
WHERE 1 = 1
AND DAY(post_date) = $day
AND MONTH(post_date) = $month
AND YEAR(post_date) = $year
";
global $wpdb;
$results = $wpdb->get_results($sql, 'ARRAY_N');
foreach ($results as $id) {
echo '<br>' . $id;
}
Update:
I changed the type of output to ARRAY_A and added the var_dump() before the foreach loop to see what's inside the array, and this is what I got:
use ARRAY_A to get associative array instead of ARRAY_N which returns numerically indexed multidimensional array .. $results in your code is multidimensional array ..
use var_dump() instead on echo to view variable contents ( for testing )
According to this answer you should do the following code in the foreach loop
foreach ($results as $result) {
echo '<br>' . $result->id;
}
Try to print the $results and get the appropriate object.

PHP - Array in implode

I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.

PHP Concatenate Zero to date POST value

I need to add a zero to the date value that is posted as the MySQL date value will be used as a directory path to show added photos. Currently the directory is saved as 2012-2-5 and the MySQL entry is 2012-02-05.
I have tried the following, however it doesn't seem to be working:
$dates = array($_POST['photos_year'], $_POST['photos_month'], $_POST['photos_day']);
foreach($dates as $date) {
if (strlen($date) == 1) {
$date = '0' . $date;
}
}
$photos->date = $dates[0] . "-" . $dates[1] . "-" . $dates[2];
I am using a for loop to create the date form, it might be easier for me to edit this however I haven't had any success:
<select name="photos_month" id="photos_month" tabindex="3">
<option value ="">- Month -</option>
<?php
for($date=01;$date<=12;$date++) {
if (isset($photos) && $date==$month) {
echo "<option value='".$date."' selected='selected'>".$date."</option>";
} else {
echo "<option value='".$date."'>".$date."</option>";
}
}
?>
</select>
You need to update the foreach to be
foreach ($dates as &$date)
Currently, $date is a new symbol and will not overwrite the value. That should fix it, but it may be nice to have the correct strings in the options too. You can use str_pad to do that.
When doing a foreach, the element variable $date is a new variable, a copy of the value from the array. You should use a key and update the original array.
foreach($dates as $key => $date) {
if (strlen($date) == 1) {
$dates[$key] = '0' . $date;
}
}
Also, you're running that code on the year, you don't want to be adding a zero to the year, only the month and day.
You could make it a little simpler by just using sprintf with a format string;
$photos_year = '2012';
$photos_month = '2';
$photos_day = '5';
$result = sprintf("%4d-%02d-%02d", $photos_year, $photos_month, $photos_day);
// $result = '2012-02-05'
Check out the string pad function http://php.net/manual/en/function.str-pad.php
Along with the array map function http://php.net/manual/en/function.array-map.php
Using these two together would allow for you to go through each part of the date(array_map) and pad the value with a 0 (using str_pad)
Code would look something like this
$dates = array_map("padString",$dates);
function padString($string) {
return str_pad($string,2,"0",STR_PAD_LEFT);
}
print_r($dates);
//Gives you Array ( [0] => 2012 [1] => 02 [2] => 05 )
use sprintf()
For example:
$date = sprintf('%02d', $_POST['photos_day']);

Categories