0

Question: Do the number of columns in a mysqli db table, excluding an auto-increment column, have to match exactly the number of values in the INSERT query for a prepared statement?

I have got a mysql table with three columns.

CREATE TABLE IF NOT EXISTS `secure_user_data` (
`user_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(32) NOT NULL,
`last_name` varchar(32) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

An INSERT query using a prepared statement with the two values, first_name and last_name, works well.

/* This works fine with the above table. */
if ($stmt = $mysqli->prepare("INSERT INTO secure_user_data (first_name, last_name) VALUES (?,?)")) {
$stmt->bind_param('ss', $first_name, $last_name);
}
$stmt->execute();

However, if I create a new column, user_name, in the table the above INSERT query won't insert a record.

CREATE TABLE IF NOT EXISTS `secure_user_data` (
`user_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(32) NOT NULL,
`last_name` varchar(32) NOT NULL,
`user_name` varchar(32) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

If I add the 3rd value, user_name, to the INSERT query it will insert a record into the table with the immediately above.

/* This works with auto-increment column plus the three more columns. */
if ($stmt = $mysqli->prepare("INSERT INTO secure_user_data (first_name, last_name, user_name) VALUES (?,?,?)")) {
$stmt->bind_param('sss', $first_name, $last_name $user_name);
}
$stmt->execute();

My table might eventually end up with twenty or thirty columns. I am trying to figure out how I can start with the minimal number of INSERT query values and then let the user fill in the rest as he can find the time.

Thank you in advance.

Harvey
  • 65
  • 6
  • 1
    No, but you did define `user_name` as NOT NULL, then if you didn't give the user_name, it just won't insert. – Shiji.J Oct 24 '16 at 01:43
  • Try executing the query on your DB directly and you should have the same behavior. There are no `mysqli` databases, that is just a driver to connect to a mysql database. – chris85 Oct 24 '16 at 02:31
  • @Fred -ii- What duplicate? http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1? I've looked at several questions/answers and don't see one that addresses the issue of table columns and insert values. – Harvey Oct 24 '16 at 13:07
  • @Shiji.Jiang You mean use NULL values for varchar and text column types? NOT NULL worked for non-prepared insert statements for those column types. – Harvey Oct 24 '16 at 13:13

0 Answers0