PHP: validate decimal Mysqli data type - php

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)

Related

Why is this md5 function returning null sometimes?

I'm selecting a couple of values from a mysql database, combining and hashing them. Sometimes the result is null. Anyone know why?
First we fetch an associative array representing the row.
$results = dal::query("select foo, email from wtf where email = ?", $_GET["email"], "row");
Then we check for truthy results and hash.
if($results["foo"] && $results["email"]){
$whyisthisnullsometimes = md5($results["foo"] . $results["email"]);
$url = "https://example.com/dostuff.php?thing={$whyisthisnullsometimes}";
}
$whyisthisnullsometimes occasionally is just null. Not sure why.
The url is appended to an email message and sent. Users are hitting this link, which would not exist if ($results["foo"] && $results["email"]) evaluates to false.
wtf.foo is char 32 and wtf.email is varchar 250. collation is latin1_swedish_ci
That is quick answer:
when
if($results["foo"] && $results["email"]){
your condition is false you have $whyisthisnullsometimes not defined and php interprets it as null.
For further information you should post bigger fragment of your code :-)

Passing 0 to database but not an empy text input

I am passing user entered numerical values into a database using text inputs. I want the db to execute the insert for all numerical values greater than or equal to 0 however if nothing is in the textbox I do not want the database to execute the insert. So I would like to distinguish between 0 and no entry. isset would still return true. any help would be great
Thank You
I have my code written, I just need help with the logic test of determining whether zero or null.
You want to use isset in this case as it will detect if the textbox is null or not set however it will pass if it is 0
if (isset($_POST['textbox']))
You can further combine it with strlen like this:
if (isset($_POST['textbox']) && strlen($_POST['textbox']) > 0)

Problems inserting negative numbers in MySQL with PHP

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

Enter either a date or a null value in database using MySql

I have searched the site and although I have found questions and answers similar I haven't been able to find an answer. After 4 hours of searching I've decided to bite the bullet and ask the question.
I have 4 date fields in a form that aren't required. I would like it to enter a date into the database if one of the fields has an entry or null if any are left blank.
I have an if statement that checks if the value is empty and if so $value = null, otherwise use $value = date("Y-m-d",strtotime($_post['value'])) to convert it to a date and this works well.
The problem is in my query. If I use '$value' it will insert the date correctly but won't insert a null value because using 'null' makes sql think it's a string. If I use just $value the null inserts just fine but the date goes in as 0000-00-00.
Any advice would be very much appreciated
Thanks for the advice so far...
Null is allowed, this is my script...
if(empty($_POST['fp32_original_install_date'])){
$fp32_install = NULL;
}else{
$fp32_install = date("Y-m-d",strtotime($_POST['fp32_original_install_date']));
}
$sql = "INSERT INTO accounts_cstm (id_c, support_c, install_date_c, sware_renewal_date_c, product_key_c, account_status_c, fp32_support_type_c, fp32_support_renewal_date_c, fp32_original_install_date_c) VALUES ('$Guid','$cdr_support', '$cdr_install', '$cdr_renew', '$prod_key', '$account_status', '$fp32_support', '$fp32_renew', $fp32_install)";
If I use in the query $fp32_install a null value goes in just fine but a date goes in as 0000-00-00, if I use '$fp32_install' the date goes in fine but a NULL value goes in as 1970-01-01 (probably because it sees 'NULL' as a string)
If I echo $fp32_install the value is shown as 2012-08-16 and the SQL type for the column is date and the default is NULL
If you are using posted values from a form, then $_POST['value'] will not be NULL.
You should check for empty values instead.
if($_POST['value']=="")
{
$value="NULL";
}
else
{
$value="'".date("Y-m-d",strtotime($_POST['value']))."'";
}
From the behavior you describe, it sounds as if your DATE column is defined with a DEFAULT 0 clause, or you are providing an invalid value.
According to the MySQL documentation:
<snip>
Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00' or '0000-00-00 00:00:00').
</snip>
It's difficult to diagnose the exact problem without seeing example code. As a starter, I suggest you try echoing out the SQL statement that is being sent to the database.
I have a strong suspicion that the value for the DATE column is going to appear with quotes around it, a string value of 'NULL', rather than the bare keyword NULL.

How do I get PHP to convert a blank field in MySQL to "0"?

I have created a field in MySQL named "pid", which I use in PHP coding at the end of other variable names to indicate which of 7 template designs a user has created. The limit is 7, at which point they are given a message that they have reached their limit.
I have the code working EXCEPT when the field is blank (before user creates the first template). When I hard-code a "0" it works. But, obviously, I need to use the "{pid}" variable to pick up the template sequence in the database.
Here is the PHP:
<?PHP
$pid = {pid};
$total_templates = 7;
if ($total_templates > $pid) {
echo "<a href='create.template.php'><img src='create_template.png'></a>";
} else {
echo "<b style='color: #CC0000'>Your limit of $pid Templates has been reached";
}
?>
How do I get the code to convert a blank field in MySQL to "0" in conjunction with the above code?
If I understand your question, could you not set it to 0 if it is empty()?
$pid={pid};
if(empty($pid))
$pid = 0;
You can also set the default value for that field in mysql. If you are using phpAdmin, go to the table and click the "Change" action and set the default value there. If you need sql command to do this, I can get that for you too.
The best way is to set the default value in mysql to 0. Then you will have no issues.
You could always use intval in order to force it as an integer. See http://php.net/manual/en/function.intval.php.
if ($total_templates > intval($pid))
Although I would just set the default value of the pid field to 0 in MySQL.
You could use the ternary operator to set the $pid value
$pid = ({pid} != '' ? {pid} : '0');
If there is a real value on $pid it'll display it, else it'll display 0, I haven't tested this code.
A better approach would be to set a default value for that field in your SQL.
For more info about the ternary operator

Categories