I asked a question about bigints yesterday which was kindly answered. However, I have been observing some weird behaviour and would like to understand what is going on.
In my php I have an array which I send back to a javascript web client program which uses it.
In the php
sendBack = null;
sendBack[0]['TimeStamp'] = $Time; // A bigint got from a mysql table milliseconds from 1970
sendBack[0]['Text'] = $Message; // A varchar message got back from mysql
// I am guessing at this point you have worked out this is a text-chatroom thing going on
sendBack[1]['TimeStamp'] = 0; // A zero indicates an admin issue - note its an int but a small one
sendBack[1]['Text'] = $MessageAdmin;
// And I pack it up to send back
echo json_encode($sendBack);
In the js I unpack it to use with:
var json = eval('(' + data + ')');
The problem is, the 0 index TimeStamp in the js is being treated as a string but the index 1 Timestamp is being treated as an int.
From an educational point of view does anyone know what is going on?
I believe values returned from a database with PHP are always strings. In order to convert your zero-index timestamp you'd need to do something like:
sendBack[0]['TimeStamp'] = parseInt($Time, 10);
which will convert it to an integer value (base-10).
Obviously the 1-index timestamp is being set as zero directly hence the reason it's returning as an int.
Related
My idea is to make tooltip for new users on website. They will go through the tooltips and each time they complete a tooltip it inserts into DB.
However i've got a button which is skip all. So my idea is to insert all the reminder tooltips which they've not completed into the DB with for loop.
So it works if there has been no tooltips clicked already. So the tooltip would be equal to 1 because coming through the $data is equal to 0. However if the tooltip is equal to 1 when passed through $data it gets a +1 and the for loop doesn't seem to post anything into database
$NumberOfTooltips = 2;
(int)$data->tooltipLastID = ((int)$data->tooltipLastID === 0) ? 1 : (int)$data->tooltipLastID + 1;
for ($x = (int)$data->tooltipLastID; $x <= $NumberOfTooltips; $x++) {
$query = "";
$query = "INSERT INTO tooltips ";
$query .= "(tooltip_id, inserted) VALUES ($x, NOW())";
database::query($query);
$this->id = database::getInsertID();
}
On the broken loop the value of (int)$data->tooltipLastID is 2
Is it because the (int)$data->tooltipLastID is already equal to $NumberOfTooltips?
General improvements
These do not directly solve the question asked but they do give you a helping hand in clarifying your data and steaming out any secondary bugs and bloopers. Also pointing out some best (or at least, better) practise.
$x is a lazy and poorly defined counter. Prefer using descriptve veraibles such as $tooltipCounter
$data->tooltipLastID should not start at 1; use the same syntax as every other integer number system in PHP/programming and start at zero. If you need a one then add +1 only when it's needed (VALUES (".$x+1.")).
$NumberOfTooltips = 2; The number 2 is probably not high enough for adequate testing.
var_dump($data->tooltipLastID) and var_dump($NumberOfTooltips) to check both values are what you expect.
Rewrite the test code to take the variables out of the code so that you can check your Database connction works correctly (such as if you're trying to insert into a string field-type by mistake)
$query = ""; is redundant.
You should not need to type cast (int) your object variables ($data->whatever) all the time but type cast them when they're set.
Also by adding +1 to a variable PHP automatically recasts the variable as an int anyway.
Check that your $data->tooltipLastID is publicly accessible/writable.
You use $this ; so which class are you in? Are you self referencing the data class?
A bank holiday is just one day.
It is better the inserted Database column is set by the database automatically upon insert. You can use this SQL to alter your current table:
ALTER TABLE <yourTable> MODIFY COLUMN inserted timestamp DEFAULT CURRENT_TIMESTAMP
Check the type of $data->tooltipLastID? And plz use var_dump($data->tooltipLastID) and var_dump((int)$data->tooltipLastID) before the for loop to see what indeed the original value and the $x is.
Strange type casts will result in strange bugs...
On my website I am attempting to make a countdown timer. The same code for the timer works if I tell it the value of the column and it works on a test php page. The problem is that the mktime value is not being read right from the mysql database. However if I put the column to output inside of an echo it outputs fine. The column that contains the data is called expire. The other values I am loading from mysql are inside of he echo however all connection statements are made before I call any. I am using the mysqli_fetch_array to call the values.
$target = mktime($row['expire']);
$today = time();
$difference = $target-$today;
$hours = $difference/3600;
$minutes = ($hours-floor($hours))*60;
echo('ENDS IN: '.floor($hours).' Hrs '.floor($minutes).' Mins');
Yes the document is HTML that it gets included into
The way I formatted the expire column in mysql was standard as Hr,Min,Sec,MM,DD,YYYY. The actual content of the column is "21,0,0,7,12,2017"
Thanks in advance, David.
The problem is, that you get a string from your database in $row['expire']. But mktime() is an integer only function. So, first you need a workaround to explode and convert your string to integers, before it will work with mktime().
Please delete the following line from your code:
$target = mktime($row['expire']);
Try this instead:
$timeparts = array_map('intval', explode(',', $row['expire']));
$target = mktime($timeparts[0],$timeparts[1],$timeparts[2],$timeparts[3],$timeparts[4],$timeparts[5]);
Hope it was helpful. But please do not save timevalues as a string in your database. Read about other possibilities in the manual.
For the past 2 days I have been looking over the internet on how to handle data stored as json in mySQL database.All I found was a single article in here which I followed with no luck.So here is my question
This is my table called additional with 2 columns only...jobid and costs. jobid is an int of length 5 and obviously the primary key, costs is simply stored as text. Reason I combined all the costs under one column is because the user in my application can put whatever he/she wants in there, so to me the costs is/are unknown. For example one entry could be
24321 , {"telephone" : "$20"}
or
24322 , {"telephone" : "$20", "hotel" : "$400"}
and so on and so forth but I hope you get the point.
Now given this example I need to know how to handle data in and out from the database stored as json using php. So insert, select and update but I think with one given example I can do the rest If someone can help me understand how to handle json data in and out from a database.
Oh and one last thing. Not only I need to know how to fetch the data I need to be able to separate it too e.g:
$cost1 = {"telephone" : "$20"};
$cost2 = {"hotel" : "$400"};
I really hope someone can help with this because like I said above I spent 2 days trying to get my head around this but either no articles on this matter(except the one from this site) or completely irrelevant to my example
You tagged it as PHP so you can use php functions: json_encode and json_decode.
For example when you read (SELECT) and got this cost value in string corresponding to the primary key 24322:
//after you query db and got the cost in string...
$sql = "SELECT * FROM additional";
$result = mysqli_query($conn,$sql); $row = mysqli_fetch_array($result);
//from your comment below.... just changed to $cost so I don't have to change everything here...
$cost = $row['costs'];
//$cost = '{"telephone" : "$20", "hotel" : "$400"}'
//you just have to:
$cost = json_decode($cost);
// result in an object which you can manipulate such as:
print_r($cost->telephone);
// $20 or:
print_r($cost->hotel);
//$400;
//or if you want to go through all of the costs... you change that to array:
$cost = (array)$cost; //or on your json_decode you add a TRUE param... ie(json_decode($cost, TRUE))...
print_r($cost);
//will produce an associative array: ['telephone'=>'$20', 'hotel'=>'$400']
//for which you can do a foreach if you want to go through each value...
On the other hand when you save to db with an object:
$cost = (object)['hotel'=>'$300', 'taxi'=>'$14'];
//you json_encode this so you can write to db:
$cost = json_encode($cost);
//a string... you can then use $cost to write to db with (insert, update, etc)
Note: json_decode needs the input string to be UTF-8 encoded. So you might need to force your mysql server to provide UTF-8. Some reading: https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql
Hope this helps...
You can use json_encode() and json_decode() throughout your update or insert process.
Basically
json_encode() takes Array and returns JSON as String
json_decode() takes JSON as String and returns Array
http://php.net/manual/en/function.json-encode.php
So in your case whenever you want to update 24321 , {"telephone" : "$20"}
you got to decode like
$array = json_decode($row['jsonDataOrWhateverTheColumnNameIs'],true);
$array['telephone'] = "40$";
...
...
$jsonString = json_encode($array); // Use this string with your update query.
I have a VBScript that I`m converting to PHP, I hae some part that I don`t understand and don`t know the output of ... Also if possible, provide me with a similar method in HTML/PHP
TextBox1.Value = 1#
txtTurnoverIncl = TextBox1
Format(CDbl(txtTurnoverExcl.Text) * _
CDbl(txtRoyalty.Text) / 100, "#,##0.00")
If txtTurnoverExcl.Text <> "" Then
Format(Round(.Text * 14 / 114, 2), "#,##0.00")
TextBox1 = Now()
TextBox3 = Date
TextBox4 = Format(MyDate, "dddd")
And this function:
Private Function SumCashUp() As Double
Dim i As Long
Dim tmp As Double
For i = 10 To 12
With Me.Controls("TextBox" & i)
If IsNumeric(.Text) Then
tmp = tmp + CDbl(.Text)
End If
End With
Next i
SumCashUp = tmp
End Function
I guess thats all.
TextBox1.Value = 1# - Assign the value 1 in format Double to the textbox control. (thanks MikeD)
txtTurnoverIncl = TextBox1 - Assigning reference to the control TextBox to variable called txtTurnoverIncl
CDbl(txtTurnoverExcl.Text) - Convert the text inside the textbox txtTurnoverExcl to double i.e. numeric value with decimal point e.g. 2.6 - this is useful if you want to perform mathematical operations on the value for example.
Format(..., "#,##0.00") - Format number to look like this: 2.60 or 8.25 i.e. with two digits after decimal point.
Round(.Text * 14 / 114, 2) - The .Text means you're inside With (somecontrol) block, so it's actually somecontrol.Text i.e. taking the Text of the control. Round function will round the number for example Round(662.791, 2) will return 662.79 and Round(662.796, 2) will return 662.8
Now() - Returns the current date and time on the machine where the code is executing
Date or Date() - Like Now() but only with the date, time will be 00:00:00
Format(MyDate, "dddd") - Get name of the day of week of MyDate, according to the Culture on the machine. For example for Hebrew culture it will return יום שלישי for English culture it will return Tuesday. In general, Format() given date and string will Format the date according to the string e.g. Format(Now(), "dd/MM/yyyy") will return 14/12/2010
The last function returns the sum of the values of the textboxes named "Textbox10", "Textbox11", and "Textbox12" in a pretty complicated way. I guess in PHP you would do something like this (assuming you are POSTing a form):
function sumCashUp() {
return (double) $_POST['Textbox10'] + (double) $_POST['Textbox11'] + (double) $_POST['Textbox12'];
}
first of all it would be better to analyze what the whole thing is doing (semantically) rather than looking at sequences of code. So the remainder of this post is a bit speculative ....
There are a couple of textboxes displayed on the screen
TextBox1 ... initialized with value 1(double), later containing current time (now()) (imho a sin in itself - brrrr - hope there is good business logic explanation for this)
TextBox3 ... initialized with the current date
TextBox4 ... initialized with "something we don't know" - hopefully a date (MyDate), and formated as Weekday ("dddd")
TextBox10 - TextBox12 ... seem to be used to calculate a variable SumCashUp
we have some more variables which may be textboxes as well (as sometimes we see a .Text added in the code)
txtTurnoverIncl
txtTurnoverExcl
txtRoyalty
SumCashUp
and a code fragment that calculates a 14% margin from a Gross (*14/114), rounds and formats the result ... and we have no clue about where this result is used. We can speculate that it may be another form field (because of .Text) - maybe txtRoyalty - but we don't know.
Basically all the code fragments are about putting values into textboxes displayed on the screen and/or using the values of that text boxes to compute something (like the SumCashUp or a 14% GM).
So I guess the path to the solution must be
get the source layout of textboxes
understand the business logic
create a HTML page containing a form with similar objects (textboxes, a submit button, etc.)
write PHP code that implements the business logic - most probably as a reaction to a POST event triggered by a Submit button
You already received a couple of code fragments, but one needs to put this into a greater context, otherwise the code blocks won't help.
I am attempting to grab a date supplied via POST, then generate a list of dates over a 12 week period from the supplied start date. These dates would then go into the DB and a 12 week schedule would be output, which the user can interact with (add/edit/delete).
I am successfully taking the start date, generating the 12 week date list and adding this into the DB in serialized form, but when it comes to selecting the dates for display, I get the following error:
Notice: unserialize() [function.unserialize]: Error at offset 0 of xxx bytes in ...
Here is my code:
1st .php file here to take a form input (a date) and then get a list of each date over a 12 week period from the start date, and insert into the DB:
The array:
$start = strtotime($_POST['Start_Date']);
$dates=array();
for($i = 0; $i<=84; $i++)
{
array_push($dates,date('Y-m-d', strtotime("+$i day", $start)));
}
$savetodb = serialize($dates);
The insert:
$sql = "INSERT INTO programme VALUES (NULL, '20', '".$_POST["Start_Date"]."' , ' ".$savetodb." ', '".$_POST["Programme_Notes"]."')";
2nd .php file here - SELECT and unserialize:
$result = mysql_query("SELECT Programme_Dates FROM programme");
while($row = mysql_fetch_array($result))
{
$dates = unserialize($row["Programme_Dates"]);
echo $dates;
}
From what I've read the problem could be related to the DB column where the serialized array is inserted (ie being too small), but it is set to TEXT so that should be fine right? I also thought there may be certain characters within a date causing problems, but when testing with a "regular" array (ie just text), I get the same errors.
Any suggestions / hints much appreciated, thanks.
Why are you using stripslashes? My bet is that is the problem. Remove that from there and see if it works.
As a side note, stripslashes should be avoided as if data is probably inserted into the database they should be escaped properly meaning no extra slashes should be added. If you need to stripslashes from the data itself I would suggest using something like array_filter after you unserialized the array.
EDIT
You should also look into SQL Injection and how to prevent it, as your code is suseptible to be exploited.
UPDATE
Looking further at your code you insert the serialized array with 2 extra spaces: ' ".$savetodb." ', try using just '".$savetodb."', that and see if it fixes your issue.
i have found that the serialize value stored to database is converted to some other way format. Since the serialize data store quotes marks, semicolon, culry bracket, the mysql need to be save on its own, So it automatically putting "backslash()" that comes from gpc_magic_quotes (CMIIW). So if you store a serialize data and you wanted to used it, in the interface you should used html_entity_decode() to make sure you have the actual format read by PHP.
here was my sample:
$ser = $data->serialization; // assume it is the serialization data from database
$arr_ser = unserialize(html_entity_decode($ser));
nb : i've try it and it works and be sure avoid this type to be stored in tables (to risky). this way can solve the json format stored in table too.