how to put values for columns for whome the NULL? - php

I am confused by using this query.
INSERT INTO `book`(`book_id`, `book_title`, `isbn`, `ean`, `book_image_url`,
`book_author`, `book_description`, `category_id`, `book_type`, `addedBy`,
`addedWhen`, `modifyBy`, `modifyWhen`)
VALUES (NULL,'abc',123,,'http://www.example.com','xyz',,'1',,'admin',
2008-06-08,NULL,NULL)
I have allowed NULL for description, ean and for the book_type column and also set NULL as the default value but this query is not working. But if I fill them i surprised that the query is executed.
What's going on?

INSERT INTO `book`(`book_id`, `book_title`, `isbn`, `ean`, `book_image_url`,
`book_author`, `book_description`, `category_id`, `book_type`, `addedBy`,
`addedWhen`, `modifyBy`, `modifyWhen`)
VALUES (NULL,'abc',123,'','http://www.example.com','xyz','','1','','admin',
2008-06-08,NULL,NULL)

You should not put empty values like for the "ean" column in your example :
NULL,'abc',123,,'http://www.example.com'
The part between 123 and the URL should not be empty, but replaced with a NULL or an empty string, depending on what you want. Otherwise, it's a SQL syntax error.

For some fields you are not passing any values
INSERT INTO `book`(`book_id`, `book_title`, `isbn`, `ean`, `book_image_url`,
`book_author`, `book_description`, `category_id`, `book_type`, `addedBy`,
`addedWhen`, `modifyBy`, `modifyWhen`)
VALUES (NULL,'abc',123,'','http://www.example.com','xyz','','1','','admin',
2008-06-08,NULL,NULL)

Related

PHP issue insert with auto_increment

I'm pretty new to PHP code.
I have a tabel that I want to insert in to but for some reason the insert statement does not work. The tabel has an ScanID column that AUTO_INCREMENT 's. I've tried a few things like just leaving the ScanID out of the statement but that didn't work either ( I also tried swapping the NULL with ' '). I was able to insert in to other tables where there isn't an ID that AUTO_INCREMENT's so my pretty sure that my connection works.
<?php
$xml=simplexml_load_file("someFile.xml");
$con =new PDO("mysql:host=localhost;dbname=testDB",'root','');
$ScanType="someType";
$start_date=$xml ->start_datetime;
$end_date=$xml ->finish_datetime;
$TargetTargetID="1";
$stmt=$con->prepare('insert into
Scan(ScanID, ScanType, start_date, end_date, TargetTargetID) values
(:ScanID, :ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanID',NULL);
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();
$ScanID=$con->lastInsertId();
echo $ScanID;
?>
EDIT: this worked for me
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();
No need to pass auto increment column value in insert query just remove from columns and values to
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');
Remove from bind values
$stmt->bindValue('ScanID',NULL);

need assistance with solving this database error

i am trying to create a user account and i got this error message.
A Database Error Occurred
Error Number: 1048
Column 'group_id' cannot be null
INSERT INTO `bitauth_users` (`username`, `password`, `active`, `activation_code`, `group_id`, `password_last_set`) VALUES ('FAAN', '0884e4e5928d672b182a37b885b5e6ec', 1, '7c6ef5bd05fd2d189df64da76e76017ecec7d233', NULL, '2016-06-23 04:07:08')
Filename: C:\inetpub\vhosts\vidoplus.com\httpdocs\system\database\DB_driver.php
Line Number: 330
Please what do i need to do to fix this. i am new at this. Thanks
As group_id itself suggest that it's a primary key of some table (I think its will be groups table) and treated as a foreign-key in your bitauth_users table.
So you can not pass NULL to it.
You have to pass some value which is related to the table where it is primary key.
Note:- please provide some real value (don't provide empty or 0 etc because at the time of fetching record you will face problem)
Form your error message, you need to give value of group_id (not null value). You can try this:
INSERT INTO bitauth_users (username, password, active, activation_code, group_id, password_last_set) VALUES ('FAAN', '0884e4e5928d672b182a37b885b5e6ec', 1, '7c6ef5bd05fd2d189df64da76e76017ecec7d233', 1, '2016-06-23 04:07:08');
Hope it will help ;)
group_id is not null field ... so if you want to store NULL value then make it nullable other wise you can store 0 or '' blank value.
.
INSERT INTO `bitauth_users` (`username`, `password`, `active`, `activation_code`, `group_id`, `password_last_set`) VALUES ('FAAN', '0884e4e5928d672b182a37b885b5e6ec', 1, '7c6ef5bd05fd2d189df64da76e76017ecec7d233', '', '2016-06-23 04:07:08')
In your sql,tha VALUES part,the group_id is setted to NULL.The error msg is "Column 'group_id' cannot be null".So you can convert NULL to zero.
The sql can be like this:
INSERT INTO `bitauth_users`
(`username`,`password`, `active`, `activation_code`, `group_id`,`password_last_set`)
VALUES
('FAAN', '0884e4e5928d672b182a37b885b5e6ec', 1, '7c6ef5bd05fd2d189df64da76e76017ecec7d233',
0, '2016-06-23 04:07:08')
Hope this can help you!

Setting variable's database value to NULL instead of empty string

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 :)

PHP/MySQL Insert null values

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).")");

Using NULL value in INSERT or UPDATE with prepared statements

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));

Categories