convert a data varchar to date month - mysql

I have a table with a date column in it, but its data type using a varchar.
Month
| 01 02 03
I want to convert that data into a form of month name,I have tried this way, the data is successfully converted into months but always month of january.
foreach($list as $post) {
$time = strtotime($post->album_periode_bulan);
$newformat = date('F',$time);
$no++;
$row = array();
$row[] = $no;
$row[] = $time;
$data[] = $row;
}
I have implemented this in datatables

In MySQL you do
UPDATE your_table
SET your_column = DATE_FORMAT(STR_TO_DATE(your_column, '%m'), '%M');
and that's it. Read more about the format parameters for both functions here.
Note though, newer releases set the sql mode NO_ZERO_IN_DATE by default. You might need to disable this temporarily with
set session sql_mode = "";
Check this before!!! with
show session variables like 'sql_mode';
or you might end with all your rows being NULL.

Related

Update DateTime manually

Since I'm hassling to much with the timestamp I would like to use dateTime. But since dateTime doesn't offer the auto update, I need to do it manually. But my NOW() doesn't do anything to my row.
function user_activity($active){
$query = $this->link->prepare("UPDATE memory SET
page = ? AND activity2 = NOW() WHERE user_id='{$_SESSION['id']}' ");
$values = array($active);
$query->execute($values);
$counts = $query->rowCount();
return $counts;
}
Don't use AND in your SET statement, instead use a comma. It also looks like you have too many ) in your query.
function user_activity($active) {
$query = $this->link->prepare("UPDATE memory SET page = ?, activity2 = NOW() WHERE user_id='{$_SESSION['id']}' ");
$values = array($active);
$query->execute($values);
$counts = $query->rowCount();
return $counts;
}
As Phil mentions, you have a query error here. Always use exception handling when executing SQL queries.
Learn Exception Handling

MySQL - select missing dates from table?

Suppose you have the following table values:
date | value
2012-01-01 | 8
2012-01-02 | 3
2012-01-03 | 17
2012-01-09 | 100
2012-01-12 | 2
Now suppose you want to select all the dates between 2012-01-02 and 2012-01-12 and show their values if present. If you simply query the table for the appropriate date range, the dates that don't have values are going to be absent, for obvious reasons. Is there a way to fill in those dates in the query?
The obvious solution is to create a table dates that just stores a list of all dates that may come up, and then to select from the dates table and join values to it, but I'd like to have a solution that doesn't rely on creating a single-column table if I can.
Of note: there are existing questions on SO on this topic, but they are all from 2010 (at least the ones I found when searching were), and MySQL features have grown in that time; there may be a dynamic solution now. If that's not the case, and the dates table is still the best solution, then this question should be closed as a duplicate.
The lack of answers from others suggests to me that at the current time, it is not possible to traverse a range of dates in MySQL without a table that holds those dates. I have, however, written some code in PHP that I'm using to fill in the missing dates after the fact:
function formatResults($inbound, $from, $to) {
$results = array();
$count = 0;
// In order not to lose any results, we have to change how the results are referenced
$indexes = array();
$stats = array();
foreach ($inbound as $stat) {
// ['listindex'] is the date, renamed in the query
$stats[$stat['listindex']] = $stat;
}
// In a function in case you want to pop it out
function dateArray($from, $to) {
$begin = new DateTime($from);
$end = new DateTime($to);
$interval = DateInterval::createFromDateString('1 day');
$days = new DatePeriod($begin, $interval, $end);
$baseArray = array();
foreach ($days as $day) {
$dateKey = $day->format("Y-m-d");
$baseArray[] = $dateKey;
}
$baseArray[] = $to;
return $baseArray;
}
$indexes = dateArray($from, $to);
// Now all the rows we need to return are uniquely identified in $indexes
// So we traverse $indexes to create our results array, rather than relying on $inbound
foreach($indexes as $index) if ($index != '') {
$data = array();
// Make sure we do not run into any 'missing index' problems
if (!isset($stats[$index]))
$stats[$index] = array(
'listindex' => $index,
// ... populate full list of empty fields
);
foreach ($stats[$index] as $key => $value) {
$data[] = $value;
}
$results[$count] = $data;
$count++;
}
return $results;
}

Make Zend\Db (zf2) between clause inclusive

I'm currently using Zend Framework 2 and a query with date ranges to obtain data out of a MySQL DB, and I came across the between clause that was previously not available in ZF1.
However, my code which looks something like this is not working correctly:
$dateStart = '2012-12-20';
$dateEnd = '2012-12-31';
$sql = new Sql($_db);
$select = $sql->select()
->from(array("t" => $table))
->columns(array("col1" => "col_as_1", "col2" => "col_as_2"));
$select->where->between("date", $dateStart, $dateEnd);
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute()->getResource()->fetchAll(\PDO::FETCH_ASSOC);
Apparently the between clause is not inclusive, I can only get results until 2012-12-30, is there a way to make it inclusive? I've been taking a look at the ZF2 docs but they are not very helpful and running the same query on MySQL query browser returns all of the data I need.
So you can try lessThanOrEqualTo and greaterThanOrEqualTo.
Between doesn't seem to provide this functionality: between($identifier, $minValue, $maxValue)
If you trace out your query with $select->__toString() you can see the query as string.
I don't have ZF2 on my computer but I could imagine that between in ZF2 will output date > '2012-12-20' AND date < '2012-12-31'.
NOTE THIS : WHEN USING between on Mysql
date_column_name between 'startDate' AND 'endDate'
NOTE : you should want to insert +1 date to endDate . Because of when you insert 2015-05-18 date to endDate.you can not get data of 2015-05-18.So you need to plus one date to endDate.
You can do it using this
$plusToDate = date('Y-m-d H:i:s', strtotime($toDate . ' + 1 day'));
The BETWEEN should be inclusive, are you sure there are no hours, minutes and seconds after the date, that would cause it not to select dates on 2012-12-31 since 2012-12-31 00:00:01 would technically be > 2012-12-31
Format must be same, use mysql DATE function
$select->where->between("DATE(date)", DATE('.$dateStart.'), DATE('.$dateEnd.'));
$from_date = date('Y-m-d', strtotime($AppCleaner->from_date ));
$to_date = date('Y-m-d', strtotime($AppCleaner->to_date ));
$select->where->between('appointment_date', $from_date . ' 00:00:00', $to_date . ' 23:59:59');
also, Use the between clause as below:
$sql = new Sql($this->adapter);
$select = $sql->select();
$select->from('app_posts');
$select->where->NEST->between( 'id', 30,40);
$select->group('app_posts.id');
// echo $select->getSqlString($this->adapter->getPlatform());
// exit;
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
$posts = $resultSet->buffer()->toArray();
return $resultSet;
Try this:
//I have a static function to make conversion Data Format
public static function convertBrazilianDate2MySQLDatabase($dataBrazil) {
$array = explode("/", $dataBrazil);
$array = array_reverse($array);
$str = implode($array, "/");
return date("Y-m-d", strtotime($str));
}
//In My Service I built my sentence
$dtStart = \Estrutura\Helpers\Data::convertBrazilianDate2MySQLDatabase($dt_start) . ' 00:00:01';
$dtEnd = \Estrutura\Helpers\Data::convertBrazilianDate2MySQLDatabase($dt_end) . ' 23:59:59';
$select->where->between('field name in table', $dtStart, $dtEnd);
[...]

xml unix timestamp to mysql timestamp and record mysql

My XML:
<simpletype type="TURKEY">
<city code="01">
<telcode>(0 322)</telcode>
<name>Adana</name>
<time>1345337940</time>
</city>
<city code="02">
<telcode>(0 416)</telcode>
<name>Adıyaman</name>
<time>1340236800</time>
</city>
</simpletype>
MY Mysql import Code:
require_once('db.php');
#mysql_connect(_SERVER,_USER,_PASSWORD);
#mysql_select_db(_DATABASE);
$doc = new DOMDocument();
$doc->load( 'CityCode.xml' );
$cities = $doc->getElementsByTagName( "city" );
foreach( $cities as $city )
{
$names = $city->getElementsByTagName( "name" );
$codes = $city->getElementsByTagName( "telcode" );
$times = $city->getElementsByTagName ( "time");
$name = $names->item(0)->nodeValue;
$code = $codes->item(0)->nodeValue;
$time = $times->item(0)->nodeValue;
mysql_query("SET CHARACTER SET utf8");
$sql = "INSERT INTO telcode (sehir, name, time) VALUES ('$name' ,'$code' ,'UNIX_TIMESTAMP ($time') ";
#mysql_query($sql);
}
My Question:
My xml source have a unix timestamp and i must use is mysql timeststamp (0000-00-00 00:00:00)
How can i convert $time unix timestamp to mysql timestamp and record mysql db ?
In MySQL you can convert a UNIX-style timestamp (seconds since 1970 UTC) to a MySQL timestamp with the FROM_UNIXTIME function.
See here. http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_from-unixtime
In php, you can read a timestamp out into whatever format you like.
date($format, $timestamp);
http://php.net/manual/en/function.date.php

Trouble Inserting An Array of Information into a MySQL Database

I am having an issue with inserting an array of information into a mysql database. Basically I built a sortable gallery similar to Facebook's photo albums that can be arranged by moving the div to a new spot with jquery's sortable function.
I am using Ajax to call a php file which will inser the new order of the div's into the DB. The information is being passed correctly, it is just not being inserted correctly.
The error I am receiving is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Array' at line 1
The Php code is:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
If I remove the mysql_query function and just do a print_r, I get:
Array
(
[0] => UPDATE table SET order = '0' WHERE id = '2'
[1] => UPDATE table SET order = '1' WHERE id = '4'
[2] => UPDATE table SET order = '2' WHERE id = '3'
[3] => UPDATE table SET order = '3' WHERE id = '1'
[4] => UPDATE table SET order = '4' WHERE id = '5'
[5] => UPDATE table SET order = '5' WHERE id = '6'
)
This is the first time I have tried to do something like this. Any help would be great.
Thank you in advance for the help!
In mysql_query($sql) $sql is an array, therefore it's value is simply Array. When you assign $sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'"; simply make this line $sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";. That should solve your problem.
EDIT:
You can leave the [] and simply remove the mysql_query from where it is. After your foreach list item, add this:
foreach($sql as $query) {
mysql_query($query);
}
Sounds like there is some confusion about what the [] operator does. You use [] when you want to append an element to the end of an existing array.
For example:
$sql = array();
$sql[] = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will produce the error you are seeing
Versus:
$sql = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will work
You should rewrite your code as such:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
That will do what you are intending. However, this is still not a good idea, since you are passing untrusted $_GET data directly to the database. I could, for example, call your script with a string like:
http://yoursite.com/yourscript.php?listItem=1'%3B%20DROP%20TABLE%20yourtable%3B
Since the value of listItem is going directly to the database -- and the $item >= 1 check is insufficient, since PHP will evaluate a string as an integer if it begins with numeric data -- all I have to do is add a single quote to terminate the previous query, and I am then free to inject whatever SQL command I'd like; this is a basic SQL injection attack. Whenever you write database-touching code, you should cleanse any input that might be going to the database. A final version of your code might look like:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) { // this check may or may not be needed depending on its purpose
$sql = 'UPDATE table SET order = "' . mysql_real_escape_string($position) . '" WHERE id = "' . mysql_real_escape_string($item) . '"';
mysql_query($sql) or die(mysql_error());
}
}
There are other ways to cleanse input data as well, that is just one of them. Hope that helps.