title: Making multiple replacements using str_replace in php
body: <p>OK here's the problem: </p>
  
  <p>I'm trying to write the query function for a database class in my project and I want to make it easier to escape the sql and check if it is harmful to the database in anyway.</p>
  
  <p>Let's say I have a query like this:</p>
  
  <pre><code>INSERT INTO users (id,name,email,username,birthdate)
  VALUES(1,'Josh','josh101@coolsite.com','josh101','1978-11-02')
  </code></pre>
  
  <p>But it won't really help If I hardcode this into the function. So lets say I used a question mark for all the values I want to insert and then pass an array to the function containing the actual values I want to replace, just like the way it's done in codeigniter.</p>
  
  <p>Here's a sample:</p>
  
  <pre><code>//Here's the way the function appears in the class definition.
      public function query($sql,$params=array()){
  
       if (!empty($params) &amp;&amp; is_string($sql)):
                 //do some stuff here.
  
  
              elseif (empty($params) &amp;&amp; is_string($sql)):
                  //do some other stuff here.
  
              else:
                  //bad sql argument.
                  die("Mysql_database ERROR: The query submitted is not a string!");
              endif;
  
      }
  
  //Here's where the function is applied.
   $sql="INSERT INTO users (id,name,email,username,birthdate)
          VALUES(?,?,?,?,?)";
  
  $params=array(1,'Josh','josh101@coolsite.com','josh101','1978-11-02');
  
  $db= new Mysql_database();
  
  $response=$db-&gt;query($sql,$params);
  </code></pre>
  
  <p>Now here's what I want to do:</p>
  
  <ol>
  <li>If the second argument is not provided, just run the query as it is.</li>
  <li>Else check the elements of the array provided for their type and escape them properly then replace them in their appropriate positions in the pseudo-sql string provided.</li>
  </ol>
  
  <p>The problem is that it seems that all the question marks get replaced by only the first element of the array: </p>
  
  <p>Here's the code:</p>
  
  <pre><code>/*assuming I already have a function called create_array that well,
  basically creates an array with n elements 
  specified in the first parameter and fills each element with the value provided in 
  the second parameter.*/
      $toreplace = create_array(substr_count($sql, "?"),"?");
      $sqlComplete = str_replace($toreplace, $params, $sql);
  </code></pre>
  
  <p>If I echo $sqlComplete I get this:</p>
  
  <pre><code>INSERT INTO users (id,name,email,username,birthdate)
  VALUES(1,1,1,1,1)
  </code></pre>
  
  <p>What can I do so that each element of $params is put in its appropriate position in the sql string?</p>
  
  <p>PS: Please don't tell me to just use codeigniter because I'm trying to challenge myself here a bit by building a project from scratch, I don't want to always depend on frameworks to get the job done.</p>