Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdo prepared statement insert DEFAULT when the variable in BindParam is null

I have this problem: I'm using PDO prepared statement.... I want to BIND a variable BUT if the variable is NULL it have to INSERT in MYSQL the DEFAULT VALUE of the field...

I'm trying with IFNULL(:User_Login__Is_Active, DEFAULT), And I tried also: COALESCE(:User_Login__Is_Active, DEFAULT), Same error: PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;

How can you do that?

Look this example:

        $stmt = $this->pdo->prepare('INSERT INTO user_login
                                        ( User_Login__ID,
                                          User_Login__Is_Active,
                                          User_Login__Created_Date )
                                   VALUES ( 
                                          :User_Login__ID,
                                          IFNULL(:User_Login__Is_Active, DEFAULT),
                                          :User_Login__Created_Date )');


    $stmt->bindParam(':User_Login__ID', $this->User_Login__ID, PDO::PARAM_INT);
    $stmt->bindParam(':User_Login__Is_Active', $this->User_Login__Is_Active, PDO::PARAM_STR, 100);
    $stmt->bindParam(':User_Login__Created_Date', $this->User_Login__Created_Date, PDO::PARAM_STR, 100);


    $this->User_Login__Is_Active = null;
like image 736
Samuele Avatar asked Feb 27 '11 00:02

Samuele


People also ask

What is the use of bindParam () in statement class?

The bindParam() function binds a parameter to a named or question mark placeholder in an SQL statement. The bindParam () function is used to pass variable not value.

How does PDO prepared statements work?

In layman's terms, PDO prepared statements work like this: Prepare an SQL query with empty values as placeholders with either a question mark or a variable name with a colon preceding it for each value. Bind values or variables to the placeholders. Execute query simultaneously.

What is PDO :: Param_str in PHP?

PDO::PARAM_STR (int) Represents the SQL CHAR, VARCHAR, or other string data type. PDO::PARAM_STR_NATL (int) Flag to denote a string uses the national character set.

What type of object is returned by PDO :: prepare ()?

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object.


1 Answers

The keyword DEFAULT can't be used inside an expression, it can only replace the entire expression.

However, the function DEFAULT() can be used anywhere.

So replace DEFAULT in your example with DEFAULT(User_Login__Is_Active).

like image 154
aaz Avatar answered Oct 18 '22 12:10

aaz