Trouble saving date and time to MySQL using PHP - php

I'm writing a website and I'm having a problem with saving date and time to MySQL database using PHP but all I got for the date is 0000-00-00 00:00:00. I'm not sure what's the problem with my code so I hope you guys can help me point it out.
Below is the INSERT function I store in an external php file for convenience
<?php
class FITQuery {
public static function insert($table, $fields, $values, $condition = null) {
$query = "INSERT INTO ".$table;
$query .= '(';
for ($i = 0; $i < count($fields) - 1; $i++) {
$query .= $fields[$i].',';
}
$query .= $fields[count($fields) - 1];
$query .= ') VALUES (';
for ($i = 0; $i < count($values) - 1; $i++) {
$query .= "'".$values[$i]."',";
}
$query .= "'".$values[count($values) - 1]."'";
$query .= ') ';
if (mysql_query($query)) return true;
else die("INSERT:".mysql_error());
}
} ?>
And here is the code where I use the INSERT:
<?php
if (!empty($_POST)) {
// POST PROCESS
$title = $_POST['title'];
$short_desc = $_POST['short_desc'];
$content = $_POST['content'];
// FILE UPLOAD
if (isset($_FILES['avatar'])) {
$avatar = FITUtils::uploadFile($_FILES['avatar']['name'], $_FILES['avatar']['tmp_name'], "../uploads");
}
else $avatar = null;
// Insert
FITQuery::insert('news', array('title','short_desc','content','avatar','created_date'),
array($title, $short_desc, $content, $avatar, FITUtils::getDate()));
FITUtils::redirect('index.php?page=news');
}
else {
}
?>
I'm pretty sure it's not the INSERT function's problem because I already tried the "traditional" way but still got the same result. Anyone has some suggestions for me? I'm a newbie in PHP so I hope that you guys can help me with this. Thanks!

Try changing FITUtils::getDate() to
date('Y-m-d H:i:s', strtotime(FITUtils::getDate()))
The date format expected by MySQL is like 2011-12-17 04:20:00 which corresponds to the "format" parameter Y-m-d H:i:s passed to the date function in the suggestion above.
I don't know the date format returned by FITUtils::getDate(). If it is a string, then strftime will transform it into a timestamp, so we can use it as the second parameter for the date function. If it already returns a timestamp, then you may try the following code instead:
date('Y-m-d H:i:s', FITUtils::getDate())

Use variable to store date and time, your database field must have field type Date.
and do it like this:
$date_time= SYSDATE;
Then use this variable to insert into database using query.
Hope it works good as I've used this one...

Related

PHP Array to string to mysql - empty record

I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.

UPDATE Query not working - PHP/MySQL/bind_param

It's a simple update code in a PHP function through a GET call from the front-end(Not sure if this matters), the code is converting a particular time zone value to unix time stamps -
$oldDate = null;
$newDate = null;
$ctr = 0;
$timeStamp = array();
$query= $this->userDatabaseConnection->stmt_init();
$query->prepare("SELECT Timestamp from Transaction INNER JOIN `Order` ON `Order`.TransactionId = Transaction.TransactionId");
$query->execute();
$query->bind_result($tID); //this holds the current time zone values
while($query->fetch()){
$oldDate = $tID;
array_push($timeStamp, $oldDate);
}
$query->close();
foreach($timeStamp as $row){
$newDate = strtotime($row);
$queryUpdate= $this->userDatabaseConnection->stmt_init();
$queryUpdate->prepare("UPDATE `Order` SET OrderDate=? WHERE TransactionId=?");
error_log("ERROR!",0);
$queryUpdate->bind_param('is', $unixTS, $oldTS);
$unixTS = $newDate;
$oldTS = $row;
$queryUpdate->execute();
$queryUpdate->close();
$ctr++;
}
if($ctr == 88){
return true;
}
else{
return false;
}
}
The $ctr variable is returning the total number of rows that need to be updated - which equals to the correct value and thus returns a true to my front end Angular controller.
I tried echo-ing the $newDate and $row values - they seem to be correct too.
But it just does not update my table. Can someone please help me figure out why? Am I missing something here? The error log does show the message in my Apache log - but I can't seem to figure out what's causing it.

MySQL - Getting Two Different Results (PHP and phpMyAdmin)

