在php&中插入后如何获得返回id pgSQL的

时间:2016-04-15 07:00:01

标签: php postgresql

我创建了两个表:employee和employeedetails。

employee表格中:id (pkey) userid,pswd,lastlogindate

employeedetails表格中:id(pkey), sno(forienkey), name,age,designation,registration,salary

我希望员工身份的sno(fkey)中的员工ID,但我手动插入,我想自动插入。

<?php
$host        = "host=127.0.0.1";
$port        = "port=5432";
$dbname      = "dbname=books";
$credentials = "user=postgres password=postgres";

$db = pg_connect( "$host $port $dbname $credentials"  );
if(!$db){
    echo "Error : Unable to open database\n";
} else {
    echo "Opened database successfully\n";
}

if(isset($_POST['register']))
{
    $userid=$_POST['userid'];
    $pswd=$_POST['pswd'];
    $name=$_POST['name'];
    $age=$_POST['age'];
    $designation=$_POST['designation'];
    $salary=$_POST['salary'];
    $registartiondate=date("Y-m-d",time());            
    $sql="insert into employedetails(sno,name,designation,registartiondate,age,salary) values('".$name."','".$designation."','".$registartiondate."','".$age."','".$salary."')";
    $query= " insert into employe (userid,pswd) values ('".$userid."','".$pswd."')";

    $exe=pg_query($db,$query);

    $q = pg_query($db,$sql);

    if($q)
    {
        echo "INSERTED SUCCESSFULLY";
    }
    else
    {
        echo pg_last_error($db);
    }
}
?>
<html>
<form method="post">
userid<input type="text" name="userid"/>
<br>
pswd<input type="text" name="pswd" /><br/>
name<input type="text" name="name" /><br/>
age<input type="text" name="age" /><br/>
designation<input type="text" name="designation" /><br/>
salary<input type="text" name="salary" /><br/>

<input type="submit" value="Submit" name="register"/>
</form>
</html>

1 个答案:

答案 0 :(得分:1)

Postgresql支持RETURNING子句,它可以将一组更新,插入甚至删除,就像在SELECT语句中一样:

INSERT INTO employee (name, password)
VALUES ($1::text, $2::text) 
RETURNING employee_id, name, '****' as password
;

employee_id | name | password
    1       | john | ****
(1 row)

它将返回插入行的提问字段。