How to grab items from a DB by date - php

This is my script:
$spending_period = time() - (30 * 24 * 60 * 60);
$spending_period = date('Y-m-d', $spending_period);
$monthly_income_query="SELECT amount FROM budget_items WHERE (date_code >= '$spending_period') && (type=='Income') ORDER BY date_code DESC";
$monthly_income_result=mysql_query($monthly_income_query);
while($monthly_income_scan=mysql_fetch_array($monthly_income_result)){
if($montly_income_counter >=1){
$monthly_income=$monthly_income + $monthly_income_scan['amount'];
}
}
I receive an error that mysql_fetch_array() is not a valid result resource.
The goal is to grab only items in the budget_items table that have a date_code (using the DATE type) occurring within the last 30 days.
Anyone have suggestions?

If something doesn't work with your
query - you may want to try it out in
mysql console with some sample date.
If data is returned, then try printing out a query. I have a hunch that $spending_period variable might not be interpolated correctly into your query string (try using '{$spending_period}' instead of '$spending_period'.

You need to format the date as a strong and use CAST inside the select statement to accept the value as a date value.

Related

save database rows in a cookie and then retrieve them

i want to use PHP setcookie() and i am having a problem with it. as a matter of fact i want to fetch some rows from data base then first save them in cookies and then retrieve them. consider i have a table in my database with multiple rows and for example 4 column. how can i do this. this is my current code. any idea thank you
<html>
<body>
<?php
error_reporting(0);
include("config.php");
$quer= "SELECT*FROM ".$db_table." ";
$query=mysqli_query($connect,$quer)
or die(mysqli_error());
?>
<?php while($row = mysqli_fetch_array($query)):
setcookie("$cookiename", $row, 2 * 24 * 60 * 60 * 1000);
//i do not know how can i retrieve columns now
?>
<?php endwhile;?>
</body>
</html>
In your case mysqli_fetch_array() function returns an multidimensional array, which means that you should refer to the $row variable, for example:
$row[0][0] // 1st row, 1st column
$row[2][4] // 3rd row, 5th column
You can also fetch data as an assotiative array, look at http://php.net/manual/en/mysqli-result.fetch-array.php
Here's an example:
$cookie_name="cook";
setcookie($cookie_name, $row['key'],2 * 24 * 60 * 60 * 1000), "/");
Check this out for more:setcookie
If you really want/need to save the entire row in the cookie you can pack the array $row in a single string eg as JSON:
//modified example from #Satty
$cookie_name="cook";
setcookie($cookie_name, json_encode($row),2 * 24 * 60 * 60 * 1000), "/");
//to read the cookie:
if(isset($_COOKIE[$cookie_name]))
$row_from_cookie = json_decode($_COOKIE[$cookie_name]);
If there is a certain caracter that you can be sure of that it isn't present in your data so it can be used as a separator (eg. ";") you could also use implode and explode to pack your entire array in a single string.
But if some of the columns are of any type that can contain any character I wouldn't do it like that since there can always be a character that you didn't expect in your data (eg. if you only store names you may assume that nobody has a semicolon in his name but it's still possible that somebody enters a semicolon in the input field).

MYSQL query using LIKE function for date

I have the following statement in the where statement of a mysql query:
WHERE scrap_date LIKE '%-01-%'
I want to grab all the data with the scrap_date being in January. The error I recieve is:
"Incorrect datetime value: '%-01-%' for column 'scrap_date' at row 1"
The datatype for scrap_date is DATETIME.
Not sure what syntax to use to get data with the a date in January, any suggestions?
You are assuming the date is represented internally as a string. It is not.
Since its a DateTime, use the MONTH function to extract the month and compare it to the desired value
WHERE MONTH(scrap_date) = 1
You may try this:
select * from your table WHERE MONTH(scrap_date) = 1
You can use the DATEPART() function
SELECT * FROM table
WHERE (DATEPART(mm, scrap_date) = 01)
use month function
WHERE MONTH(scrap_date) = 1

PHP adding 2 variables not equaling to what its supposed to.(should be easy)

I have a column on my database called "hrs_worked" (int), where it stores the amount of hrs I've put into a project.
What i want to happen within my app is that:
A. i enter in my current worked hours,
B. Extract the hrs recorded on the database,
C. Take A and add it to B,
D. Take this new number and record the added total (A above and B)to the database since that will be my new total hrs worked on any given project.
i take in the new hours(that i submitted via form) with:
$hrs = mysqli_real_escape_string($c2d, $_POST['hrs']);
I pull out the old hrs in the database via:
$pullOutHrsQS = "SELECT hrs_worked FROM tlm_accounts WHERE company_name = '$compName'";
$pullOutHrsDoIt = mysqli_query($c2d, $pullOutHrsQS);
$originalHrsSet = (int)mysqli_fetch_array($pullOutHrsDoIt);
I then add them via:
$hrs += $originalHrsSet;
or
$hrs = $hrs + $originalHrsSet;
Now, lets say that my old hrs are 10hrs worked, and my new hrs are 5hrs worked, I want to add these together via
$hrs += $originalHrsSet;
or
$hrs = $hrs + $originalHrsSet;
and instead of this resulting in 15hrs, it results in 6hrs. The math is always wrong.
I guess the question i am asking is " What am i doing wrong?! Am i missing something?"
Thanks in advanced.
The better option would be to simply increment the field like this;
"UPDATE tlm_accounts SET hrs_worked = hrs_worked + '$hrs' WHERE company_name = '$compName'"
Hope that helps.
You don't need to SELECT data to UPDATE it (see Harry's answer), but for the record...
mysqli_fetch_array returns either an array or null but you are casting the return value to an int, so $originalHrsSet will always be either 1 or 0. Try this instead:
$result = mysqli_fetch_array($pullOutHrsDoIt);
$originalHrsSet = (int) $result[0];
You do not need to select a whole array for a single value. Try using mysqli_stmt_fetch instead. Try using var_dump with the values you enter just to make sure they're what you expect.

