+ 1

How to Insert into db with where clause

Here is the following code I am trying to update the columns and if $_POST is empty assign it into the current db variable value so first I made a while loop to get all tables from db $sql1 = "SELECT * FROM user WHERE username = :usr"; $stmt1 = $conexao_pdo->prepare($sql1); //where clause $stmt1->bindParam(':usr', $username); $stmt1->execute(); while ($linha = $stmt1->fetch(PDO::FETCH_OBJ)) { $col_name = $linha->name; $col_surname = $linha->surname; } After this while loop comes the following code to check if post was empty or not and if empty assign `$name` to the current `$col_name`. Which stores the value of the db column, and if not empty assign the var to `$name` to the `$_POST['name'];` here a example if(empty($_POST['name'])){ $name = $col_name; } else { $name = $_POST['name']; } if(empty($_POST['surname'])){ $surname = $col_surname; } else { $surname = $_POST['surname']; } //add to db $sql = "UPDATE user SET name = :name, surname = :surname WHERE username = :username"; $stmt = $conexao_pdo->prepare($sql); $stmt->bindParam(':username', $username); $stmt->bindParam(':name', $name); $stmt->bindParam(':surname', $surname); $stmt->execute(); but it's not updating the db table and not addind any value on it People told me that update don't add values to the column but if user change the name or surname and save it again? insert will update or add a new user column? Also I would like a alternative how to insert with pdo using where clause.

18th Apr 2017, 8:23 PM
Otávio Barreto
Otávio Barreto - avatar
4 Respuestas
+ 2
i know i can't use where in insert but i need a alternative to use it. the problem with update is that it do not update empty columns
18th Apr 2017, 9:22 PM
Otávio Barreto
Otávio Barreto - avatar
+ 1
use update to change values in the database. use insert to add new values to the database. you can't use where with insert.
18th Apr 2017, 9:05 PM
Mario L.
Mario L. - avatar
+ 1
Insert into ..... Select .... from... where .... This is perfectly valid.
9th Feb 2018, 1:00 AM
Natalia
Natalia - avatar
+ 1
Just to clarify. INSERT as name suggest will create new record, e.g. new user in table. If values of existing record should be changed, e.g. user changes password, then UPDATE is a way to go.
9th Feb 2018, 1:08 AM
Natalia
Natalia - avatar