trying to INSERT NULL if input field left blank - php

I'm trying to insert NULL into the mySQL databse with PHP.
I've got:
$myVariable=$_POST[inputfield];
if(!is_numeric($myVariable) || $myVariable==0){
$myVariable=NULL;
}
My database field is decimal, and IS NULL has been set. It keeps reverting to 0.00 if input is left blank. How do I set NULL if left blank, so I can call a php if NULL function?
Edit Calling if NULL in decimal is not correct?
<? if ($debit==NULL || $debit=="0.00") {echo 'Awaiting Cost';}
elseif ($debit != NULL || $debit!="0.00") { echo "£$debit";}?>
This displays my message correctly, so if if NULL is useless for a decimal i'll just leave 0.00. Is this hacky?
SQL structure for those who asked:
`myTableField` decimal(10,2) default NULL,

If you are composing an SQL statement by appending the value of the $myVariable variable, then you should look if it's NULL or not and modify the SQL statement accordingly.
For example, if your code is something like:
$sql .= "myVariable = '" . mysql_real_escape_string($myVariable) . "'";
then you should change it to something like:
if (is_null($myVariable)) {
$sql .= "myVariable = NULL";
} else {
$sql .= "myVariable = '" . mysql_real_escape_string($myVariable) . "'";
}

Try it on the SQL side:
$sql = "INSERT INTO `table` (`field1`) VALUES (IF($myVariable == 0, NULL, $myVariable))";

try:
$myVariable="NULL";
.
if your code is:
$val=NULL;
mysql_query("SET #v=$val");
the MySQL got the string:
SET #v=0;
it's like using :
echo "SET #v=$val";

you can filter field's data in MySQL itself, using a TRIGGER:
CREATE TRIGGER table1_update BEFORE UPDATE ON table1 FOR EACH ROW SET
NEW.num=IF(NEW.num=0 ,NULL,NEW.num),
NEW.txt=IF(NEW.txt="",NULL,NEW.txt);
CREATE TRIGGER table1_create BEFORE INSERT ON table1 FOR EACH ROW SET
NEW.num=IF(NEW.num=0 ,NULL,NEW.num),
NEW.txt=IF(NEW.txt="",NULL,NEW.txt);

Related

How do I store NULL date in Mysql [duplicate]

I am having trouble inserting null values into date fields into a MySQL table.
Here is the insert query:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ("'.$string1.'", "'.$string2.'", '.$date1.', '.$date2.')';
Columns s1 and s2 take string values and d1 and d2 take dates. When I run this query with only the string fields, there is no problem.
The date values can be either set or null, so I have not included the quotation marks in the query, but have instead added them to the variable earlier on. This is the php code I am using to set the date values:
if (empty($date1)){
$date1 = NULL;
}
else{
$date1part = explode("/",$date1);
$date1 = '"'.$date1part[2].'/'.$date1part[1].'/'.$date1part[0].'"';
}
When the date values are all set, the record is inserted correctly. However, when either of the dates is null, nothing is inserted.
Why can't I just insert null values into MySQL like this?
Try this:
$query = "INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ('$string1', '$string2', " . ($date1==NULL ? "NULL" : "'$date1'") . ", " . ($date2==NULL ? "NULL" : "'$date2'") . ");";
so for example if you put this into query:
$string1 = "s1";
$string2 = "s2";
$date1 = NULL;
$date2 = NULL;
result should be:
INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL);
You should convert the null variable into a NULL string first
Like this:
if(is_null($date1)){
$date1 = 'NULL';
}
If you are using a MySQL date column, you must also specify that it should hold null when creating it, like this:
CREATE TABLE `table` (
id INT NOT NULL AUTO_INCREMENT,
date DATE NULL DEFAULT NULL,
PRIMARY KEY(id)
)
It is also very important that you perform the query with bound parameters, for example using pdo
http://www.php.net/manual/en/pdo.construct.php
http://php.net/manual/en/pdo.prepared-statements.php
How do I insert NULL values using PDO?
Something like this:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES (?, ?, ?, ?)';
$stmt = $db->prepare($query);
$stmt->execute(array($string1,$string2,$date1,$date2));
If NULL does not work, just pass your date as "0000-00-00":
$chequeDate = "0000-00-00";
Backslash N is another way to express NULL in MySQL.
Try putting the value (backslash N): \N into one of the parameters like this:
$data1 = "\N";
$sql="insert into tablename set column_s1='" . $data1 .
"', column_s2='" . data2 .
"', column_s3='" . $data3 . "'";
Reference: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
In Derby, If you want to insert values except the ones you have declared Null (column_d1, column_d2), sql:
INSERT INTO DB.table (column_s1, column_s2) VALUES ('s1', 's2');
Probably answer is unneeded at this moment, but I found solution exactly I have been searching. Use an Expression to pass NULL like this:
['some_date_to_update' => new Expression('NULL')]
Hence, MySQL will understand what you want, and save (NULL) in DB instead of storing 0-dates. Hope this will help somebody.
In Mysql DATE data type Default NULL means
Some version set as 0000-00-00
Some version set as 1970-01-01
Years later, if someone is still experiencing this issue, you want to use PDO and bind the variables, everything will be taken care of no need to handle the null variables yourself.