MySQL PDO NOW() as assigned value - is it possible?

I'm trying to pass a MySQL's NOW() function into PDO's assigned value through PHP and it's failing. I found that I must pass this directly into MySQL statement. But in my case, sometimes the datetime field can be empty.
Is it even possible to pass NOW() as PHP's assigned value?
Some code:
I'm building query dynamically and the datetime is dependent on some other variable's value.
if(isset($accountStatus)&&$accountStatus!=""){
$tmp[':account_status']=$accountStatus;
if($accountStatus==0){
$tmp[':vCodeExpire']="NOW() + INTERVAL 1 WEEK";
$tmp[':verified']=0;
}else{
$tmp[':verified']=1;
}
}
Building SQL query:
$sql="";
foreach($tmp as $k=>$v){
$sql.=str_replace(":","",$k)."=".$k.",";
}
$sql=substr($sql,0,strlen($sql)-1);
Then, I run PDO query:
$db=$pdo->prepare("UPDATE users SET $sql WHERE id=:id");
$db->execute($tmp);
I tried replacing double-quotes with single-quote around NOW() + INTERVAL 1 WEEK with no luck.
I also tried with single-quote around PDO query, but then $sql is passed directly, not using an assigned values.
is it possible?
No.
There are 2 solutions.
Calculate expiration date using PHP. Something like date('Y-m-d',strtotime('+1 week'))
Create a conditional part for the query
if(isset($accountStatus)&&$accountStatus!=""){
$tmp[':account_status']=$accountStatus;
if($accountStatus==0){
$accSql = "NOW() + INTERVAL 1 WEEK,";
$tmp[':verified']=0;
}else{
$accSql ='';
$tmp[':verified']=1;
}
$db=$pdo->prepare("UPDATE users SET $accSql $sql WHERE id=:id");
Use strtotime() instead of MySQL to get date values.

Is there a short and sweet function toString a single jSON object or similar in my example?

I have converted a PHP array into a single selection in a Codeigniter PHP function like so...
function check_week($week_array)
{
$sql = "SELECT X_id FROM products WHERE date_sub(curdate(), INTERVAL 1 DAY) <= updated_at;";
$query = $this->db->query($sql, $week_array);
$week = $query->result_array();
$weeks = json_encode($week[array_rand($week)]);
return $weeks;
}
and I get a return of ...
{"X_id":"XXX1AXPJV6"}
I have already narrowed this down to one id, so no need to use a loop, I just need the id in one simple move. (so I just want XXX1AXPJV6 as a variable). Also, I did try keeping in PHP for this and Codeigniter was finicky about allowing any conversion to string due to the call to this model is from a library file.
btw, my 1 DAY interval is for testing, it will be 7
An attempt at using...
$weeks2 = $weeks[0]['X_id'];
return $weeks2;
...gets error "Cannot use string offset as an array in..."
If I understand the question correctly
$weeks = json_encode($week[array_rand($week)]);
should be
$weeks = reset($week[array_rand($week)]); // returns the value of the first element in the array
hope that helps.
If you only need one random row, your SQL should retrieve only one random row.
function check_week($week_array)
{
$sql = "SELECT X_id FROM products WHERE DATE_SUB(CURDATE(), INTERVAL 1 DAY) <= updated_at ORDER BY RAND() LIMIT 1;";
$query = $this->db->query($sql, $week_array);
$week = $query->row_array();
return json_encode($week['X_id']);
}
Note the changes in the query, as well as the use of row_array() which returns a single key => value array, instead of result_array() which returns an array of arrays.
For what it's worth, you could've gotten the result you need by altering this line to:
$weeks = json_encode($week[array_rand($week)]['X_id']);
But the above is still a more suitable solution. Don't retrieve lots of records if you only need one.
Also, what is the $week_array parameter for? You are using it as a query binding, but there are no ? places for the bindings to go in your query, making it pointless.

Categories