title: Generate unique slug Codeigniter 3 && MySQL
body: <p>I need to generate unique slug based on user input with this code:</p>
  
  <pre><code>public function create_slug($id, $name){
  
      $count = null;
      $name = url_title($name);
      while(true) {
          $this-&gt;db-&gt;select('id');
          $this-&gt;db-&gt;where('id !=', $id);
          $this-&gt;db-&gt;where('slug', $name);
          $query = $this-&gt;db-&gt;get('users');
          if ($query-&gt;num_rows() == 0) {
              break;
          } else {
              $name .= '-' . (++$count);
          }
      }
      return $name;
  }
  </code></pre>
  
  <p>It select everything that mach the slug (<code>$name</code>), except its own slug.
  The result for first user input -  <code>123</code> is slug - <code>123</code>. For second same input the slug is <code>123-1</code>, but third input with same text is with result <code>123-1-2</code>, which is not what I want.</p>
  
  <p>I tried another way :</p>
  
  <pre><code>public function create_slug($id, $name){
      $count = null;
      $name = url_title($name);
      $this-&gt;db-&gt;select('id');
      $this-&gt;db-&gt;where('id !=', $id);
      $this-&gt;db-&gt;where('slug', $name);
  
      $query = $this-&gt;db-&gt;get('users');
  
      if($query-&gt;num_rows()){
          $count = '-' . ($query-&gt;num_rows() + 1);
      }
      return $name . $count;
  }
  </code></pre>
  
  <p>Here, is same query, but count rows + 1. 
  For first <code>123</code> the slug is <code>123</code>;
  Second <code>123</code>, slug <code>123-2</code>;
  Third <code>123</code>, slug again <code>123-2</code>, which is not unique.</p>
  
  <p>How can I create slug that is based on some user input and is unique and, if there is slug with value <code>name</code>, next will be <code>name-1</code>, if again, next will be <code>name-2</code> and etc. ? </p>