Pieter Dijkstra Pieter Dijkstra - 5 months ago 19
PHP Question

PDO query duplicate one bind Instead of their own

I've an question about my CRUD plugin. I'm working on the update section and when i update the query, all columns al get the ':id' as value and not their own ones.

Below my debugDumpParams();

string(7) "column1"
string(4) "help"
string(7) "column2"
string(4) "help"
string(2) "id"
string(1) "4"

SQL: [69] UPDATE test SET column1 = :column1, column2 = :column2 WHERE id = :id

Params: 3
Key: Name: [8] :column1
paramno=-1
name=[8] ":column1"
is_param=1
param_type=2
Key: Name: [8] :column2
paramno=-1
name=[8] ":column2"
is_param=1
param_type=2
Key: Name: [3] :id
paramno=-1


Al other sections of my CRUD are working and the insert works almost on the same way, so i don't no what i do worng, maybe someone from outside can see the eror that i can't see.

Below my code:

}elseif($type == 'update') {

$columns = array_keys($column);
$col_set = implode(",",$columns);

$query_array = array();

foreach ($column as $key => $value) {

if($key == 'id'){
$query_array_id = $key.' = :'.$key;
}else{
$query_array[] = $key.' = :'.$key;
}

}
$query = ''.$query.' '.$table.' SET '.implode(", ",$query_array).' WHERE '.$query_array_id.'';

$dbh_query = $dbh->prepare($query);

foreach ($column as $key => $value) {

$dbh_query->bindParam(':'.$key, $key);
var_dump($key);
$key = trim($value);
var_dump($key);

}

$dbh_query->execute();
$dbh_query->debugDumpParams();

echo '<br/>';

return $dbh_query;
}


Below what i get in the database:

'column1' => '4',
'column2' => '4',
'id' => '4'


Thats wrong because my function call is:

$postFile->processing('update', 'test', array(
'column1' => 'help',
'column2' => 'help',
'id' => '4'
));


Thanks a lot!

UPDATE!

Change a little bit of my code and it works, thanks a lot!

}elseif($type == 'update') {

$columns = array_keys($column);
$col_set = implode(",",$columns);

$query_array = array();

foreach ($column as $key => $value) {

if($key == 'id'){
$query_array_id = $key.' = :'.$key;
}else{
$query_array[] = $key.' = :'.$key;
}

}

$query = ''.$query.' '.$table.' SET '.implode(", ",$query_array).' WHERE '.$query_array_id.'';

$dbh_query = $dbh->prepare($query);

$dbh_query->execute($column);


return $dbh_query;

Answer

send your data right into execute. without using bindParam

$dbh_query = $dbh->prepare($query);
$dbh_query->execute($column);

but you have to understand that all this spaghetti

''.$query.' '.$table.' SET '.implode(", ",$query_array).' WHERE '.$query_array_id.''

is severely vulnerable to SQL injection