UPDATE Query not working - PHP/MySQL/bind_param - php

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.

Related

How can I work with date in php and mysql?

I want to know how can I work with dates in MySQL and PHP. I want to know how many days remain, i want to know how many day is defference(distance) between nowTime and createTime ?
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
////ISSET
if (isset($_POST['projectId'])) {
$projectId = $_POST['projectId'];
$result = mysql_query("SELECT *FROM projects WHERE projectId='$projectId'") ;
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
$response["title"]=$result["title"];
$response["exp"]=$result["exp"];
$response["userIdKarmand"]=$result["userIdKarmand"];
$response["userIdKarfarma"]=$result["userIdKarfarma"];
$response["cost"]=$result["cost"];
$response["zemanat"]=$result["zemanat"];
$response["time"]=$result["time"];
$response["createTime"]=$result["createTime"];
$response["type"]=$result["type"];
$response["nowTime"]=DATE("y-m-d");
$response["remainTime"]=DATE("y-m-d")- strtotime($response["createTime"])+$response["time"];
echo json_encode($response);
}
else {
}
}
else {
}
?>
It's not working. What can I do? I want compare createtime and nowtime and find out how many days I have time?
strtotime converts formatted string date format to timestamp. You can't substract timestamp data from string data. You have to first convert $response["remainTime"] to timestamp using strtotime() and then substract strtotime($response["createTime"]) from this value.
The best way to go through a MySQL result would be to loop through the fetch_assoc() function.
$result = mysql_query("SELECT * FROM projects WHERE projectId = '$projectId'");
// while() through an associative array from the MySQL object
while($result =& $result->fetch_assoc()) {
$response["title"] = $result["title"];
$response["exp"] = $result["exp"];
$response["userIdKarmand"] = $result["userIdKarmand"];
$response["userIdKarfarma"] = $result["userIdKarfarma"];
$response["cost"] = $result["cost"];
$response["zemanat"] = $result["zemanat"];
$response["time"] = $result["time"];
$response["createTime"] = $result["createTime"];
$response["type"] = $result["type"];
$response["nowTime"] = DATE("Y-m-d H:i:s"); // this is how you would need to format dates to work with MySQL
$remainTime = (strtotime($response['nowTime']) - strtotime($response['createTime'])); // this would return how many seconds have passed since $response['createTime'] until now
$response["remainTime"] = $remainTime;
}
echo json_encode($response);
This would allow you to have how many seconds since $response['createTime'] held in the $remainTime variable.

Update Automatic Mysql Values php

Hello I want to update MySQL table automatic at set time like i want to update table at 5:30 i have some values to update in my database at set time automatic. in PHP
$date = date('H:i:s');
if($date == "11:26:00") // 17:30:00 is equal to 5:30 but in 24 system
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
while($row= mysqli_fetch_assoc($result1))
{
$Foo= $row['foo'];
}
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
Just lie what Ashish said you can use CRON , and if you want you maybe can use this , i did not use before , try it . This code will works once ,so you have to find away to make loop cause the time will change every sec .
Note : Check the second code .
<?php
// Database connect
$date = date('H:i:s'); // Set the time to hours and minutes and seconds format
// you can echo $date to check how it looks but it will be something like this : 07:21:48
if($date == "17:30:00") // 17:30:00 is equal to 5:30 but in 24 system
{
// You can type your code here .
}
?>
Second Code :
<?php
// Remember to connect to your database
$date1 = date_create("00:00");
$date2 = date_create("23:59");
while($date1<=$date2)
{
date_add($date1,date_interval_create_from_date_string("1 sec"));
$a = date_format($date1,"H-i-s");
if($a =='17:30:00')
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
$row= mysqli_fetch_assoc($result1)
{
$Foo= $row['foo'];
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
die;
}
else
{
// you can type anything here , you can end the process by typing die; or anything you want
}
}
?>
You can check this and see how you can loop throw date in php :
I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
This can help you understand the time and date system and how to change the format for the date in php : How to get the current date and time in PHP?

Codeigniter post view count function -

Hello i'm trying to make a post count function based on the codeigniter framework and what i done so far works great looking by my side. The function is complete and everything works fine.
But i have a question here from some experts to tell me that this is the correct ussage of the function and non of the above will harm my page loading. The function is accesed by jQuery get function on every click on the post.
First i'm checking if there is an ip address and if the ip address date inserted is more then 24 hours if its more i'm deleting the current row and then checking again becuase of the previous select its still remembering the last ip address and inserting again with new datime.
And other question should i make cleanjob every week or similar for all ip addreses ?
Here is my code:
function show_count($post_id){
$ip = $this->input->ip_address();
$this->db->select('ip_address,data');
$this->db->from('post_views');
$this->db->where('ip_address',$ip);
$query = $this->db->get();
foreach ($query->result() as $row){
$ip_address = $row->ip_address;
$data = $row->data;
}
if(isset($ip_address) && time() >= strtotime($data) + 8640){
$this->db->where('ip_address',$ip);
$this->db->delete('post_views');
}
$this->db->select('ip_address');
$this->db->from('post_views');
$this->db->where('ip_address',$ip);
$query = $this->db->get();
foreach ($query->result() as $row){
$ip_address_new = $row->ip_address;
}
if(!isset($ip_address_new) && $ip_address_new == false){
$date = new DateTime('now', new DateTimeZone('Europe/Skopje'));
$this->db->set('views', 'views+ 1', false);
$this->db->where('post_id',$post_id);
$this->db->update('posts');
$data = array(
'ip_address'=>$ip,
'data'=>$date->format("Y-m-d H:i:s")
);
$this->db->insert('post_views',$data);
}
}
Thanks, any suggestions will be appreciate.
Instead of doing lots of queries to increment unique views on your posts, you should use and set cookies and have a fallback method if cookies are not enabled.
$post_id = "???"
if(isset($_COOKIE['read_articles'])) {
//grab the JSON encoded data from the cookie and decode into PHP Array
$read_articles = json_decode($_COOKIE['read_articles'], true);
if(isset($read_articles[$post_id]) AND $read_articles[$post_id] == 1) {
//this post has already been read
} else {
//increment the post view count by 1 using update queries
$read_articles[$post_id] = 1;
//set the cookie again with the new article ID set to 1
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}
} else {
//hasn't read an article in 24 hours?
//increment the post view count
$read_articles = Array();
$read_articles[$post_id] = 1;
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}

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!

Trouble saving date and time to MySQL using 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...

Categories