1

I'am trying to replace a part of a string for another value and i'am doing this for some logs that i need to create, to have the full query. I'am using PDO.

I want to in the end have the correct query to print on the log.

    public function queryBindValues($string,$data,$queriesLog) {
    echo gettype($data); //object
    $toArray = (array)$data; //convert to array
    $finalArray = [];

    //remove class name(on key) from array
    foreach($toArray as $k=>$v) {
      $k = str_replace(get_class($data), "", $k);
      $finalArray[$k] = $v;
    }

    /*
    $finalArray
      Array
      (
          [id] => 
          [gender] => vbn
          [status] => 1
          [user_id] => TLDICA
          [last_update] => 2018-04-25
      )
    */

    //string = INSERT INTO type_genders (status, user_id, last_update, gender) VALUES (:status, :user_id, :last_update, :gender);

    foreach($finalArray as $k=>$v) {
      $string = str_replace(":$k", $v, $string);
    }

    echo $string;
    //INSERT INTO type_genders (status, user_id, last_update, gender) VALUES (:status, :user_id, :last_update, :gender)
}

Can someone help me? Thanks,

  • what does that mean? `$string = str_replace(":$k", $v, $string);`, you're replacing placeholders into the values? i don't understand what are you trying to accomplish here – Kevin Apr 25 '18 at 07:17
  • I'am replacing :status by 1, for example. – Diogo Castro Apr 25 '18 at 07:18
  • just make sure `$string` does really have those placeholders, looking on this side it would work just fine, my advice to you also is to log the queries made this way instead https://stackoverflow.com/a/304008/3859027 – Kevin Apr 25 '18 at 07:27
  • cannot log like that, i'am using PDO, bindvalues. you don't get the complete query. – Diogo Castro Apr 25 '18 at 07:30
  • oh okay, yeah you cannot get the logged query if its being prepared, anyway, the problem is elsewhere, since you have the correct `$string` with the correct value, [it will work just fine](https://3v4l.org/IfKvG), like what i've said earlier, you need to debug some more, – Kevin Apr 25 '18 at 07:39
  • yes, same code, but for some reason it doesnt work. thanks anyway. – Diogo Castro Apr 25 '18 at 07:43
  • found the problem, it is on the array. if i create manually the array it works. but if i convert from object to array, doesn't work. – Diogo Castro Apr 25 '18 at 07:59
  • good for you then, that's why on the link i provided, if the given inputs are correct, the code should work just fine. we just don't know (on our end) what the original `$data` looks like – Kevin Apr 25 '18 at 08:29
  • $data looks like this: TypeGenders Object ( [id:TypeGenders:private] => [gender:TypeGenders:private] => w [status:TypeGenders:private] => 1 [user_id:TypeGenders:private] => TLDICA [last_update:TypeGenders:private] => 2018-04-25 ) – Diogo Castro Apr 25 '18 at 08:55

0 Answers0