1

I want to use pdo to insert some data in database with a method I created, but it is not returning the right data

I used the same code with show and select methods and worked fine, in the foreach of method base() is where the bindParam is, I used var_dump() to see what the $key and $value are returning and them are returning the right data, but when I look the database, only the last value is being inserted in all columns

protected function base($query, $params = null, $show = true)
{
    $stmt = $this->conn->prepare($query);

    // checking if there are params or if not, this part will be useless
    if (isset($params)) {

        // making a foreach to bind all parameters, the problem is here, but why?
        foreach($params as $key => $value)
            $stmt->bindParam($key, $value);
    }
    $stmt->execute();

    // checking if needs show the values (for select and show commands)
    if (isset($show)) {
        $results = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
        return $results;
    }
}    

public function add($value = array(), $table)
{

    // turning the array key into strings for putting the columns I want to work with in pdo
    $keys = array_keys($value);
    $keystr = implode(', ', $keys);

    // getting only the values to use later
    $vlr = array_values($value);

    // making a foreach loop for make variables names uppercase and starting with an :
    $i = 0;
    foreach($keys as $key => $data)
    {
        $x[$i] = ':' . strtoupper($data);
        $i++;
    }
    $values = implode(', ', $x);

    // combining the array with variables to be binded with their values
    $bind = array_combine($x,$vlr);

    return $this->base("INSERT INTO $table ($keystr) VALUES($values)", $bind, false);
}

I'm using bindParam and then execute, but the last value is being returned in all columns, ex:

$db->add(['name' => 'some name', 'email' => 'example@mail.com'], 'users');

this should insert in the database,

name: some name,
email: example@mail.com

but it is returning

name: example@mail.com, 
email: example@mail.com

and if I change to

$db->add(['email' => 'example@mail.com','name' => 'some name'], 'users');

it returns

name: some name,
email: some name

What can be doing that?

Phil
  • 157,677
  • 23
  • 242
  • 245

0 Answers0