PHPnoob
PHPnoob

Reputation: 293

insert/update and also avoiding sql injection

I want to check if somethign exist in the database before I update/insert. This is a two question in one but similar.

This is how I do it.

$p->main .= '<td><input type="text" name="value"  id="value"  size="12" maxlength="50" />';

    $statement = $conn->prepare("SELECT year, month, name table_test WHERE MLOV_year= :Year 
                 AND month= month AND name= :name");

                $bind = array(
                                'year' => $year,
                                'month'   = > $month,
                'name' = > $name
                );


                $statement->tyu_exec_sql_bind($conn,$statement, $bind );

                 if ( false === $statement->fetch()) {
                               // I will run an insert statement here.
                }



    $p->main .= '</td>';
    $p->main .= '</tr>';

Question This is my first time trying it this way and I was wondering if that is right? also if that is security?

Upvotes: 0

Views: 171

Answers (2)

SQB
SQB

Reputation: 4078

Depending on the database, you might be able to use MERGE, which does exactly that, inserting a record if it doesn't exist and updating it if it does, atomically.

This is preferrable to any check you do yourself, since that makes it a two step process. In theory, someone else could insert the record between your check and your insert, making your insert fail.


Use prepared statements to prevent SQL injection. You did that in your first bit of code, why not in your second?

And a tip, don't call your variable 'delete' when it contains an update statement, that confuses the next person to read this.

Upvotes: 1

sanjeet sharma
sanjeet sharma

Reputation: 23

First you need to check that the value exists in database, which means you need to query for it, and then take the decision of update or delete.

You could also set a unique key constraint in a table which would prevent inserting duplicate values.

Upvotes: 0

Related Questions