i want to store the value of a checkbox into my sql database, basically i want to save the default value if it is checked or not.. i am not sure what this would save either true or false?
<div><input type="checkbox" value="Yes" name="chk"/> Yes! I will come!</div>
should I insert into my table like this?
'$_POST[chk]'
Thank you
$_POST[chk] will return the text Yes, in your case, if checked, and won't set it at all if not. Knowing this, you can set the db field how you want, say 1 or 0 for tinyint type:
$chk = isset($_POST['chk']) ? 1 : 0;
$sql = "update tbl set chk1 = $chk";
I would recommend using tinyint(1) datatype for the column in which you plan on storing whether a checkbox has been selected or not.
ALTER table `my_table` ADD COLUMN `my_checkbox_col` tinyint(1) unsigned NOT NULL default 0;
Yes. And sanitize input before you insert.
Use
if(isset($_POST[chk]) ) {
$chk = (string) $_POST[chk];
}
No.
You should do it like this
if(isset($_POST['chk'])):
$chk = mysql_real_escape_string($_POST['chk']);
else:
$chk = 0;
endif;
$sql = "INSERT INTO table VALUES ('$chk')";
Then insert the field as '$chk'.
This is the safest method and it's best to remove the [' '] part of a variable as it may affect your SYNTAX when adding it to the table.
Related
We recently updated our mariadb version and it is more strict on default column values, meaning if they are not set and not defined on insert it does not insert a new row. I am looking for a quick way to update all of the database columns that do not have a default value.
I imagine the code should look something like this, keep in mind this is only a pseudo code that I imagine and running this is not going to work:
$result = dbquery("SHOW TABLES");
while ($row = dbarray($result))
{
foreach ($row as $key => $table)
{
// this is the query where it should check
// if default value is set or not, but could not find information on how to do so
$result2 = dbquery("SHOW COLUMNS FROM $table WHERE DEFAULT IS NOT SET");
while ($column = dbarray($result2))
{
// SETTING A DEFAULT VALUE
dbquery("ALTER $table ALTER $column SET DEFAULT NULL");
}
}
}
NOTE: DISABLING STRICT MODE IS NOT A SOLUTION THAT I AM LOOKING FOR IN CURRENT TIME
Any ideas on how to select the columns where the default value is not set?
Thanks
Not providing a value for a nullable column is OK, so I suspect that you want to identify non-nullable column that have no default.
You could get that information from information_schema.columns:
select table_name, column_name
from information_schema.columns
where column_default is null and isnullable = 'NO'
From there on, you would need to decide which value should be used as a default; the answer does depends on your actual requirement and of the datatype of the column.
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.
I am having an issue with sql right now; I have gave a value a default so if the field is left empty when the user submit, but it is not working. When the user submits an empty field to leave a comment instead of it default to anon it does nothing. Also, in the datebase the field is empty.
name VARCHAR (50) default 'anon',
$name= $_POST['name'];
$title= sha1($_POST['title']);
$texts= $_POST['texts'];
$forum_id = $_POST['forum_id'];
$name = str_replace("'","''",$name);
$title = str_replace("'","''",$title);
$title = str_replace("b074acd521","STREAMER",$title);
$texts = str_replace("'","''",$texts);
$title = substr($title,0,8);
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
mysqli_query($conn1, $sql) or die('Error inserting to database.');
mysqli_close($conn1);
header('Location: requests.php');
Is there another way to do it or am I just doing something wrong?
The SQL query your using will not insert the default value from your database because you are specifying a value for name (even if that value is an empty string, or null) :
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
Instead if you want the default value to be inserted into the name field you must not specify the name column in the insert statement :
$sql = "INSERT INTO post (title, texts, forum_id) VALUES ('$title', '$texts', '$forum_id')";
In SQL query you can specify for which fields, values will be provided in the query and remaining fields from the table would contain default value (in case of AUTO_INCREMENT, the next integer value will be used).
Where you given the default value directly applied in SQL? the value left in DB ultimately is what exactly you passed to DB server by SQL way, or just you defined a variable where if it don't accept a value from user then use the default value instead, please try to debug this to insure the value was handled correctly.
while insert the values you shouldn't give the column which you set default value
below Example explain it...Try like this...
create table er(id int,name char(10),gender char(2)default 'M')
Here i took gender as default
now i insert the values
insert into er (id,name)values(1,'poda')
select * from er
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.
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.