Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You should create a trigger, something like that:</p> <pre><code>CREATE TRIGGER trigger_name BEFORE INSERT ON table FOR EACH ROW SET slug = CONCAT(NEW.title, "-", NEW.id); </code></pre> <p>I'm not sure you'll be able to access the ID column before its written on the database (unless, of course, you generate your IDs yourself, not using the autoincrement).</p> <p>If you're using your DB's autoincrement (and you should be), try creating a trigger AFTER INSERT, and updating your row in your trigger. That way, even though you're updating it AFTER your insert, it'll still run before you can run any other queries (like a SELECT).</p> <p><a href="http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html" rel="nofollow">HERE</a> is the documentation on triggers.</p> <hr> <p>I was wrong. Apparently, you can't update a table you're inserting into (using an AFTER INSERT triger), it'll throw an exception. So, two possible ways to do it using SQL alone:</p> <p>The ugly way:</p> <pre><code>DELIMITER $$ CREATE TRIGGER `create_slug` BEFORE INSERT ON `events` FOR EACH ROW BEGIN SET new.id = (SELECT MAX(id) FROM events) + 1; SET new.slug = CONCAT(new.menu_name, "-", new.id); END$$ DELIMITER ; </code></pre> <p>It overrides your database's AUTOINCREMENT. Really, don't do that.</p> <p>Or, you can create a procedure:</p> <pre><code>DELIMITER $$ CREATE PROCEDURE insert_event(MenuName VARCHAR(30), Content TEXT, PhotoName TEXT) BEGIN INSERT INTO events (menu_name, content, photo_name) VALUES (MenuName, Content, PhotoName); SET @id = LAST_INSERT_ID(); UPDATE events SET slug = CONCAT(menu_name, "-", @id) WHERE id = @id; END$$ DELIMITER ; </code></pre> <p>And, instead of calling (as you were calling):</p> <pre><code>$query = mysql_query("INSERT INTO events (menu_name, content, photo_name) VALUES ('{$menu_name}', '{$content}', '{$photo_name}');", $connection); </code></pre> <p>just call</p> <pre><code>$result = mysql_query("CALL insert_event('{$menu_name}', '{$content}', '{$photo_name}');",$connection ); </code></pre> <p>Again, I'll strongly advice against using mysql_query. It's outdated, discontinued and unsafe. You should check out mysqli or PDO.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload