<form action="hi.php" method="post">
<input type="text" name="id" />
<input type="hidden" name="name" value="name" />
</form>
I send this input with no value. I want to update id column as NULL.
$id = $_POST['id'];
$name = $_POST['name'];
$mysqli->query("UPDATE table SET id=$id WHERE name='$name');
However that updates it as empty not NULL. How I can insert NULL in $id?
If I send a value with <input name="id">, it updates it correctly. However if I send it empty, column becomes empty, I want it as NULL.
When using prepared statements and parameters, a NULL value in one of the parameters will also be treated as NULL by the MySQL server.
HTTP parameters are transported as strings. If no value has been given for an input control, the value for the key/value-pair will be an empty string (!=NULL). But you can still have somethig like if(emptystring) use NULL in your script.
e.g.
<?php
// only for this example; otherwise leave _POST alone....
$_POST['id'] = 1;
$_POST['name'] = '';
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_errno) {
trigger_error( sprintf('mysqli connect error (%d) %s', $mysqli->connect_errno, $mysqli->connect_error), E_USER_ERROR);
die;
}
mysqli_report(MYSQLI_REPORT_STRICT|MYSQLI_REPORT_ALL); // that's all the "error handling" for this example....
setup($mysqli);
// even if the user didn't fill in any value, the parameters should be in the request
// as empty strings
if ( !isset($_POST['name'], $_POST['id']) ) {
echo 'missing POST paramete';
}
else {
// <-- maybe some plausiblity checks here anyway; e.g. some assumptions about the id you can test, leaving it out as optional for now --->
// decision point: applying trim() to _POST[name] and _then_ consider it NULL or not - you might disagree about the specifics, just an example.
$name = trim($_POST['name']);
if ( 0===strlen($name) ) {
$name = NULL;
}
// <-- actually it would suffice to establish the databse connection here....
$stmt = $mysqli->prepare('UPDATE soFoo set name=? WHERE id=?');
$stmt->bind_param('ss', $name, $_POST['id']);
$stmt->execute();
printTable($mysqli);
}
function printTable($mysqli) {
$result = $mysqli->query('SELECT * FROM soFoo ORDER BY id');
foreach( $result as $row ) {
var_export($row); echo "\r\n";
}
}
function setup($mysqli) {
$mysqli->query('CREATE TEMPORARY TABLE soFoo (id int, name varchar(32), primary key(id))');
$mysqli->query("INSERT INTO soFoo (id,name) VALUES(1,'oldname1'),(2,'oldname2')");
}
prints
array (
'id' => '1',
'name' => NULL,
)
array (
'id' => '2',
'name' => 'oldname2',
)
I suggest you use PDO, and not mysql() but this will give you the idea:
$id = $_POST['id'];
if($id==''){
$id='NULL';
}
else{
$id = mysql_real_escape_string($id);
}
$qr = 'Update table SET id='.$id;
mysql_query($qr);
Related
This question already has answers here:
MySQL and PHP - insert NULL rather than empty string
(10 answers)
Closed 7 years ago.
I have a variable on php and it sometimes can be NULL and I want to insert this variable to my db. But problem is, PHP's null value does not insert to db as null value.
My column on db allows null values.
if($variable != true){
$variable = null;
}
//insert my null value to db
$insert = $db->prepare("insert into mytable set mycolumn = $variable" );
$insert->execute();
//mycolumn is an integer column which is DEFAULT null
//above query fails. Why?
That is because PHP null is converted into the empty string "" when you create the query string.
$variable = null;
$insert = "insert into mytable set mycolumn = $variable" ;
echo $insert;
Will produce:
insert into mytable set mycolumn =
To fix your query you would need to check if the PHP variable is null and change it to string NULL. (Also now mentioned in the comment of #MarkB.)
if ($variable == null){
$variable = "NULL";
}
This will produce:
"insert into mytable set mycolumn = NULL"
Note that NULL has no " around it because it is now concatenated to the other string.
*(note: insert into tablename set .. is not correct, you either insert data or you update tablename set data.)
(Not an answer to your actual question but maybe to your problem. The "immediate" problem regarding the variable substitution in your double-quoted string has been answered here)
Since you're already using prepare you can simply make it a parametrized statement
$insert = $db->prepare('insert into mytable set mycolumn=?' );
$insert->execute( array($variable) );
and $variable===NULL will result in a NULL value in your MySQL table.
e.g.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
setup($pdo);
$stmt = $pdo->prepare('INSERT INTO soFoo SET mycolumn=?');
$variable = 1; $stmt->execute( array($variable) );
$variable = NULL; $stmt->execute( array($variable) );
$variable = 2; $stmt->execute( array($variable) );
foreach( $pdo->query('SELECT id,mycolumn FROM soFoo', PDO::FETCH_ASSOC) as $row) {
var_export($row);
}
function setup($pdo) {
$pdo->exec('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
mycolumn int,
primary key(id)
)
');
}
prints
array (
'id' => 1,
'mycolumn' => 1,
)array (
'id' => 2,
'mycolumn' => NULL,
)array (
'id' => 3,
'mycolumn' => 2,
)
I want to store a name in the mySQL database. When I click the submit button, PHP should check if the name already exists in the database. If yes then do not submit and print an error message:
Name already exists in database.
<?php
if ( !empty($_POST)) {
$name = $_POST['name'];
$valid = true;
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO people (name) values(?) ";
$q = $pdo->prepare($sql);
$q->execute(array($name));
}
}
?>
<form action="form.php" method="post">
<input name="name" type="text" value="<?php echo !empty($name)?$name:'';?>">
<button type="submit" >Submit</button>
</form>
Try following query to check if a value already exists in mySQL database?
$q = $pdo->prepare("SELECT name FROM people WHERE name = :name LIMIT 1");
$q->bindValue(':name', '$name');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row = $check['name'];
// Do Something If name Already Exist
} else {
// Do Something If name Doesn't Exist
}
you could declare the column as unique and check if the query executes or not, for example:
$query = $pdo->prepare("SELECT name FROM table WHERE name = :name");
$query->bindValue(':name', '$name');
if ($query->execute()){
//no duplicate
}
else {
//error, check the error code.
echo "$stmt->errorCode()";
}
$query-> execute will retun true on success and false other wise, and the database will return an error when the input is a duplicate in a unique coulmn.
I think Making the duplication check in the database is safer.
i have a database contain thousands of row, the user can update his/her row by providing the updated values, i need to update the row only with a non null values provided by the user, if the value provided by user is null the previous data should be remain, for example:
id=1
name = John
address = USA
if the user provide name with null value and address with UK value then the data should be:
id=1
name =John
address = UK
any help with php code example will be highly appreciated.
You should loop through the $_POST superglobal and construct a new array for insertion that does not include the nulls, then use that for your query instead of $_POST directly.
$update = array();
foreach ($_POST as $key => $value) {
if(!is_null($value) && !($value == ''))
$update[$key] = $value;
}
Then use $update for your query parameters, which should not contain any null or blank values.
I use PDO connection
First create a table and insert as follows
create table testing(id int(11), name varchar(100),address varchar(200));
insert into testing values(100,'Null','California');
insert into testing values(200,'sectona','California');
pdo_connect.php
<?php
$db = new PDO (
'mysql:host=localhost;dbname=yourdbname;charset=utf8',
'root', // username
'root' // password
);
?>
<?php
pdo_connect.php
// from form inputs
/*
$id=$_POST["id"];
$name=$_POST["name"];
$address=$_POST["address"];
*/
// direct variable initialisation
/*
$id='100';
$name = 'John';
$name = 'Null';
$address = 'California';
*/
// initialize a null value
$check ='Null';
// check null value for name variable in the first insert statement
$resultn = $db->prepare('SELECT * FROM testing where name = :name');
$resultn->execute(array(
':name' => 'Null'
));
while ($row = $resultn->fetch())
{
$nm = $row['name'];
}
if ($nm == $check)
{
echo '<b><font color=red><b></b>You cannot update with a Null Value</font></b>';
exit();
}
// update if name is not null
$update = $db->prepare('
UPDATE testing SET
name = :name,address = :address
WHERE id= :id');
$update->execute(array(
':name' => 'yourname',
':address' => 'USA',
':id' => '100'
));
echo 'update successful';
?>
finall to update using a non null value from database, then substitute the code below in the query statements
$resultn = $db->prepare('SELECT * FROM testing where name = :name');
$resultn->execute(array(
':name' => 'sectona'
));
I have a table with id which is the primary key and user_id which is a foreign key but the session is based on this in my code.
I have tried EVERYTHING, so I will post my full code.
The form should insert if there is not a user_id with the same session_id in the table. If there is, it should update.
At the moment, when the user has not visited the form before (no user_id in the table) and data is inserted in, the page returns to the location page: but the data is not inserted in the table. if the user changes the data once it is updated it doesn't change either.
This is the table structure:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
`complete` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
The code I have been using (and failing):
$err = array();
$user_id = intval($_SESSION['user_id']);
// otherwise
if (isset($_POST['doThesis'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// check if current user is banned
$the_query = sprintf("SELECT COUNT(*) FROM users WHERE `banned` = '0' AND `id` = '%d'",
$user_id);
$result = mysql_query($the_query, $link);
$user_check = mysql_num_rows($result);
// user is ok
if ($user_check > 0) {
// required field name goes here...
$required_fields = array('thesis_Name','abstract');
// check for empty fields
foreach ($required_fields as $field_name) {
$value = trim($_POST[$field_name]);
if (empty($value)) {
$err[] = "ERROR - The $field_name is a required field" ;
}
} // no errors
if (empty($err)) {
$id = mysql_real_escape_string($_POST['id']);
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
//replace query
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query))
echo "the query failed";
else header ("location:myaccount.php?id=' . $user_id");
}}}
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
class="forms">
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?> </textarea>
</tr>
<tr>
<td>Abstract<span class="required">*</span>
</td>
<td><textarea name="abstract" style="width:500px; height:150px"
type="text" id="abstract" size="600"><?php echo $row_settings['abstract']; ?>
</textarea></td>
</tr>
<?php }
} else { ?>
//shows fields again without echo
I've tried var_dum($query) but nothing appears
PS I know the code isn't perfect but I'm not asking about this right now
I can't see how your replace statement will ever insert the initial row, as the where clause is always going to be false (there won't be a row with that user Id).
I think of you want to use replace you need to replace into thesis (id, userid, etc) without a where clause. If id and userid have a unique constraint and a row for userid exists then it will be updated; if it doesn't exist it will be inserted.
However- if you don't know id- which you won't if you are using auto increment, then I'm not sure you can do this with replace. See http://dev.mysql.com/doc/refman/5.0/en/replace.html
Why don't you check for the existence of a row an then use update or insert?
BTW, is the idea that a user can enter multiple theses into a form, or just one? Your table suggests they can have multiple. If this is what you are trying to achieve then I think you should be storing the id of each thesis in a hidden field as part of the form data. You would then be able to use REPLACE INTO thesis (id, user_id, thesis_name, abstract) VALUES ($id, $user_id, $thesis_name, $abstract) where id is the id of the thesis obtained from each hidden field. If this is not present, i.e. the user has entered a new thesis, then use NULL for id in the insert. This will work using the REPLACE INTO as the id column is auto increment.
Perhaps you mean user_id not id:
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE user_id='{$_SESSION['user_id']}'";
Or if you do mean the id from $_POST['id']
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE id='$id'";
Also instead of REPLACE you should use UPDATE. Im pretty sure its faster because REPLACE basically deletes the row then inserts it again, im pretty sure you need all the fields and values else your insert default values. From the manual:
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT
So you should use:
$query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE id='$id'";
You are doing everything right just one thing you are doing wrong
Your replace query variable is $query and you executing $the_query.
you wrong here:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query)) // this is wrong
echo "the query failed";
replace it with:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($query)) // use $query
echo "the query failed";
I have the following code which is supposed to increment a field value by 1 in a prepared PHP mysql statement:
function db_OP_doVote($pdo, $postid, $votetype)
{
$prepStatement = $pdo->prepare(
"UPDATE content_posts SET `:votetype` = `:votetype` + 1 WHERE `id` = :id"
);
$prepStatement->execute(array(':votetype' => $votetype, ':id' => $postid));
echo "Success";
}
This however, does nothing. No error is thrown back about incorrect SQL syntax and the script runs to completion, but my field does not update at all.
The values for this script are fed through a jQuery post() to this script:
//isset checking here
$postID = (int)$_POST['id'];
$voteType = $_POST['type'];
if ($voteType == "y")
{
$trueType = "v-cool";
}
elseif ($voteType == "m")
{
$trueType = "v-meh";
}
elseif ($voteType == "n")
{
$trueType = "v-shit";
}
else
{
die();
}
$db = db_Connect();
db_OP_doVote($db, $postID, $trueType);
Which also appears to filter the values and send them fine. I can't wrap my head around what the issue could be. The field being incremented is a BIGINT(20).
What am I missing?
EDIT: Solved the issue.
N.B's comment hit the nail on the head - binding the column name causes it to be quoted, which invalidates the query. Thanks!
you can't use binding for the field names.
from the question it seems that your setup is wrong.
you should have another table with votes and vote types as data.
You can't parameterize column names with PDO. What you can do is have hard-coded values (which you basically already have) and construct the SQL string accordingly. I would check this value in the actual function too though, just to be on the safe side:
function db_OP_doVote($pdo, $postid, $votetype)
{
if( !in_array( $votetype, array( 'v-cool', 'v-meh', 'v-shit' /*, etc. */ ), true ) )
{
throw new InvalidArgumentException( 'Unexpected $votetype: ' . $votetype );
// or simply return false perhaps
}
$sql = '
UPDATE content_posts
SET `' . $votetype . '` = `' . $votetype . '` + 1
WHERE `id` = :id
';
$prepStatement = $pdo->prepare( $sql );
$prepStatement->execute(array(':id' => $postid));
echo "Success";
}
However, this strategy suggests your database design could use a little more attention. The way you have it now, is that for every type of vote, you have a column. This is not really efficient and/or flexible database design. What happens if you get asked to add another type of vote?
I'd suggest adding another table, to be more flexible:
CREATE TABLE `content_post_vote` (
`content_post_id` int(11) NOT NULL,
`vote_type` enum('cool','meh','shit') NOT NULL, # using enum() to assure valid vote types
`votes` bigint(20) DEFAULT NULL,
PRIMARY KEY (`content_post_id`,`vote_type`)
)
Then your query would be something like:
$sql = '
INSERT INTO `content_post_vote` (`content_post_id`,`vote_type`,`votes`)
VALUES( :id, :votetype, 1 )
ON DUPLICATE KEY UPDATE `votes` = `votes` + 1
';
What this does is insert a vote if there is no record for a certain primary key (content_post_id,vote_type) yet, and else update the record with a vote if the record already exists.
Then to query the database for how many votes of a particular type a particular content_post has gotten, you do this:
$sql = '
SELECT `votes` # or perhaps more columns
FROM `content_post_vote`
WHERE `content_post_id` = :id AND
`vote_type` = :votetype
';