I am trying to build a simple web app to keep up with my debt and I want to use the same database table for adding and also subtracting data.
I am converting the input from the input field using a simple php operation to convert it to a negative number:
$sum2 = $sum*-1;
$sum being the input field:
$sum = $_POST['shuma'];
The Idea is, when I input a positive number, my debt grows larger, when I input a negative number, my debt gets smaller, it's a simple idea.
In MySQL database, I am inserting the input into:
decimal(7,2) Default:Null
The problem is, the positive input, even though it's being converted into a negative number, it's not being inserted as negative in MySQL, it inserts it again with a positive number. The problem it's not within PHP because I tested it and even after the form it's submitted and data it's pushed into MySQL, I still can get the negative number shown using the echo in PHP.
Does anyone have any idea how to solve this?
P.S. Maybe I should mention, when I try to insert negative directly from phpmyadmin it works, it accepts the negative number in the same field.
Thank you.
change you field type to DECIMAL (10,2) . Field length defination is on you. Define length according to your requirement.
In this case negative value will be inserted. If not, then please die(); your query and execute it directly in mysql. Because for another field's problem also negative value not insert in table though the field type is DECIMAL.
Well, I am trying to use the same input field for both, only use a
checkbox, when the box it's checked, it's a negative number, otherwise
it's positive
About that comment.
i.e. you have
<input type="checkbox" name="negative"/>
<input type="text" name="sum" />
<?php
$sum = (int)$_POST['sum'];
...
so you can have, let's say two methods:
function increase($value) {
return query("UPDATE table SET value = value + $value");
}
and
function decrease($value) {
return query("UPDATE table SET value = value - $value");
}
so you are checking:
if(isset($_POST['negative']) {
decrease($sum);
}
else {
increase($sum);
}
However, the queries are just a sample, I just wanted to explain the logic, where you don't need to add the number with negative sign, but you can change the query depends on the checked inputs
Related
This may sound a little stupid but I need some help.I should save some records in the database as follow by accessing the following link:
http://localhost/whatsapp/index.php?r=users/create&mobile=012345678900
This is what I have in the controller:
public function actionCreate()
{
$model=new Users;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
echo "hello"." hii";
if(!isset($_POST['number']))
{
echo "aho";
$model->number="012345678900";
//$model->number=$_POST['number'];
echo 'bye';
//$model->attributes=$_POST['Users'];
if($model->save())
echo "done";
return "Doneeee";
}
}
The data is saved correctly except the column number.Always a certain number is saved as follows:
2147483647
Any dea why this is happening?!
Sql engine generate this kind of number when data type is not bigint and length of col is less than the length of number you entered.
In your Users table change the type of number to varchar and set its length to 15 or 20 or whatever you want.
Try this query
ALTER TABLE `users` CHANGE `number` `number` VARCHAR( 15 )
Note:- You are getting this problem because you have set your number field as int type. and the biggest value int type can hold is what you are getting in the database. So changing it to the varchar type will solve the problem.
A number starting with 0 is regarding as the OCTAL representation of the number
http://en.wikipedia.org/wiki/Octal
What is happening here is that the octal number, when represented as a "normal" or "decimal" number, gets to large, and overflows in the space provided (kind of like the mileage counter in a motor vehicle). Therefore, when the number gets saved, it gets converted into a number, then overflows.
The correct treatment is to regard this as a string, as suggested by #Let me see
I have a table with the column data type like this:
price decimal(6,2) unsigned NOT NULL,
And my validation code is like this:
if ( (!empty($_POST['price'])) && (is_numeric($_POST['price'])) && (isset($_POST['price'])) > 0 ) {
$price = ($_POST['price']);
} else{
$price = FALSE;
echo '<p> Only accept number and must be higher than zero</p>';
}
I use the $_POST form for users to submit the value. But you know,
1/ When the user types any non-numeric value such as a,b,c etc, it also validates well.
2/ When the user types the value zero in, it validates well too.
However, the question is that when I tested it with no value typed in. I mean that I left the value empty and hit the 'submit' button, the error message still returned as per the }else { part does, but the value was still inserted into the table column with a value of 0.00 technically at the same time.
To my limited knowledge, I can guess that the problem was probably at the Mysqli data type of the table I chose, but i don't know how to correct it.
Can you help me, please?
I think the solution you're looking for is to simply move the inserting code to the first if statement. That way it'll only insert the value if it is numeric and not empty.
What you describe means that you've failed to stop the insert when $price===false
(i.e. the problem is not the evaluation; it has given you the correct message. You've some programming logic error elsewhere)
I am new to elastic search and here is my scenario I am trying to solve.
I have a search input box that supports autosuggestion logic.
The results are fetched from an elastic index which uses ngram filter.
What I want to improve is to introduce a scoring capability so as to order the results from the most important to the less important one (depending on the score).
The score must be based on the following cases:
If there is a match that starts with the given string, set score 100
If there is a match that contains the given string and does not start with it, set score to 10
For this purpose an elastica script was implemented with mvel statements in order to support regular expression match. In other words, it checks to see if the value on the left matches the regular expression on the right (only then a variable is incremented accordingly). But unfortunately it goes wrong when search string is language specific despite the fact that the value on the left is of the specified language too. Another problem to deal with is the second case I mention above (cannot make it to work).
The script when a value ('one example' (belongs to the name field)) starting with the given word ('one') works just fine.
$testParam = mb_strtolower('one', 'utf-8');
$regexStart = '^' . $testParam . '.*$';
$ElasticaScript = new Elastica_Script(" total = 1; if(doc['name'].value ~= '{$regexStart}'){ total += 100; } return total; ");
The script when a value ('one example' (belongs to the name field)) contain the given word ('example') does not work and as a result total score remains 1 and does not increment to 11 as it should be.
$testParam = mb_strtolower('example', 'utf-8');
$regexStart = '^.*' . $testParam . '.*$';
$ElasticaScript = new Elastica_Script(" total = 1; if(doc['name'].value ~= '{$regexStart}'){ total += 10; } return total; ");
And at last, with the same logic, when I try to match a greek word against a value (containing greek letters) of the name field, the increment of the total score is ignored as well.
All the work has been done using the elastica, let alone php.
Could you please help to solve my problem ?
If there is another approach/solution, feel free to share it with me.
Thank you in advance
doc['name'].value loads the analyzed version of the field. Unless your field is set to not analyzed, this will likely be very different than the original content of the field, and not useful for doing regex matches. The Elasticsearch docs on script fields say this only makes sense for non-analyzed or single term fields. For example, if your content is indexed as ngrams, this value will consist of ngrams.
You can access the original text of the field using _source.field_name, and then compute your score based on that. You can still do your search as usual against the ngrams, and use the _source just for scoring.
Here's a sample function_score query that defaults the score to _score, adds 100 if the name field starts with one, else adds 10 if the name field contains one anywhere else. It uses _source.name to access the contents of the name field, so it's doing the regex against the original text of the name field, not the ngrams calculated from the name field.
{
"query": {
"function_score": {
"boost_mode": "replace",
"script_score": {
"script": "total = _score; if (_source.name ~= '^one.*') { total += 100 } else if (_source.name ~= '.*?one.*?') { total += 10 } return total"
}
}
}
}
I have GET[] input and would like to carry out their validation. The input data is always a number by. Schema. I want to make sure that the pass number and the appropriate amount - not to throw the sql query.
at this moment I am using the procedures
$cc = $_GET['cc'];
if ($cc=='') $cc='9012';$find=array("..", "/", "\\");
$replace=array("", "", "");
$cc=str_replace($find, $replace, $cc);
$eic = $_GET['eic'];
.... ect.
// where f.ex. 9012 is an real existing data (in dbase) to generate sucure sql question
GET[] variable data schema
$_GET[$cc] - always 4 digits
$_GET[$eic] - always 4 digits
$_GET[$iy] - always 4 digits
$_GET[$ir] - always 1 digit
Can you show me a better way to secure my GET?
If the query you're getting is always a digit you can use the intval() function in PHP to make sure its an int.
$eic = intval($_GET['eic']);
http://php.net/manual/en/function.intval.php
You can force numeric values by using intval().
You can't, however, represent values with a leading 0 like 0123 using this method.
If you don't have values with leading zeros use this:
<?php
$_GET['cc'] = intval($_GET['cc']);
strlen($_GET['cc']) == 4 ? $_GET['cc'] : $_GET['cc'] = 0; // Replace 0 with default/error value
// Repeat the steps above for all parameters...
?>
change in the number of digits in a variable crashes Query
Well, the whole point of validation is that you "validate" data and don't even bother disturbing your SQL database in case the data has not been validated. Why would you bother executing a query which you know to be invalid?
I don't really agree with using intval() for validation. With intval(), you're forcefully changing the value inputted by the user, which is not really validation. A better method would be to use is_int() instead.
For security? Nothing beats "Prepared Statements"
http://php.net/manual/en/pdo.prepared-statements.php
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.
include 'connect.php';
$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");
while ($row=mysql_fetch_assoc($sql)) {
$start=$row['start'];
}
echo $start; //nothing happens
From what I know float type isn't precise. It doesn't show you that actual value so 1.1 that you saved may not be the actual value stored. Trying setting your field as decimal and give it a length of say, 10,1 where 10 is the maximum number of digits (the precision) and 1 is the number of digits to the right of the decimal point (the scale). It should work doing query like stuff='1.1' or stuff=1.1.
WHERE stuff = '$stuff' is a String comparison.
Compare number like so
WHERE stuff = $stuff
Don't use float( even if you insert 1.1 into the table, the actual value for float type is not 1.1, but something like 1.100000023841858) . Change it to double in database (or decimal)
You might not be seeing any output because your echo is outside the loop.
The scope of your variable $start would be confined to the loop.
Change the stuff field to DOUBLE type.
Then,
SELECT * FROM table WHERE stuff=$stuff
this should be the sql query