Note that there are some explanatory texts on larger screens.

plurals
  1. POPrevent duplicate records to a table using PHP
    text
    copied!<p>I want to prevent duplicate values into a database table from a form using PHP.</p> <p>I have created the following:</p> <p>A database with a table named <strong>clients</strong>:</p> <pre><code>CREATE TABLE clients( firstName varchar(20), lastName varchar(20), primary key(firstName, lastName)); </code></pre> <p>A simple form named <strong>form.html</strong></p> <pre><code>&lt;h2&gt;Enter your First and Last Name&lt;/h2&gt; &lt;form action="frm_script.php" method="post"&gt; &lt;p&gt;&lt;strong&gt;First Name:&lt;/strong&gt;&lt;br /&gt; &lt;input type="text" name="firstName" /&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Last Name:&lt;/strong&gt;&lt;br /&gt; &lt;input type="text" name="lastName"/&gt;&lt;/p&gt; &lt;input type="submit" name="submit" value="Add Customer" /&gt; &lt;/form&gt; </code></pre> <p>A form processing script named <strong>frm_script.php</strong></p> <pre><code>&lt;?php if(isset($_POST['submit'])) { //get the name and comment entered by user $firstName = $_POST['firstName']; $lastName = $_POST['lastName']; //connect to the database $dbc = mysqli_connect('host', 'username', 'password', 'dbname') or die('Error connecting to MySQL server'); //insert results from the form input $query = "INSERT IGNORE INTO clients(firstName, lastName) VALUES('$firstName', '$lastName')"; $result = mysqli_query($dbc, $query) or die('Error querying database.'); mysqli_close($dbc); } echo "Customer Added"; ?&gt; </code></pre> <p>So far with my <strong>frm_script.php</strong> file the above works and for a unique record displays customer added. However, for a duplicate record it throws "Error Querying Database".</p> <p>How can I update the <strong>frm_script.php</strong> script for the following?</p> <p>If a duplicate row is found on entering a First / Last name combination it should display the message "Client already listed" along with that record.</p> <p>If no duplicate row is found on entering a First / Last name combination on the form it should insert the entry to the database and display the message "customer added"</p> <p>I have read that a SELECT should be run first then an INSERT but I am not sure how to implement this into my existing code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload