Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

php - How can I create a value from two other values in the same table in my SQL?

I have a table named "orders" in an SQL database:

id  date   name  orderID
========================
1   1502   John    ?
2   1502   Jane    ?

The "id" is set to AUTO_INCREMENT and the "date" is created when I insert data via my php form:

if ( !empty($_POST)) {
        $name = $_POST['name'];
        $valid = true;


        if ($valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO orders (name,date) values(?,CURDATE())";
            $q = $pdo->prepare($sql);
            $q->execute(array($name));
            Database::disconnect();
        }
}

I wish that the value for "orderID" is created automatically from the values "id" and "date":

id  date   name  orderID
========================
1   1502   John    15021
2   1502   Jane    15022
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Due to the fact, that the id is an AUTO_INCREMENT you have no hand on this value. But it's quite simple. Add a AFTER INSERT trigger to the table and let it update the orderID column afterwards.

Here a quick example of a AFTER UPDATE trigger.

CREATE TRIGGER yourTrigger
AFTER INSERT
   ON yourTable FOR EACH ROW

BEGIN
    UPDATE yourTable
    SET orderid = CAST(date as char(4)) + CAST(id as char(1))
    WHERE ID = NEW.id

END; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...