I have updated certain field in my database & that field has default value as NULL. How can I again fill NULL if field is emptied or deleted. As during this updation blank value is filled in database and of course that is not NULL. Is filling NULL instead of blank value good?
Using php how can I do that? Suppose I have condition if code
if(!empty($photo))
{ $a in database;
}
But in this condition if $photo is empty it will fill blank value of $a... Let me know to fill NULL in database.
You just have to write null, and not an empty value, to your database.
You SQL query would look like this :
update your_table
set your_field = NULL
where ...
instead of :
update your_table
set your_field = ''
where ...
To switch between those two queries, you might need some condition in your PHP code, depending on how it's organized ; maybe like this :
if (empty($photo)) {
// query to set the field to NULL
}
else {
// query to update the value
}
Note that if you have no value to store for a row in your database, you might also want to just delete that row :
delete from your_table
where ...
Of course, it's up to you to determine which is the best for your application : a row with a NULL value, or no row.
Related
First off, forgive me the unsafe code, I will work on that later on.
For now this problem:
I have a page with a form to which a user can add fields and modify existing fields.
I sent the form and when the input is new I also create an empty hidden input field for the primary key column that's empty to add a new row to db. Only this row is not being created. When user modifies existing row it does work. So the update on duplicate key part works, but the Insert part for a new field does not work.
I already used print_r to check what the variables look like and indeed like I wanted for a new field footNoteID is empty and footNoteNL contains whatever user entered, and for a modified field footNoteID has the old primary key value and whatever was modified. So that looks alright.
Yet the Insert part for a new field does not work.
This is the code on the php page that processes the form:
// two posted arrays from a form with multiple input fields
$footNoteNL = $_POST['footNoteNL'];
$footNoteID = $_POST['checkfootNoteID'];
// looping through the arrays
for($j=0, $count = count($footNoteNL); $j<$count; $j++) {
$footNoteNLThis = $footNoteNL[$j];
$footNoteIDThis = $footNoteID[$j];
$sql4 = "INSERT INTO footnotes (footNoteID, albumID, addedDate, footNoteNL, footNoteEN) VALUES ('".$footNoteIDThis."', '92', '".$datum."' , '".$footNoteNLThis."', 0)
ON DUPLICATE KEY UPDATE footNoteNL = '".$footNoteNLThis."'";
$result = mysqli_query($conn, $sql4);
This is the form on the HTML side, and the jquery that adds the input and hidden field. This part works. I use brackets on the form field to create a posted array. Like said, when checking what gets posted it seems ok.
$(document).ready(function () {
$('.addButton').on('click', function () {
$(".footNoteContainer").prepend("<div><input type='hidden' name='checkfootNoteID[]' value=''><TEXTAREA NAME='footNoteNL[]'></TEXTAREA>
// and so on
The part of the form this gets prepended to:
foreach ($mysqli->query('SELECT * FROM footnotes WHERE albumID = '.$album_id.' ORDER BY addedDate ASC') as $row ) {
<TEXTAREA NAME='footNoteNL[]'>".stripslashes($row['footNoteNL'])."</TEXTAREA>
<input type=\"hidden\" NAME=\"checkfootNoteID[]\" VALUE=\"".stripslashes($row['footNoteID'])."\">
// and so on, just to show that here the field are non empty since they get pulled form db
and here is what a check looks like when adding a new field, and modifying an existing ones: "_newly added field value 9092_old input value"
So before the underscore of the newly created field, there is no value for $footNoteIDThis , which makes me expect a new row gets added to db. For the modified field there is the old key "9292" so that\s a duplicate and indeed that one gets updated ...
this is dump form db:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Table structure for table `footnotes`
--
CREATE TABLE `footnotes` (
`footNoteID` int(111) NOT NULL,
`albumID` int(11) NOT NULL,
`addedDate` date NOT NULL,
`footNoteNL` text NOT NULL,
`footNoteEN` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Indexes for table `footnotes`
--
ALTER TABLE `footnotes`
ADD PRIMARY KEY (`footNoteID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `footnotes`
--
Sorry for all the info, hopefully it makes sense, sorry for cumbersome method, but I really don't see why this doesn't work, although I suspect the problem lies in the db table settings or structure?
I am not using HTML form to get values for this query. I am just inserting a second query once user creates a specific record. However, the second query is not inserting '0' unless I change it to VARCHAR. Others are working fine except for number.
$null = null;
$query2="insert into npi_program2 (prodID,prodName,TPM,scheme,phases,status,number,date,remarkProg)
values('$prodID','$prodName','$null','$null','$null', 0 ,DATE_FORMAT(NOW(),'%b-%d-%Y'),'$null')";
$res1=$db->query($query2);
0 is not equal to null. 0 is false. To insert null in the database, you should pass NULL as a value.
$query2="insert into npi_program2 (prodID,prodName,TPM,scheme,phases,status,number,date,remarkProg)
values($prodID,$prodName,NULL,NULL,NULL, 0 ,DATE_FORMAT(NOW(),'%b-%d-%Y'),NULL)";
$res1=$db->query($query2)
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));
I am trying to check if a value column is null then insert a value into it based of a series of if statements, my only problem is I don't know what the value of null actually is in PHP.
I have checked that the id_created is being echo'd out, and the first insert script is working but it seems there is problem with my if statement:
if (isset($_POST['ra'])){
$db->query('INSERT table (`lid`, `id_created`, `call_start`) VALUES ('.intval($_GET['id']).','.intval($_SESSION['user']['id']).',NOW())');
if ($_SESSION['user']['id'] == $calllogs['id_created']){
if ($calllogs['call_end'] == 'Null'){
$db->query('INSERT INTO table (`call_end`) VALUES (NOW()');
}
}
}
Thanks
If I have a table with 3 columns: id,column1,column2. If i want to update column1 just when receiving "column1" parameter in URL request otherwise update column2 when receiving "column2" parameter in URL adress. Is that possible? I made that but i think that's not correct:
$sql= "UPDATE people SET
answer_yes= '$answer_yes'+1,
answer_no='$answer_no'+1";
Thank you for helping.
EDIT: Now that is working (based on Richard Vivian answer)
If($answer_yes==1)
{
$sql= "UPDATE people SET answer_yes= answer_yes +1"or die(mysql_error());
mysql_query($sql);
}
else if ($answer_no==0)
{
$sql= "UPDATE people SET answer_no= answer_no+1" or die(mysql_error());
mysql_query($sql);
}
You can create 2 SQL statement options:
If($answer_yes)
{
$sql= "UPDATE people SET answer_yes= '$answer_yes'+1"
}
else
{
$sql= "UPDATE people SET answer_no= '$answer_no'+1"
}
I'm unsure which database model you are using, but the logic would be to pass a NULL value if you don't have a value to pass, and check that the values not null before updating.
SQL Server
UPDATE Table
SET Column1=ISNULL(#Column1,Column1),
Column2=ISNULL(#Column2,Column2)
MySQL
UPDATE Table
SET Column1=IFNULL($Column1,Column1),
Column2=IFNULL($Column2,Column2)
What is happening here is that ISNULL/IFNULL is checking whether the first value passed to it is NULL, and if it is, its returning the 2nd value. The 2nd value is the same value as the current value, and therefore it updates it with the same value (ie. Not changing the value).
You can do this:
UPDATE people
SET answer_yes = COALESCE($answer_yes + 1, answer_yes),
answer_no = COALESCE($answer_no + 1, answer_no);
The COALESCE returns the first non NULLable value in the values passed to it. If any of the parameters $answer_yes or $answer_no were passed with a NULL value, then $answer_yes + 1 and $answer_no + 1 will be evaluated to NULL also, there for the COALESCE will return the column value, and in this case the column will be updated with its value, i.e, it won't changed.