如何根据另一列的值在列中分配默认值


How to assign a default value in a column based on another column's value?

我想在我的数据库列有一个默认值,这是相同的每一行,但最后的字符应该是行的主键。

这是可能实现使用PHP/MySQL吗?

e。g(我希望Link列具有默认值)

+----+----------------------------+
| ID |            Link            |
+----+----------------------------+
|  1 | edit_item.php?id=1         |
|  2 | edit_item.php?id=2         |
|  3 | edit_item.php?id=3         |
+----+----------------------------+

非常感谢您的帮助!

在插入时,您需要插入并更新您的记录。

首先插入您的记录,然后获得最后插入的id,然后更新记录例如:

<?php 
$sql = "INSERT INTO TableName(Link) VALUES ('edit_item.php')";
if (!mysqli_query($con,$sql)) { 
    die('Error: ' . mysqli_error($con));
} else {
    $id = mysql_insert_id();
    mysqli_query($con,"UPDATE TableName SET Link='edit_item.php?id=".$id."' WHERE id=$id); 
}

您不能动态设置默认值,但是您绝对可以使用printf()的某种替换,例如:

模式:

CREATE TABLE links (
    id   INT  PRIMARY KEY AUTO_INCREMENT,
    link TEXT DEFAULT "edit_item.php?id=%d"
);
然后在PHP中,使用printf()

将%d替换为ID
<?php
// Let's assume it's an array with this format:
// ['id' => 1, 'link' => 'edit_item.php?id=%d']
$row = yourSelectCommandThatReturnsAnObject();
// In this case, $row['id'] will replace the %d.
$link = printf($row['link'], $row['id']);

您可以查看PHP文档中的printf()获取更多信息