How to handle nulls in this PHP/mysql insert statement - php

I sometimes have arrays with null or empty values. In MySql they are set up to be non-nullable, but they have default values assigned. Why then, does MySql give me an error, e.g. Column user_type can not be null. (I'm not running in strict mode).
I realise that I could use the keyword DEFAULT in place of some values when preparing the query, but I don't really want to do that. I would like to be able to write my SQL statements verbatim, rather than put them together with foreach loops, etc. For example, I would like to use "INSERT INTO users (user_type, first_name, last_name, password) VALUES (:user_type, :first_name, :last_name, :password)";
As far as I recollect, this was working fine (i.e. substituting in the correct defaults) until I moved from using ? query markers to named parameters...
Thanks...

I would create a function that accepts the values as parameters. It would have the default values in an associative array. If the value for any of the parameters is null, it would replace it with the default.
eg
function setUpQuery($user_type_in, $first_name_in, $last_name_in, $password_in){
$default_values('user_type' => 'Admin', 'first_name' => 'John', 'last_name' => 'Doe', 'password' => 'XXX');
$user_type = ($user_type_in == NULL)? $default_values['user_type']:$user_type_in;
.....
return "INSERT INTO users (user_type, first_name, last_name, password) VALUES ('$user_type', '$first_name', '$last_name', '$password');"
}
Good Point. How about the following:
INSERT INTO users(user_type, first_name, last_name,password) values
(ifnull('$user_type',default(user_type)), ifnull('$first_name', default(first_name)),
ifnull('$last_name',default(last_name)), ifnull('$password', default(password));

Related

PHP/MySQL Using Variables and INSERT INTO syntax

I am trying to pass variable values to a MySQL database table. I am using a PDO to get access to the database, and am able to echo the variable values that I want to insert to my browser. The only thing I can think of is that my syntax is wrong. I am clearly a novice at using PHP/MySQL.
I am not getting any errors. The info isn't going into my table. What am I doing wrong?
$sql = "INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES ('$version', $points, $passing_percent, $gained_score, '$username', '$email', '$quiz_title', CURDATE() )";
Query to create table:
MySQL CREATE TABLE Query:
CREATE TABLE testquiz (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
version TEXT,
points INT,
passing_percent DOUBLE,
gained_score DOUBLE,
username TEXT,
email TEXT,
quiz_title TEXT,
date DATE NOT NULL
) DEFAULTCHARACTER SET utf8 ENGINE=InnoDB
When using PDO, the generally accepted practice is to use prepared statements for SQL, which essentially are a method used to sanitize your string input.
If your database connection object is $dbo then it would usually go like this.
Create a prepared statement by calling the prepare method on your database connection object:
$sql = $dbo->prepare("INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES (:version, :points, :passing_percent, :gained_score, :username, :email, :quiz_title, CURDATE())");
As you can see, instead of passing in the variables I want for the values directly, I've created placeholders. Then, call the execute method on the $sql obect and pass the values in for the placeholders as key-value pairs in an array.
$sql->execute(array(":version" => $version, ":points" => $points, ":passing_percent" => $passing_percent, ":gained_score" => $gained_score, ":username" => $username, ":email" => $email, ":quiz_title" => $quiz_title));
This code passes in the values you define instead of the placeholders, and it properly escapes and sanitizes the variables you pass in for security, while executing your INSERT statement.
http://us1.php.net/pdo.prepared-statements
Change the insert statement to the below format and try.
$sql = "INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES ('".$version."', '".$points."', '".$passing_percent."', '".$gained_score."', '".$username."', '".$email."', '".$quiz_title."', CURDATE())";

Error in executing insertion query

Isn't this query correct?
$insert = INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10');
I got following error, please help I am a beginner.
Parse error: syntax error, unexpected 'INTO' (T_STRING) in
C:\xampp\htdocs\google.php on line 9
$insert = "INSERT INTO `geninfo` (`S.N`, `Name`, `Address`, `DOB`) VALUES ('Suresh','Ratnanagar','Missing address here','1989/04/10');";
Note that I have also corrected your MySQL query. S.N refers to the column named N on the table named S, which I'm pretty certain is not what you wanted.
Also I just realised you have four columns, but only three values. Fixed that too.
You have no quotes, it should be like this:
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10')";
upd
It seems you are storing date of birth as a string, not as a timestamp (or similar) which is not a good idea
You need to give a (NULL or '') for the S.N field and quotes should be given before and after each and every value.
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES
('', 'Suresh','Ratnanagar','1989/04/10')";
Moreover the field name S.N could create problems. Let me know if this works.
$insert = "INSERT INTO geninfo (S.N, Name, Address, DOB) VALUES ('Suresh','Ratnanagar','1989/04/10')";

Basic insert into SQL

I know this is really simple i haven't touched PHP and SQL in a few years.
This works
$mysqli->query("INSERT INTO sonyCES2013.registration (id,
firstName, lastName, eMail, telephone, outlet, comfirm,
preferTime, date) VALUES (NULL,Cat, 'Catherine',
'Cat#gmail.com', '123-456-4561', 'Some Text', 'Yes', '4:00pm'
,'1/09/14')");
this doesn't work
$mysqli->query("INSERT INTO sonyCES2013.registration (id,
firstName, lastName, eMail, telephone, outlet, comfirm,
preferTime, date) VALUES
(NULL,{$fName},{$lName},{$eMail},{$telephone},{$outlet},{$comfirmation},{
$preferTime},{$day})");
help and yes i did check that the variables aren't empty and i did try without the `` between each {}
You need to add ' ' to the variables to make the interpeter able to understand what you are trying to do ( in this case passing some php variable as parameters)
Use this and see if it works:
$mysqli->query("INSERT INTO sonyCES2013.registration (id, firstName, lastName,
eMail, telephone, outlet, comfirm, preferTime, date) VALUES
(NULL,'$fName','$lName','$eMail','$telephone','$outlet',
'$comfirmation','$preferTime','$day')");
It won't work that way because the resulting SQL looks something like this:
$mysqli->query("INSERT INTO sonyCES2013.registration (id, firstName, lastName, eMail, telephone, outlet, comfirm, preferTime, date) VALUES (NULL,Cat, Catherine, Cat#gmail.com, 123-456-4561, Some Text, Yes, 4:00pm ,1/09/14)");
Note the lack of single quotes around the strings, which make the SQL invalid.

Submitting data to two mysql tables using PDO

Is it possible to submit data to two tables with the same query?
My existing code looks like this:
private function adduser() {
if (!empty($this->error)) return false;
$params = array(
':user_level' => parent::getOption('default-level'),
':name' => $this->name,
':email' => $this->email,
':username' => $this->username,
':password' => parent::hashPassword($this->password)
);
parent::query("INSERT INTO `login_users` (`user_level`, `name`, `email`, `username`, `password`)
VALUES (:user_level, :name, :email, :username, :password);", $params);
I didn't write this code so it is a bit confusing to me as I don't usually use PDO. What I would like to do in addition to this is add two values to my 'url_alias' table, the first is the UID (which is auto incremented from the first query) and the second is another variable value.
All of the examples I have found while searching dont seem to work for me because of the way this existing code looks.
Can anyone give me a hand?
It doesn't matter what db driver your are using (PDO, Mysqli, etc.) you question is purely about mysql capabilities. Mysql may update and delete rows from multiple tables in a single query but not insert. I.e. INSERT table_1, table_2 ... is not allowed.
You have to run one query for each table you want to insert data.

postgres enum insertion using pg_query

I have a table with one field of enum type. I execute the following query using pg_query
INSERT INTO users (email, facebook_id, first_name, middle_name, last_name, birth_date, password, gender, school_id, timezone, email_verified, role_id) VALUES ('robert#1599309412.com', NULL, 'Robert', '', 'George', '1984-05-20', 'Some password', 'MALE', 1, '0.0', false, 1 );
pg_query($connection, 'INSERT INTO users (email, facebook_id, first_name, middle_name, last_name, birth_date, password, gender, school_id, timezone, email_verified, role_id) VALUES (\'robert#2084537193.com\', NULL, \'Robert\', \'\', \'George\', \'1984-05-20\', \'Some password\', \'MALE\', 1, \'0.0\', false, 1 )')
but i get error as below.
PHP Warning: pg_query(): Query failed: ERROR: invalid input value for enum sex: "MALE"
LINE 1: ...rt', '', 'George', '1984-05-20', 'Some password', 'MALE', 1,...
Direct execution of query in postgres client don't give this error.What is solution for this?
Please make sure cases match. Postgres is not too strict about it (consider the table names), but it might worth a check.
Having a gender attribute enum'd is unnecessary overhead in my opinion, you're better off having a male int column with 1, 0 values and maybe null for unknown/not specified. With values greater than 1 it's still future-proof just in case a new gender appears. :)
If you really are attached to enums, you might want to consider using PDO, because it makes binding values a lot easier and a lot more secure.

Categories