I'm trying to run a SQL query, and it is working correctly in phpMyAdmin, but whe running it in PHP, the query comes back very wonky. The following query yields two different results:
SELECT `stock_ticker`, `stock_simpleName`, `stock_logo`
FROM `stocks`
WHERE stock_simpleName REGEXP'^c'
I get the following results in phpMyAdmin (Which is correct):
stock_simpleName
----------------------
Coca-Cola
Campbell's
ConAgra Foods
However, in PHP it comes out really weird:
stock_simpleName
-----------------------
Coca-Cola
MasterCard
Campbell's
Microsoft
The Walt Disney Company
PepsiCo
The Hershey Company
Proctor & Gamble
ConAgra Foods
...etc...
Why is this happening? This doesn't make any sense. Is it due to a server setting in PHP or some form of encoding or whatnot?
EDIT:
Here is my PHP Code:
The sub-model class (the creator of the pieces):
public function allOtherSearchResults($query, $dontQuery = null) {
$name = "stocks";
$where = "stock_simpleName REGEXP'^" . $query . "'";
$cols = array("stock_ticker", "stock_simpleName", "stock_logo");
$limit = 5;
return $this->select($name, $cols, $where, $limit);
}
The main-model class (this runs the query):
public function select($tableName, $columns, $where = null, $limit = null) {
global $purifier;
// Make columns SQL friendly
$cols = "`";
$cols .= implode("`, `", $columns);
$cols .= "`";
$table = "`" . $tableName . "`";
if (!empty($where)) {
$where = " WHERE " . $where;
}
// Check limit
if (!empty($limit)) {
$limit = " LIMIT $limit";
}
// SQL CODE
$sql = "SELECT " . $cols . " FROM " . $table . $where . $limit;
// SQL DEBUGGING IF CODE RETURNS BOOLEAN ERROR
echo $sql . "<br>";
$query = $this->conn->query($sql);
// Store the value in a variable called table with an array of that table's name followed by it's values
// EX: $model->table["bands"]["band_name"]
//
// Accessible by the individual page/directory's controller's
while($row = $query->fetch_assoc()){
// Store values as $model->table["tableName"]["columnName"]["index (usually 0)"]
foreach ($row as $key => $val) {
$this->data[$tableName][$key][] = $row[$key];
}
}
// Loop through results to clean them
// Foreach loops through each column
// Make sure the table isn't empty (i.e. login returns an error)
if (!empty($this->data[$tableName])) {
foreach ($this->data[$tableName] as $key => $tableArray) {
// For loop goes through each value in a certain row
for ($i = 0; $i < count($tableArray); $i++) {
// Convert from data variable to table after HTML PURIFIER
$this->table[$tableName][$key][$i] = $purifier->purify($tableArray[$i]);
}
}
}
// Declare the array after loop has finished for use in view
$this->table;
if (!empty($this->table)) {
return true;
}
}
And it gives me the same SQL output as above. I am not sure if there is a different interpretation of certain characters in PHP versus the standard MySQL in phpMyAdmin. Has anyone even had this problem before?
I'm guessing, that there is a problem wiht ^ character.
Try to set proper connection & result encoding, eq.
$this->conn->query("MYSQL SET NAMES utf8");
$this->conn->query("MYSQL SET CHARACTER SET utf8");
Also, check if your php script file is saved in UTF-8 encoding.
Moreover, you should consider of using prepared statement (even to prevent SQL Injection):
$this->conn->prepare("SELECT * FROM `stocks` WHERE `stock_simpleName` REGEXP ?");
$this->conn->bind_param("s", "^c");
$this->conn->execute();
$query = $this->conn->get_result();

PHP variable used in SQL

My code checks if there is $GET value, if not then assign ALL values of array.
Seems like simple thing,not sure why its not working.
if(isset($_GET["smonth"])) {$smonth= $_GET["smonth"];
}
else {$smonth =12;} working , but not what I want
else {$smonth =array (1,2,3,4,5,6,7,8,9,10,11) ;}
After that I would like to use it in SQL :
and d.month_of_year = '".$smonth."%'
That would be something like
and month_of_year = (all values of array) or 1 value)
My Question:
What would be best solution to check, if active month is available? If not, assign All months to query.Thank You
The built-in PHP functions of in_array and implode should solve your issue:
in_array('1', $_GET["smonth"]); // checks if January is in $_GET["smonth"]
implode("," , $_GET["smonth"]); // Pull all of the values out of $_GET["smonth"] as a A STRING
Try in your statement and d.month_of_year IN (" . implode(',', $smonth) . ")
= operator checks for single value. If you want to check multiple values, use in.
and d.month_of_year in (".$smonth.")
You also have a % there, which works with LIKE queries.
<?php
if(isset($_GET['month'])){
$month = date('m'); //This would give you the index of the current month.
$array = array('01','02','02');
$query = "select * from table where month = ";
if(in_array($month,$array)){
$query = "select * from table where month = '".$month."'";
//Then query here
}
else
{
$query = "select * from table";
$where = "";
foreach($month as $m){
$where .= ' month = "'.$m.'" and ';
}
//There would be a ending and pls just try remove it
$query .= $where;
// then query here
}
}
?>

Content is not visible in CodeIgniter calendar

I can insert data into the database using CodeIgniter and also get the data from the database, but the problem is I can't get the data from date 1-9 (the data is present in the database). After the 9th of the month, the data is retrieved successfully.
Controller:
function display($year=null,$month=null){
if (!$year) {
$year = date('Y');
}
if (!$month) {
$month = date('m');
}
$this->load->model('Calendar_model');
if ($day = $this->input->post('day')) {
$this->Calendar_model->add_calendar_data("$year-$month-$day",$this->input->post('data')
);
}
$this->load->model('calendar_model');
$data['calendar']=$this->calendar_model->generate($year,$month);
$data['viewName']=('Student/s_calendar');
$this->load->view('Student/template',$data);
}
Model:
function get_cal_data($year,$month){
$query=$this->db->select('date,data')->from('student_calender')->like('date',"$year-$month")->get();
$cal_data=array();
foreach($query->result() as $row){
$cal_data[substr($row->date,8,2)]=$row->data;
}
return $cal_data;
}
use this function for your calendar data the codeignitor only picks values past 9 because it compares the two characters in the html page to the two characters of days from your database. any number below 10 does not match because in your database it saves any day below 10 with a zero. use this
function get_calender_data($year,$month)
{
$query = $this->db->select('date, data')->from('calendar')
->like('date',"$year-$month",'after')->get();
$cal_data = array();
foreach ($query->result() as $row) {
if(substr($row->date,8,1)==0)
{
$cal_data[substr($row->date,9,1)] = $row->data;
}
else{
$cal_data[substr($row->date,8,2)] = $row->data;
}
}
return $cal_data;
}
I had the same problem via zend framework finally I got the point that the data in mysql is in this format :
YYYY-MM-DD HH:ii:ss
And my query was in this format :
YYYY-m-d h:i:s
It means for example I hade
2013-01-02 13:02:30
in database and I searched for time between
2013-1-2 13:2:30 and 2013-1-3 13:2:30
which gave me wrong answers.
use vardump and see your values of year and month!

Categories