How To Use SQL PRIMARY KEY STATEMENT With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 18-09-2020

SQL PRIMARY KEY uniquely identify every tuple or a record in a table. SQL PRIMARY KEY only assigned one column to auto increment the value on every insertion. SQL PRIMARY KEY should have UNIQUE values on each row in table. SQL PRIMARY KEY can not contain NULL values.

SQL PRIMARY KEY

SQL PRIMARY KEY.

CREATE TABLE Employee(
EmployeeID   INT              NOT NULL,
FirstName  VARCHAR (20)     NOT NULL,
LastName   VARCHAR (20)     NOT NULL,
AGE  INT              NOT NULL,
ADDRESS   VARCHAR (20)     NOT NULL,
SALARY   DECIMAL (18, 2),
PRIMARY KEY (EmployeeID));//primary key 

 

To Create a PRIMARY KEY on the "EmployeeID " column when the table is already created.

ALTER TABLE Employee ADD PRIMARY KEY (EmployeeID );​​

 

To Delete  or  Alert  the PRIMARY KEY on the "EmployeeID " column when the table is already created.

ALTER TABLE Employee DROP PRIMARY KEY;



2.Complete code of SQL PRIMARY KEY  in PHP script.
<!DOCTYPE html>
<html lang="en">
<head>
    <title>How to use SQL PRIMARY KEY </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>SQL PRIMARY KEY</h1>
    </div>
    <br>
    <div class="well">
        <?php
        $connect = mysqli_connect("localhost", "root", "", "management");
        if($connect === false){
            die("ERROR: Could not connect. " . mysqli_connect_error());
        }
        $sql_1 = "CREATE TABLE Employee(
                        EmployeeID   INT              NOT NULL,
                        FirstName  VARCHAR (20)     NOT NULL,
                        LastName   VARCHAR (20)     NOT NULL,
                        AGE  INT              NOT NULL,
                        ADDRESS   VARCHAR (20)     NOT NULL,
                        SALARY   DECIMAL (18, 2),
                        PRIMARY KEY (EmployeeID))";

        if(mysqli_query($connect, $sql_1)){
            echo "<br><h1 class='text-success'>Employee table created successfully.</h1>";
        } else{
            echo "ERROR: Could not able to execute $sql_1. " . mysqli_error($connect);
        }
        mysqli_close($connect);
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post