I am sending values to a php script on the same server as a MySQL database. A php script sends the values to the database. However, somewhere along the path sometimes a value loses a decimal and I end up with an extremely high value.
I am monitoring PH and a few other things so the number is relatively low (between 4-12). Sometimes I end up with 720 instead of 7.20. Should this be corrected through a trigger? If so how? Or should it be handled on the PHP side? How can I not accept values or render them null when entering? Thank you for your time.
<!DOCTYPE html>
<html>
<body>
<h1></h1>
<?php
// Create connection
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$temp1 = ( $_GET["1"] * 9/5)+32;
$temp2 = ( $_GET["3"] * 9/5)+32;
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$sql = "INSERT INTO `ANALOG_SENSORS` (`TEMPERATURE`, `HUMIDITY`, `TEMPERATURE2`, `HUMIDITY2`,`PH`,`DATE_TIME`)
VALUES (" . $temp1 . ", " . $_GET["2"] . ", " . $temp2 . ", " . $_GET["4"] . ", " . $_GET["5"] . ",
NOW()- INTERVAL 7 HOUR)";
$result = mysqli_query($con, $sql);
}
</body>
</html>
Floating-point variables (float / double) should be handled as floating-point variable.
In MySQL and PHP, valid floating-point number are numbers with a dot as separator between integer and decimal part.
var_dump(floatval('13.37')) => double(13.37)
var_dump(floatval('13,37')) => double(13)
As you can see, with a coma, the decimal part is cut off, MySQL act exactly like this.
You have to be sure that your input data is formatted as is has to be.
$ph = str_replace(',', '.', $_GET['5']);
In a MySQL query, a coma is reserved character, if your data include a coma and isn't in a string (like in your case), the coma will be interpreted as separator, and add a new column to the insert query.
SELECT 1.2 => 1.2
SELECT 1,2 => [1, 2]
Also, make sure that your MySQL table fields' type are correctly set to float/double.
Related
I am looking to generate a random number say 01:20 and then add 8 hours onto that and store that as a variable. However I want to do this within only the time and not use any random integers.
The date given for the query is found using a preset date at the moment set to 01-01-2017. StaffID is gotten from a loop through another table.
This is the PHP code snippet.
strtotime($random_hour = rand(00,23));
echo $random_hour . " Hour <br> ";
strtotime($random_min = rand(01,59));
echo $random_min . " Min <br> ";
$randomhourmin = $random_hour . ":" . $random_min;
echo $randomhourmin . "<br>";
This is the final SQL insert query.
$sql = "INSERT INTO schedule (staffID, cdate, starttime, endtime, dayoff) VALUES ('$rowID','$fDate','$randomhourmin','$randomhourmin','0')";
You can use below
$int= rand(1262055681,1262055681);
Also check mt_rand(), which is to have better randomness in the results:
$int= mt_rand(1262055681,1262055681);
To turn a timestamp into a string, you can use date(), ie:
$string = date("Y-m-d H:i:s",$int);
I need to search a text column for the occurrence of certain words in the column.
For instance as an example the column contents may look like:
KIT: TYPE WELD NECK ORIFICE FLANGE, CONSISTING OF TWO FLANGES WITH
JACK SCREWS BUT WITHOUT BOLTS AND GASKETS, RATING CLASS 600, RAISED
FACE, BORE TO MATCH .312 IN WALL, MATERIAL FORGED 304 STAINLESS STEEL
ASTM-A182 GRADE F304, SPECIFICATION: SP-50-13 REV: 1
Now the user needs to enter into a textbox for instance the following:
ASTM-A182 F304 WELD NECK
Currently I use this code:
$sql = "SELECT * FROM commtable WHERE MATCH (ldisc) AGAINST ('" . $ldisc . "' IN NATURAL LANGUAGE MODE);";
But most records returned (it returns hundreds of records) don't contain all the search terms entered in the text field.
How can I fine tune this full text search (or use another method) to give me a better result more closely to what was entered?
EDIT:
Table type:
EDIT 2:
It is working now, added this code:
if ($ldisc != "") {
$parts = explode(" ", $ldisc);
$tempSQL = "SELECT * FROM commtable WHERE MATCH (ldisc) AGAINST (" . "'";
for ($i = 0; $i < count($parts); $i++) {
$tempSQL = $tempSQL . '+' . $parts[$i] . ' ';
}
$tempSQL = $tempSQL . "' IN BOOLEAN MODE);";
$sql = $tempSQL;
$result = mysqli_query($con, $sql);
}
And changed the minimum word length to 1.
This question sounds like basically what you're looking for: MySQL fulltext search - Only results that contain all words
NATURAL LANGUAGE MODE by its nature returns approximate matches. To match all words in BOOLEAN MODE, you must add a + in front of every required word. For example,
MATCH (ldisc) AGAINST ('+ASTM-A182 +F304 +WELD +NECK' IN BOOLEAN MODE)
You'll have to split the input string and add the + signs. How to do that is left as an exercise to the programmer. =)
Change it to boolean mode
"SELECT * FROM commtable WHERE MATCH (ldisc) AGAINST ('" . $ldisc . "' IN BOOLEAN MODE);";
Another thing is to keep an eye on ft_min_word_length
I am trying to add a timestamp to my database when I update a form, and for reason that I do not know, I am getting an error... and when just trying to insert the year, month, day I get "1988" inserted into my database. I use a similar timestamp elsewhere on the same site and it works fine. What am I doing wrong?
Note: yes I know I should be using mysqli and I'm vulnerable to sql injection. I plan on converting the entire site later in the year.
$homeScore = ((strlen($game['homeScore']) > 0) ? $game['homeScore'] : 'NULL');
$homeOdds = (str_replace("\xBD", ".5", $homeScore));
$visitorScore = ((strlen($game['visitorScore']) > 0) ? $game['visitorScore'] : 'NULL');
$visitorOdds = (str_replace("\xBD", ".5", $visitorScore));
$odds_timestamp = date("Y-m-d g:i:s A");
$sql = "update " . $db_prefix . "schedule ";
$sql .= " set odds_timestamp = " . $odds_timestamp . ", homeOdds = " . $homeOdds . ", visitorOdds = " . $visitorOdds . "";
$sql .= " where gameID = " . $game['gameID'];
mysql_query($sql) or die('Error updating odds: ' . mysql_error());
You have missing (single) quotes " . $odds_timestamp . "
that will need to be '" . $odds_timestamp . "' since it will contain characters that MySQL will complain about... being hyphens.
That is a string.
Now, if any of your other variables are also strings, they too need to be quoted as shown.
I.e.: '" . $string . "' as opposed to " . $integer . "
More on string literals:
https://dev.mysql.com/doc/refman/5.0/en/string-literals.html
Pay attention to Riggs' comments, one of which being:
"You would be best advised to make the datatype a DATETIME or TIMESTAMP as if you keep the VARCHAR it will make the data much more difficult to process later. Just change the date() to produce a legal MYSQL data format"
Using a VARCHAR won't fix it, as it still considered as a string literal for the column.
New comments by Riggs:
"You would be best advised to make the datatype a DATETIME or TIMESTAMP as if you keep the VARCHAR it will make the data much more difficult to process later. Just change the date() to produce a legal MYSQL data format. You can always add the AM/PM when you present the date time to any user. VARCHAR date/time will really mess with your selection criteria later as well. Remember - Database for DATA, Browser for PRESENTATION"
You can use MySQL's NOW() function, which returns current datetime.
Without error message, Its difficult to say something.
or if you can print your query it will be helpful.
but try with.
odds_timestamp = '" . $odds_timestamp . "'
to make it explicit string.
Try adding a timestamp column in the database table with an on update set current timestamp clause.
Heres a simple example from MySQL Documentation:
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Should take care of it and cut out the middle man. Win-win.
I made a simple query system through mySQL which is showing me 100 records and I fetch them into my game but I have probelm with the codes in PHP.
I want to have 5char space between each row So I have to use tab space (\t\t\t\t\t), But I have a problem with this current system (e.g If I have field with two diffrent string value 10char and 2char then use tab space to make space between them I get different results:
2Char string + 5char space = 7Char and 10Char string + 5Char space = 15Char
$query = "SELECT * FROM `scores` ORDER by `score` DESC LIMIT 100";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result);
for($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
echo $i+1 . "-" . "\t\t Name: " .$row['name'] . "\t\t\t\t Device: " . $row['device'] . "\n \t\t Difficulty: " . $row['level']. "\t\t\t\t Score: " . $row['score'] . "\n\n";
}
Codes Output
1- Name: James Device: HTC OneX
Difficulty: Hard Score: 5760
2- Name: Erika_S Device: PC
Difficulty: Normal Score: 13780
...
My Desired Output
1- Name: James Device: HTC OneX
Difficulty: Hard Score: 5760
2- Name: Erika_S Device: PC
Difficulty: Normal Score: 13780
...
Tab in fact is one char, but displayed in the way that user want. When, for example, in IDE you choose 8 spaces for 1 tab you will get it. There's a fantastic concept called elastic tabstops, but it's only concept - so sad.
Conclusion: you can't do it what you described with tab.
What you can do:
Calculate needed spaces and hardcode with , but it's dirty and you shouldn't do this.
Use html tables
Instead of $row['...'] use sprintf("%-15s", $row['...']), but in each place you'll need to adjust the number (-15) to what's really needed
<?php
$s = 'monkey';
$t = 'many monkeys';
printf("[%s]\n", $s); // standard string output
printf("[%10s]\n", $s); // right-justification with spaces
printf("[%-10s]\n", $s); // left-justification with spaces
printf("[%010s]\n", $s); // zero-padding works on strings too
printf("[%'#10s]\n", $s); // use the custom padding character '#'
printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters
?>
The above example will output:
[monkey]
[ monkey]
[monkey ]
[0000monkey]
[####monkey]
[many monke]
read more at http://www.php.net/manual/en/function.sprintf.php
if you can't use printf, you can easily create your own function that does something similar, and is enough for what you need:
function add_spaces($str, $total_len) {
return $str . substr(" ", 0, $total_len - strlen($str));
}
I'm working on a legacy database table that has a phone no. field
but the problem is that all the entries (over 4k) are in varying
formats.
I was wondering if there was a quick way to fix them by looping through the records using PHP and updating the records to a particular phone format
4K doesn't sound like many records at all.
And I'd bet that the varying formats fall into a finite number of combinations.
I wonder if it'd be possible with a few judicious SQL queries. If your RDBMS has regular expressions and string replacement functions you could manage it with a few UPDATE instructions. If not, any language with the capability of querying a database, doing string replacement, and updating would do the job.
I agree 4k records isn't anything to worry about. I suggest querying the phone numbers and the primary id of the table, stripping all characters from phone number and then manipulating it to be the format you want. Or, you could keep it as only numbers and use your front-end to modify the number every time you display it. Below is a little untested script you can try to use. Doesn't handle extensions and expects there are 10 numbers.
// mysql_connect stuff
$q = mysql_query("Select phone_id, phone_number From phones");
while($r = mysql_fetch_assoc($q)) {
$num = ereg_replace("[^0-9]", "", $r['phone_number']);
if(strlen($num) == 10) {
$num = substr($num, 0, 3) . '-' . substr($num, 3, 3) . '-' . $substr($num,-4);
}
$update = mysql_query("Update phones Set phone_number = '" . $num . "' Where phone_id = " . $r['phone_id']);
// updated?
}