Pergunta

I'm working with MDB2's prepared statements and am a little confused with the documentation, specifically dealing with MySQL built-in functions like NOW() or CURDATE().

The values passed in $data must be literals. Do not submit SQL functions (for example CURDATE()). SQL functions that should be performed at execution time need to be put in the prepared statement. Similarly, identifiers (i.e. table names and column names) can not be used because the names get validated during the prepare phase.

So the docs say to include these functions in the prepared statement, but I'm not sure how to account for the fieldnames. For instance, if I have a table with five columns:

id lastname firstname gender dateadded

And I want to insert a row with just first, last and dateadded... I might use something like

INSERT INTO mytable (firstname,lastname,dateadded) VALUES('jane','doe',NOW())

If it weren't for the dateadded column I'd use something like:

    $types = array(
        'text', 
        'text' 
    );
    $sth = $mdb2->prepare('
        INSERT INTO 
            mytable 
        VALUES 
            (
                :firstname,
                :lastname
            )', $types);

    $data = array(
        'firstname'     => 'Jane', 
        'lastname'  => 'Doe'
    );
    $affectedRows = $sth->execute($data);

So -- how do I account for the MySQL function as far as listing out the fieldnames? Or do I need to plan on inserting values for every field in the table?

Foi útil?

Solução

I don't understand your problem.
Why not just add NOW() to the prepared statement, as it said?

$sql = 'INSERT INTO mytable ( lastname, firstname, dateadded) 
        VALUES (:firstname, :lastname, NOW())';
$sth = $mdb2->prepare($sql, $types);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top