PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
create table operators ( id_operator int primary key auto_increment, name_operator varchar(64) not null, unique key (name_operator) ); INSERT INTO operators (name_operator) VALUES ('Ернат'); INSERT INTO operators (name_operator) VALUES (null); INSERT IGNORE INTO operators (name_operator) VALUES (null); SELECT * FROM operators;
Copy Clear
Copy Format Clear
<?php $operator = "Borat"; try { $pdo->beginTransaction(); // Check if operator exists $stmt = $pdo->prepare( "SELECT id_operator FROM operators WHERE name_operator =:name_operator;" ); $stmt->execute(["name_operator" => $operator]); $result = $stmt->fetch(PDO::FETCH_ASSOC); var_dump($result); $id_operator = $result["id_operator"]; echo "id_operator: $id_operator"; // If not exists store new record if (!$id_operator) { $sth = $pdo->prepare( "INSERT INTO operators (name_operator) VALUES (:name_operator);" ); $sth->execute(["name_operator" => $operator]); $id_operator = $pdo->lastInsertId(); $pdo->commit(); } } catch (PDOExecption $e) { $dbh->rollback(); print "Error!: " . $e->getMessage() . "</br>"; } echo "id_operator: $id_operator";
Show:  
Copy Clear