In my SQL database there're many fields like this:
Field Type:Text Null:Yes Default:NULL
My INSERT looks like this:
INSERT INTO tbl (col,col,col,...) VALUES ('val','val','val',...)
Now, those quotes in my INSERT statement's values are inserting '' (empty string) in to the database when what I really want is nothing (NULL).
So I tried
if (isset($_POST['title'])) {$newTitle = mysql_real_escape_string(trim($_POST['title']));} else {$newTitle = NULL;}
and that just inserts 'NULL' - the string containing the word NULL.
What can I do to be certain my NULL values are inserted properly?
What you have is fine, but you need to combine it with a prepared statement...
// prepare the statement
$stmt = $mysqli->prepare("INSERT INTO tbl (title, x,y,z) values (?,?,?,?)");
$stmt->bind_param($newTitle, $x,$y,$z);
$x = 'hello, world';
// execute prepared statement
$stmt->execute();
If x or newTitle are NULL, they will be NULL in the DB
You can try by adding a NULL without the quotes example below:
INSERT INTO tbl (col,col,col,...) VALUES (NULL,'val','val',...)
Also make sure the column that you want to have a pure null must have the allowed NULL ticked.
Don't specify the field in INSERT INTO or provide a value.
If you have 3 fields, f1 f2 f3
And you
INSERT INTO tbl (f1, f3) VALUES ('something', 'something')
Then f2 will not be inserted and default to null.
I use '0' instead of null. When you use if statements you can run queries like
if($row['f2'] == 0){...
Rather than null :)
Related
I recently found out that you can bind null values in PDO:
$stmt = $db->prepare('SELECT * FROM foo WHERE bar = :bar');
$stmt->execute(array(':bar'=>null));
$foo = $stmt->fetchAll(PDO::FETCH_OBJ);
This would successfully fetch all foo from the database, where the bar column is null.
However, I would now like to do the opposite. I would like to fetch all columns where the bar column is not null.
I am aware I could simply replace bar = :bar with bar IS NOT NULL. However, I would like to avoid that, and instead do it through prepared statements, because I sometimes have to build the query string dynamically and having to do it manually would be a lot of extra work.
Is this possible?
You cannot bind "NOT NULL". You can only bind values. "IS NOT NULL" is not a value, it's completely different query syntax. You will simply have to dynamically build your query, value binding cannot help you with that:
$query = 'SELECT ... WHERE ';
if (/* condition is NOT NULL */) {
$query .= 'foo IS NOT NULL';
$stmt = $db->prepare($query);
} else {
$query .= 'foo = :foo';
$stmt = $db->prepare($query);
$stmt->bindValue('foo', $foo);
}
$stmt->execute();
I am afraid you are wrong with your assumption. Although you can bind NULL values in general, WHERE bar = NULL statement won't return you any rows, neither with raw SQL or PDO. This whole statement will be evaluated to NULL and won't match any row.
Instead, you can use a NULL-safe equal to operator, <=>, to match fields that are either NULL or have some value. But to have values that are not null, you still have to have another query.
I am using mysqli to insert a new row into a table.
$stmt = $con->prepare("INSERT INTO `table` (field1, field2) VALUES (?, ?)");
field 1 and 2 come from a post request.
But if field 2 is not set the entire row is not inserted, how can I change this behaviour so it still inserts field 1.
You can change this behavior by allowing Null value for field 2 in Database. Or you can assign an empty string to the variable if it is NULL.
if(!(isset($_POST['field2']))
{
$field2="";
}
else
{
$field2=$_POST['field2']);
}
first you check field is set or not set
if(!(isset($_POST['field2']))
{
$field2="";
}
else
{
$field2=$_POST['field2']);
}
//and then you execute the query
I am using bindParam to set values for a MySQL insert. The column in question is an INT (11). It has a default of NULL and null is allowed. However, using bindParam it always receives a 0. I have confirmed that my $_POST['value'] is indeed null.
if(isset($_POST['value'])){
$stmt = $db->prepare("INSERT INTO table (column) VALUES (:column)");
$stmt->bindParam(':column',$_POST['value'], PDO::PARAM_INT);
$stmt->execute();
}
It keeps inserting a '0' instead of NULL if the POST value was ''.
You should be matching the complete case (Answer and type) with === (Read More)
Which most likely means that your value is not null like you presume it is.
Ensure it is by checking (pseudo code below):
if(VALUE !=== NULL) {
value = null
}
But you get the idea there? If not just comment :-)
And as aldanux mentioned in his comment, you have to wrap the column in backticks as it is a reserved word:
INSERT INTO table (`column`) VALUES (:column)
I'm struggling with some PHP/MySQL code. I am reading from 1 table, changing some fields then writing to another table, nothing happens if inserting and one of the array values is null when I would like it to insert null in the database (null values are allowed for the field). It looks a bit like this:
$results = mysql_query("select * from mytable");
while ($row = mysql_fetch_assoc($results) {
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', {$row['null_field']});
}
Not every row has a null value and in my query there are more fields and 2 columns which may or may not be null
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) "" and null and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql extension. Use mysqli and it's prepared statements instead. You'll save yourself a world of pain.
I think you need quotes around your {$row['null_field']}, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',) which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.
For example:
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");
Sometimes I need to insert into the table some null values, or update them setting the value to NULL.
I've read somewhere in the Postgres documentation that this can't be done, but can be tricked with the default value:
pg_query("INSERT INTO my_table (col_a, col_b) VALUES ('whatever', default)
I know that in this example I'll have the same result with:
pg_query("INSERT INTO my_table (col_a) VALUES ('whatever')
But the problem comes with prepared statements:
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, default)");
pg_exec($pgconn, 'insert_null_val', array('whatever'));
//this works, but
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_exec($pgconn, 'insert_null_val', array('whatever', 'NULL'));
//insert into the table the string 'NULL'.
//instead using array('whatever', '') it assume the col_b as empty value, not NULL.
The same problem applies to update statements.
I think there is a solution, because pgmyadmin can do that (or it seems like it can).
If you are wondering why I need to play with null values in my tables, let me throw an example (maybe there is a way better then the null value?):
Assume I have the users table with an email column, which can be empty, but has a unique index. 2 empty emails are equal and violate the unique constraint, while 2 NULL values are not equal and can coexist.
Use the php's literal NULL as a parameter:
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_query($pgconn, 'insert_null_val', array('whatever', NULL));