Php 插入SQL查询[SQL]后如何返回id
我已经完成了这个SQL查询,我想在插入数据后返回idPhp 插入SQL查询[SQL]后如何返回id,php,sql,Php,Sql,我已经完成了这个SQL查询,我想在插入数据后返回id $query = "INSERT INTO locals (owner,latitude, longitude, json_local) VALUES ('$owner','$latitude','$longitude','$json') RETURNING id"; 我该怎么做 这是我的新功能: function createLocal($owner,$latitude,$longitude,$json) { tr
$query = "INSERT INTO locals (owner,latitude, longitude, json_local) VALUES ('$owner','$latitude','$longitude','$json') RETURNING id";
我该怎么做
这是我的新功能:
function createLocal($owner,$latitude,$longitude,$json) {
try {
$sql = "INSERT INTO locals (owner,latitude, longitude, json_local) VALUES ('$owner','$latitude','$longitude','$json')";
$sth = $this->conn->exec($sql);
$last_id = $this->conn->lastInserId();
echo $last_id;
echo "New record created successfully";
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$this->conn = null;
}
函数createLocal($owner、$latitude、$longitude、$json){
试一试{
$sql=“插入本地值(所有者、纬度、经度、json_本地值)(“$owner”、“纬度”、“经度”、“json”)”;
$sth=$this->conn->exec($sql);
$last_id=$this->conn->lastInserId();
echo$last_id;
echo“新记录创建成功”;
}
捕获(PDO$e){
echo$sql。“
”$e->getMessage();
}
$this->conn=null;
}
}
但是错误是:“页面不工作”。如果您使用PDO,那么您将使用:
$sql=“插入MyGuests(名字、姓氏、电子邮件)
价值观('John','Doe','john@example.com')";
if($conn->query($sql)==TRUE){
$last\u id=$conn->insert\u id;
$LAST\u INSERTED\u ID=$LAST\u ID;
}否则{
echo“Error:”.$sql.“
”$conn->Error;
}
试试这个链接
试试看{
$conn=newpdo(“mysql:host=$servername;dbname=$dbname”、$username、$password);
//将PDO错误模式设置为异常
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_异常);
$sql=“插入MyGuests(名字、姓氏、电子邮件)
价值观('John','Doe','john@example.com')";
//使用exec(),因为不会返回任何结果
$conn->exec($sql);
$last_id=$conn->lastInsertId();
echo“已成功创建新记录。上次插入的ID为:.$Last\u ID;
}
捕获(PDO$e)
{
echo$sql。“
”$e->getMessage();
}
您使用的是哪种DBMS?我使用的是phpMyAdmin,您使用的是mysql/mysqli/pdo等哪个DBMS?如果mysql->$lastID=mysql\u insert\u id()phpMyAdmin
是一个用PHP编写的工具,它不是一个数据库小说明返回
后的回音永远不会执行是的,我使用PHP PDO而不是使用mysqli\uCode>api
// assuming $db is your PDO object
echo $db->lastInsertId();
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
$LAST_INSERTED_ID = $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}