How to make form with many query PHP MYSQL

How to make FORM with many query from input in php and mysql, should i only use query or use many condition to make the final query, here's the example of the form:
maybe like this
SELECT * FROM aset WHERE lokasi= .. OR jenis=.. OR merk=.. OR tanggal=..
how to skip the one of the WHERE clause if the input in FORM is NULL?
Thankyou!
you can check if the field is given/has any value first and then add it to the query, so you can pass the query with only provided fields using the append "=." operator to add.
$query = "SELECT * FROM aset";
if($_POST['lokasi'] != ''}{
$query =. "WHERE lokasi ='something'";
}
if($_POST['jenis'] != ''}{
if (strpos($query, "lokasi") !== false) //if lokasi exists in the query then add AND
{
$query =. " AND WHERE jenis ='something'";
} else {
$query =. " WHERE jenis ='something'";
}
}
You should or simply set your table column to DEFAULT NULL wherein everytime you insert record to the table, if there's a skip field in the form, it will still insert the query to the table.
For example when you create a table.
create table sample(id int(11) not null auto_increment,sample_column_1 varchar(255) default null,sample_column_2 varchar(255) default null,primary key(id));

Create mysql table from PHP array

A user is creating a table. The user enters the number of fields that will be in the table, and a form is generated based on the number they entered. They then enter the names of the columns and the type. I then create the table based on what they entered.
I can get the arrays to populate correctly, but my error message says I have a syntax error. I'm sure I did something wrong, but I tried to add a while loop inside the query since there is no set number of variables to be entered. This is what I have. If there's a better way to do it, I'm all ears.
$sql = 'CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id), ';
while($numDone < $totalFields){
$sql .= $colName[$x] . ' ' . $types[$x] . ', ';
$x++;
$numDone++;
}
$sql .= ')';
$query1 = mysql_query($sql) or die(mysql_error());
**Solved
I changed the single quotes to double quotes, used the dot operator for $table, and added an if statement for the comma. It's working now.
For one, this
'CREATE TABLE $table'
will NOT fill in $table, but will be LITERALLY
CREATE TABLE $table
use " if you want variables to be shown. You would've spotted that if you'd just echo your $sql. There might be more, but probably easily discoverable trough mentioned debugging...
You apparenty have an extra trailing comma:
CREATE TABLE $table (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
col1 INT,
col2 INT,
-- ^ here
)
1
change the single quotes (') to double quotes (") for your query.
2
or use dot operator (.) to append php variable.
$tableName = "mytable";
echo $query1 = "SELECT * FROM $tableName";
echo $query2 = 'SELECT * FROM $tableName';
// Output
SELECT * FROM mytable
SELECT * FROM $tableName
You may have VARCHAR field entered without size like fieldname VARCHAR will return error instead it should be like fieldname VARCHAR(100) ? Trailing comma may also be the reason for error as Quassnoi commented.
If you are trying to get rid of the trailing slash you can also do this by using a counter.
$fieldsCount = count($listingFields);
foreach($listingFields as $key => $listing)
{ // create the insert statement (do not add comma at the end)
$query .=" ".$listing[0];
if ( $key+1 != $fieldsCount )
{
$query .=',';
}
}

MySQL int column allows null but enters null as zero

I've looked around and have noticed a few people have had the same problem but their oversight doesn't seem to apply here.
I have a PHP function to add an array of values into a table. It first checks whether the values are empty and if so replaces them with NULL, in order to place a null in the table field. Each fields that I'm placing null into allows for null yet places a 0 there instead.
Here's some code:
public static function AddGame($array, $tId)
{
global $db; // Bring DB into scope
// Get IDs from particular names
$locId = $array['fLocation'];
// Ensure empty values are SQL null
$hTeamId = "'{$array['fHomeTeam']}'";
$vTeamId = "'{$array['fVisitTeam']}'";
$hScore = "'{$array['fHomeScore']}'";
$vScore = "'{$array['fVisitScore']}'";
$hHoldFor = "'{$array['fHomeHoldFor']}'";
$vHoldFor = "'{$array['fVisitHoldFor']}'";
// Prepare row for insertion
$row = "'','$tId','$locId',$hTeamId,$vTeamId,'{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
$stmt = $db->prepare("INSERT INTO `game` VALUES($row)");
if($stmt->execute()) return true;
else return false;
}
I've debugged this function at various lines and have dumped the $row string and it shows this, which is expected:
'','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL'
Yet when I check the table text type fields literally have the value NULL which is not what I want and also int fields show as 0. If I leave the values blank or as PHP's null then text fields show as empty (or properly null as I'd like) yet the ints still show as 0.
I expect this is only caused due to the way I insert the values indirectly.
Here is the SHOW CREATE TABLE game
CREATE TABLE `game` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tId` int(11) NOT NULL,
`Lid` int(11) NOT NULL,
`hTeamId` int(11) DEFAULT NULL,
`vTeamId` int(11) DEFAULT NULL,
`date` text NOT NULL,
`time` text NOT NULL,
`hScore` int(11) DEFAULT NULL,
`vScore` int(11) DEFAULT NULL,
`type` text NOT NULL,
`hHoldFor` text,
`vHoldFor` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1
UPDATE:
INSERT INTO `game` VALUES('','1','1','','','10/09/12','9:30AM','','','pool','winner of pool A','winner of pool B')
You are physically setting the value of the wanted NULL columns to a string of 'NULL'
NULL != 'NULL'
If you set your table structure for those columns to NULL, you can omit them from your query and they will automatically be NULL on insert.
Do this instead:
if(!empty($hHoldFor)) $hHoldFor = $array['fHomeHoldFor'];
Update
I was looking further into your example and there is a second point of failure.
$row = ... ",'$hHoldFor','$vHoldFor'";
The above line, if you set $hHoldFor = NULL, will insert quotes around NULL, turning it back into a string of NULL.
Try this:
if(!empty($hHoldFor)) $hHoldFor = "'{$array['fHomeHoldFor']}'";
...
$row = ... ",$hHoldFor,$vHoldFor";
This removes the single quotes around this value in the QUERY string and adds them to the variable itself.
Update 2
Here is an SQLFiddle using your schema. It returns NULL for NULL columns. Can you do an echo "INSERT INTOgameVALUES($row)"; and post the output? The issue is PHP is converting the NULL to 'NULL' still somewhere. This will help us get to the bottom of it.
Update 3
The issue is just as thought. Your PHP is inserting a blank string, '', into your database, which is not a NULL value. NULL is of a type, '' is a string with no length.
INSERT INTO `game` VALUES('','1','1','','','10/09/12','9:30AM','','','pool','winner of pool A','winner of pool B')
Try this:
public static function AddGame($array, $tId)
{
global $db; // Bring DB into scope
// Get IDs from particular names
$locId = $array['fLocation'];
// Ensure empty values are SQL null
$hTeamId = (strlen($array['fHomeTeam']) != 0 ? "'{$array['fHomeTeam']}'" : 'NULL');
$vTeamId = (strlen($array['fVisitTeam']) != 0 ? "'{$array['fVisitTeam']}'" : 'NULL');
$hScore = (strlen($array['fHomeScore']) != 0 ? "'{$array['fHomeScore']}'" : 'NULL');
$vScore = (strlen($array['fVisitScore']) != 0 ? "'{$array['fVisitScore']}'" : 'NULL');
$hHoldFor = (strlen($array['fHomeHoldFor']) != 0 ? "'{$array['fHomeHoldFor']}'" : 'NULL');
$vHoldFor = (strlen($array['fVisitHoldFor']) != 0 ? "'{$array['fVisitHoldFor']}'" : 'NULL');
// Prepare row for insertion
$row = "'','$tId','$locId',$hTeamId,$vTeamId,{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
$stmt = $db->prepare("INSERT INTO `game` VALUES($row)");
if($stmt->execute()) return true;
else return false;
}
You can't insert 'NULL'. Remove the single quotes around NULL.
Your string
'','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL'
Should look like
'','1','1','21','21','10/10/12','10:30AM',NULL,NULL,'pool',NULL,NULL
You should also define a column list whenever making an INSERT (ie. INSERT INTO table (col1, col2) VALUES ...)
Edit 1
I would recommend looking through your SHOW CREATE TABLE tbl_name
Edit 2
After testing this, I would still say the problem is with how you're inserting the data.
(18,1,1,21,21,'10/10/12','10:30AM',NULL,NULL,'pool',NULL,NULL)
Works.
('18','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL')
Does not work: Incorrect integer value: 'NULL' for column 'hScore' at row 1:
Edit 3
Here is an improved version of your class:
public static function AddGame($array, $tId)
{
global $db; // Bring DB into scope
// Get IDs from particular names
$locId = $array['fLocation'];
// Ensure empty values are SQL null
$hTeamId = empty($array['fHomeTeam']) ? 'NULL' : "'" . $array['fHomeTeam'] . "'";
$vTeamId = empty($array['fVisitTeam']) ? 'NULL' : "'" . $array['fVisitTeam'] . "'";
$hScore = empty($array['fHomeScore']) ? 'NULL' : "'" . $array['fHomeScore'] . "'";
$vScore = empty($array['fVisitScore']) ? 'NULL' : "'" . $array['fVisitScore'] . "'";
$hHoldFor = empty($array['fHomeHoldFor']) ? 'NULL' : "'" . $array['fHomeHoldFor'] . "'";
$vHoldFor = empty($array['fVisitHoldFor']) ? 'NULL' : "'" . $array['fVisitHoldFor'] . "'";
// Prepare row for insertion
$row = "$tId,$locId,$hTeamId,$vTeamId,'{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
$stmt = $db->prepare("INSERT INTO game (tId, Lid, hTeamId, vTeamId, date, time, hScore, vScore, type, hHoldFor, vHoldFor) VALUES($row)");
if($stmt->execute()) return true;
else return false;
}
Non-NULL values will be encased in quotes, otherwise they are assigned NULL. I've also defined the column list for INSERT and excluded id, as it's an AUTO_INCREMENT column.
Does you column allows NULL values? Check the DDL again maybe you have set the DEFAULT VALUE to zero.
When you try to insert null value in a column, don not wrap it with single quote. Example
INSERT INTO tableName (colName, ColNameB) VALUES (1, NULL)
In my case i had to display three situations: Case-empty, Case-yes and Case-no. I planned to use null, one and zero. But the null was being saved always as 0. The column i was working accepted null entries but all my nulls was being saved as zeros.
My solution, was considering Case-empty as zero, Case-yes as the number one and case-no as the number two. It is a workaround but solved the problem.

PHP and MySQL SELECT problem

Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks!
MySQL code.
SELECT *
FROM names
WHERE name = '" . $_POST['name'] . "'
AND userID = '$userID'
Here is the MySQL table.
CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
If $_POST['name'] is actually an array of strings, as you say, then try this PHP:
$namesString = '';
foreach ($i=0; $i < count($_POST['name']) $i++)
{
$namesString .= "'" . mysql_real_escape_string($_POST['name'][$i]) . "'";
if(isset($_POST['name'][$i + 1]) $nameString .= ', ';
}
With this query:
SELECT * FROM `names`
WHERE `name` IN ( $namesString )
AND `userID` = '$userID'
The query will return all the rows in which the name is the same as string in $_POST['name'].
First of all, if the userID field is unique, you should add a unique index on it in your table.
Also, watch out for SQL injection attacks!
Using something like this is much more secure:
$sqlQuery = sprintf('SELECT COUNT(id) AS "found" FROM names WHERE userID = "%s"', mysql_real_escape_string($_POST['name'], $conn));
This SQL query will return 1 row with 1 field (named found) which will return you the number of matched rows (0 if none). This is perfect if you only want to check if the userID exists (you don't need to fetch all data for this).
As for the dynamic array, you will have to post more information and I'll update my answer.
Meanwhile here are some usefull PHP functions that can help you do what you want:
For MySQL queries:
mysql_connect
mysql_real_escape_string
mysql_query
mysql_fetch_assoc
For your list of users:
explode
implode
Stated as you say, I'm quite sure the code does exactly what you are asking for. The SELECT should return the records that respond both to the name sent and the current user ID.
If you need some php code, here it is (should be refined):
$result = mysql_query('YOUR SELECT HERE');
if (!$result) {
die('ERROR MESSAGE');
} else {
$row = mysql_fetch_assoc($result));
// $row is an associative array whose keys are the columns of your select.
}
Remember to escape the $_POST.

Categories