您好,我有一个名为tblcontactlist的表,有5列(contactID,contactName,contactEmail,contactNumber,hashed_id),这是我的工作查询
$query = "INSERT INTO tblcontactlist (contactName, contactEmail, contactNumber) VALUES (:cname, :cea, :cnum)";
$stmt = $dbc->prepare($query);
$stmt->bindParam(':cname', $contactName);
$stmt->bindParam(':cea', $emailAdd);
$stmt->bindParam(':cnum', $contactNumber);
$stmt->execute();
$last_id = $dbc->lastInsertId('contactID');
$hashed_id = sha1($last_id);
$query2 = "UPDATE tblcontactlist SET hashed_id=:hid WHERE contactID=:cid";
$stmt2 = $dbc->prepare($query2);
$stmt2->bindParam(':hid', $hashed_id);
$stmt2->bindParam(':cid', $last_id);
$stmt2->execute();
这基本上做的是插入一条新记录,然后在hashed_id列上更新带有散列id的最新插入记录。有没有正确的方法呢?我是指更短的代码或更好的代码。谢谢!
答案 0 :(得分:1)
lastInsertId
预先假定您事先有INSERT,而您没有。在这种情况下,lastInsertId
是最大的contactID。因此,我将执行查询以获取并散列最大contactID,然后执行一次插入查询(并且不进行更新)。
//fetch Max contactID
$res=$dbc->prepare("SELECT MAX(contactID) FROM tblcontactlist");
$res->execute();
$fetchMax=$res->fetch(PDO::FETCH_NUM);
$last_id=$fetchMax[0];
//hash the max contactID
$hashed_id = sha1($last_id);
//for reusability you can create a function with the above code.
现在执行插入查询:
$query = "INSERT INTO tblcontactlist (contactName, contactEmail, contactNumber, hashed_id) VALUES (:cname, :cea, :cnum, :hid)";
$stmt = $dbc->prepare($query);
$stmt->bindParam(':cname', $contactName);
$stmt->bindParam(':cea', $emailAdd);
$stmt->bindParam(':cnum', $contactNumber);
$stmt->bindParam(':hid', $hashed_id);
$stmt->execute();
这对你有好处吗?