I am trying to code a cron job so if a code in the database and is unused and older then 72 hours it drops the row in the database.
The problem I am having however is that when I am trying to get the array data in a row, so I can run an 'If statement' and then the drop command, when printing the array I get duplicates like as follows
33520891520891do not usedo not use----aaron hattonaaron hattonSunday 8th of September 2013 12:46:20 PMSunday 8th of September 2013 12:46:20 PMUnusedUnused--
My code is as follows
// Set variable for the time
$timenow = date('l jS \of F Y h:i:s A');
// Start Expired password check and drop function
function cronexec_expired ($timenow) {
include('../../config.php');
// Open up a new MySQLi connection to the MySQL database
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbTable);
// Query to check the status of the code input
$expiry_check = "SELECT * FROM code_log WHERE status='Unused'";
// Run the query
$expiry_checkexec = mysql_query($expiry_check);
while($expiry_possibles = mysql_fetch_array($expiry_checkexec)) {
foreach ($expiry_possibles as $expiry_possible) {
print_r ($expiry_possible);
};
}
}
// Start Redeemed Password check and drop function
// Execute Functions
cronexec_expired ($timenow);
Any help would be really appreciated!
Edit
When removing the 'foreach' and running the following:
print_r ($expiry_possibles);
I get the following
Array ( [0] => 3 [id] => 3 [1] => 520891 [code] => 520891 [2] => do not use [refid] => do not use [3] => - [hostname] => - [4] => - [userip] => - [5] => aaron hatton [creater] => aaron hatton [6] => Sunday 8th of September 2013 12:46:20 PM [timecreated] => Sunday 8th of September 2013 12:46:20 PM [7] => Unused [status] => Unused [8] => - [timeredeemed] => - )
Am I doing something wrong?
if you mean numeric index in your array output. use mysql_fetch_assoc() instead of mysql_fetch_array()
mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.
Related
I have just started to learn about serialization and I have a question that I cannot seem to find a simple explanation to.
Say I had a table called week and inside week I had 3 columns with the third column containing a bunch of serialized meal IDs like so stored in my database:
INSERT INTO `week` (`week_id`, `meal_code`, `meal_id`) VALUES
(1, 'week12016', 'a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}');
But later I want to append another meal_id to the existing string but not update any other column so it reads
(1, 'week12016','a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;}')
I have tried in a php file to store the following
$food=array("7");
$sfood=serialize($food);
Then trying to add the 7 to the existing meal_ids in the week table
mysqli_query($conn,"UPDATE week
SET meal_id ('$sfood')");
//if entry into the database is successful, confirm with a alert popup and refresh the home page
if(mysqli_affected_rows($conn) > 0){
//header("location: admin.php");
header("refresh:0; url=admin.php");
echo "<script type='text/javascript'>alert('Upload Successful!')</script>";
exit;
But when I check my database, nothing has changed.
What am I doing wrong, is it even possible to do what I am trying to achieve?
You have to read the column from your table row. Unserialize it into a PHP variable and then add a new occurance to it.
Then serialize the new array and store it back to your database
// SELECT from table
$s = 'a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;}';
$d = unserialize($s);
print_r($d);
$d[] = 99;
print_r($d);
$s2 = serialize($d);
echo $s2;
// UPDATE table row
RESULTS
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 99
)
a:8:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;i:7;i:99;}
Storing data like this is not recommended, as it makes this data impossible to process using queries
I have a database that has budgets in them (for this, I have modified the budgets to be fake).
Long story short, I am attempting to run the following SQL query on the database, and then display a report based on it.
Here is the query: SELECT MONTHNAME(date) AS month, product, SUM(amount) AS spend FROM client_budgets WHERE advertiser_id = '$advertiser_id' GROUP BY MONTHNAME(date), product ORDER BY MONTH(date) ASC
I then clean the data a little, here is the code for that:
foreach($data AS $key => $val) {
$clean_data[] = $val;
}
From this, I get the following (this is a PHP array of the data. I have cut it off since it has about 100K rows in the database currently).
Array
(
[0] => Array
(
[month] => January
[product] => Internet
[spend] => 12000.00
)
[1] => Array
(
[month] => January
[product] => Radio
[spend] => 12250.00
)
[2] => Array
(
[month] => February
[product] => Billboards
[spend] => 6000.00
)
[3] => Array
(
[month] => February
[product] => Internet
[spend] => 16000.00
)
)
My goal is to end up being able to display in a CSV (I already have the headers set for the CSV), the following:
Month, Internet, Radio, Billboards, Television
January, 12000, 12250, 6000, 0
February, 16000, 7000, 6000, 2000
....
I am stuck right now trying to sort the data correctly, and if there is no data for Television for instance one month, to display a 0. Any help would be appreciated! I have been attempting this for almost 3 days now.
I need to export a set of json data for highchart. But I'm having a problem with looping.
I've got 2 set of arrays:
Years Array (2015,2014,2013,2012) - form MySQL
Month Array (01,02,03,04,05,06,07,08,09,10,11,12)
So I make it in array - multidimensional. With this code.
$sql_arrYr=mysqli_query($con,"select year(bk_date1) as arrYr from booking_db group by year(bk_date1) order by arrYr asc");
while($rec_arrYr=mysqli_fetch_array($sql_arrYr)){
$arrYr[$rec_arrYr['arrYr']]=array("01","02","03","04","05","06","07","08","09","10","11","12");
}
Then I've got:
Array ( [2015] => Array ( [0] => 01 [1] => 02 [2] => 03 [3] => 04 [4] => 05 [5] => 06 [6] => 07 [7] => 08 [8] => 09 [9] => 10 [10] => 11 [11] => 12 )...);
Which is looking good coz I have all data I need in a set of arrays - year and each month values.
So I continue with fetching data from mySQL with this code.
foreach($arrYr as $key=>$val){
$rows=array();
$rows[type]='spline';
$rows[name]=$key;
foreach($val as $mon){
$sql_nBk=mysqli_query($con,"select count(*) as nBkr from booking_db where year(bk_date1)='$key' and month(bk_date1)='$mon'");
$rec_nBk=mysqli_fetch_array($sql_nBk);
$rows[data][]=$rec_nBk['nBkr'];
}
}
echo json_encode($rows);
The problem happened here. It's not loop. The only line I've got is.
{"type":"spline","name":2015,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
Which I expect this:
{"type":"spline","name":2015,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2014,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2013,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2012,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
Please give me a reason why it's not loop. Even I put them in a right loop.
You are setting $rows to an empty array each time through the outer loop. Also, you can't have duplicate keys. The first type is overwritten by the next (also name and data) so you have to make it multidimensional. You can use the $key variable for this to make it easy, or implement a counter $i and use $i++ or something.
$i = 0;
foreach($arrYr as $key=>$val){
$rows[$i]['type']='spline';
$rows[$i]['name']=$key;
foreach($val as $mon){
$sql_nBk=mysqli_query($con,"select count(*) as nBkr from booking_db where year(bk_date1)='$key' and month(bk_date1)='$mon'");
$rec_nBk=mysqli_fetch_array($sql_nBk);
$rows[$i]['data'][]=$rec_nBk['nBkr'];
}
$i++;
}
echo json_encode($rows);
I'm fairly new to php and sql, and I'm trying to pull a value out of an object or a nested object. I'm able to see the code when i use the print_r command, but i'm unable to separate the actual date from the oject, and I'm also not able to search the sql using the datetime criteria. I do know that the "Date" is stored in sql as a smalldatetime data type, and I don't know how to work with that.
when i try to search sql using the following:
$sql = "SELECT * FROM GL_Register WHERE (Register_Id='5' && Date='2010-12-8 0:00:00')";
I get the following error:
Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '&'. [message] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '&'. ) )
So i cannot pull a query with the date in there properly because i don't know how. to further clarify, i am able to pull information from the database using the following information, but i am still unable to pull out the date from within the Date object.
here's how i'm loading the object:
$sql = "SELECT * FROM GL_Register WHERE Register_Id='3'";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
else{
echo $sql;
}
while($obj = sqlsrv_fetch_object( $stmt)) {
$count++;
$row = '<tr>';
$row .= '<td>'.$count.'</td>';
//$row .= '<td>'.$obj->Date->DateTime->date.'</td>';
$row .= '<td>'.$obj->Account_Id.'</td>';
$row .= '<td>'.$obj->Customer_Id.'</td>';
$row .= '<td>'.$obj->Category_Id.'</td>';
$row .= '<td>'.$obj->Credit_Or_Debit.'</td>';
$row .= '<td>'.$obj->Memo.'</td>';
$row .= '<td>$'.$obj->Amount.'</td>';
$row .= '</tr>';
echo "$row";
}
when i use the "print_r($obj)", this is what it displays:
stdClass Object ( [Register_Id] => 3 [Account_Id] => 5 [Register_Number] => 17 [Credit_Or_Debit] => D [Accounting_Period_Id] => 13 [Date] => DateTime Object ( [date] => 2010-12-21 00:00:00 [timezone_type] => 3 [timezone] => MST ) [Register_Type_Id] => 1 [Reference] => 300002 [Type_CVEO] => C [Customer_Id] => 362 [Vendor_Id] => 1 [Employee_Id] => 1 [Other_Name] => [Offset_Account_Id] => 1 [Splits] => N [Amount] => 179.9600 [Mult_Sign] => 1 [Memo] => Security Services [Status] => O [Is_Offset] => N [Offset_Register_Id] => 4 [Branch_Id] => 2 [Job_Id] => 1 [Service_Ticket_Id] => 1 [Category_Id] => 6 [Job_Expense_Code] => [Expense_Type_Id] => 5 [Post_WIP_Account_Id] => 1 [Primary_Register_Number] => 0 [Part_Id] => 1 [Currency_Id] => 1 [Exchange_Rate] => 1.0000 [Amount_Nat] => 179.9600 [Date_Time_Stamp] => DateTime Object ( [date] => 2010-12-21 12:29:06 [timezone_type] => 3 [timezone] => MST ) )
I need to be able to do two things, and i feel like i'm banging my head against the wall. It's just out of my reach and i'm hoping someone can help me out.
Questions:
How to fix the sql query using the the datetime criteria (ie pull all register_id's that have a date within the last 3 days)?
How to pull the date and time out of the object and place it into a php variable
use AND instead of &&
SELECT * FROM GL_Register WHERE Register_Id='5' AND Date='2010-12-8 0:00:00'
Ok, so with the help of a friend and chetan above, i was able to answer the first question. my first problem was that i had the wrong operators in the question. my second problem, was i was formatting the date wrong. the date needed to be formatted one of the following two ways:
select * from GL_Register where Date = '07/01/2013'
or
select * from GL_Register where Date = {d'2013-07-01'}
The first method uses an implicit conversion from varchar to date. The order of the date IE 'mm/dd/yyyy' or 'dd/mm/yyyy' is controlled by your local settings.The second method is more proper as the {d} specifies that the varchar is to be converted to a date and is not dependent on your date format settings.
but i still need the answer to the second question, how do i print the date out on a datetime object?
answered the second question. since the sql was outputting data in the DateTime format, i needed to create a new DateTime variable and dump the information into that object. once i did that, i was able to format the data ho i needed to and use it accordingly.
$newDate = new DateTime('NOW');
while($obj = sqlsrv_fetch_object($stmt)) {
$newDate = $obj->Date->format('Y-m-d');
This outputs the date in the format i need.
I'm currently writing a script that would extract all the dates from a message and convert them to timestamps. PHP's strtotime (similar to Unix's date -c 'some date') would be perfect for this, as it recognizes all kinds of dates, such as:
5pm today
2010-11-15 16:30
Thursday 8:00
However, I'm having trouble finding those dates in the first place. For example, in the following string,
I'll be there for dinner tomorrow at 9:00pm
I need to isolate "tomorrow at 9:00pm", as that's the part that strtotime recognizes.
Is there a regular expression or something similar that would return me all dates that can be parsed by strtotime?
The only thing I can think of is date_parse. A regular expression that matches any format accepted by strtotime would be huge.
An example of date_parse:
$str = "I'll be there for dinner tomorrow at 9:00pm";
$parsed = date_parse($str);
print_r($parsed);
It would output something like this (I removed the unimportant parts from it to make it the result lighter):
Array
(
[year] =>
[month] =>
[day] =>
[hour] => 21 // 9:00pm
[minute] => 0 // 9:00pm
[second] => 0 // 9:00pm
[fraction] => 0
[warning_count] => 1
[is_localtime] => 1
[zone_type] => 2
[zone] => -540
[is_dst] =>
[tz_abbr] => I
[relative] => Array
(
[year] => 0
[month] => 0
[day] => 1 // tomorrow (would be -1 for yesterday, etc.)
[hour] => 0
[minute] => 0
[second] => 0
)
)
Whether this works for you depends primarily on what your input looks like. If you have more than one instance of a date in your input string, it will not work as expected.
This might not be totally efficient, but should work for any date string that consists of up to 5 words in length. I would write the function, but I think you'll get the idea with the comments below...
$words = explode(' ',$original_string);
// Use the array_chunk() function break up this array into 1-word,
// 2-word, 3-word, and 4-word long substrings of the original string
// Reform them back into strings and pass each one through strtodate()