php - very strange duplicate entry error -


this question has answer here:

i saving data repeatedly code. first time run it doesn't complain. second time says duplicate entry '$id' key 'primary'. echoing $id value , different everytime. table 5min old , guess can't corrupted. approach wrong?

function insertdata($conn,$data){     $id=$data['id'];     $name=$data['name'];     $fp=$data['first_price'];     $sp=$data['second_price'];     echo "$id<br>";     echo "$name<br>";     echo "$fp<br>";     echo "$sp<br>";     $query = 'insert names values("$id", "$name", "$fp", "$fp")';     $result = $conn->query($query);     if (!$result){         echo "nothing saved, sorry $conn->error";     } } 

table structure:

+--------------+--------------+------+-----+---------+-------+ | field        | type         | null | key | default | | +--------------+--------------+------+-----+---------+-------+ | id           | varchar(15)  | no   | pri | null    |       | | name         | varchar(150) | yes  |     | null    |       | | first_price  | varchar(10)  | yes  | mul | null    |       | | second_price | varchar(10)  | yes  | mul | null    |       | +--------------+--------------+------+-----+---------+-------+ 

you're trying insert string literals $id etc table because you're using single quotes.

here's example work:

$query = "insert names values('$id', '$name', '$fp', '$fp')"; 

now speaking shouldn't need insert primary key value, use null , auto increment if table set way. in case it's not (auto_increment not listed under "extra" primary key). consider adding it.

i'll assume ->query() pdo library, avoid sql injection should use parameter binding , adjusted code this:

$query = 'insert names values(?, ?, ?, ?)'; $stmt = $conn->prepare($query); $stmt->execute(array($id, $name, $fp, $fp)); 

... or if you're using mysqli rather pdo:

$query = 'insert names values(?, ?, ?, ?)'; $stmt = $conn->prepare($query); $stmt->bind_param('isdd', $id, $name, $fp, $fp); $stmt->execute(); 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -