0

So I am having the $sql variable which is supposed to be a string containing an sql insert statement.Here's the piece of code:

$fields = array('Nume_dep' => $params['Nume_dep'],
                'Id_manager' => $params['Id_manager']);
$id = $params['Id_manager'];
$sql = "insert into departament(Nume_dep,Id_manager) values('$params['Nume_dep']', CONVERT($id, UNSIGNED))";

This is the error message that I get:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

The syntax error is in the insert statement, but I don't know how to fix it.

rkyr
  • 3,131
  • 2
  • 23
  • 38
  • You should rewrite it so it doesn't have any syntax errors. Try to use prepared statements, this code as is is not safe. http://markonphp.com/mysqli-select-prepared-statements/ – Mikel Bitson Nov 05 '15 at 17:49
  • You're using single quotes in your SQL both around the first value, and as the key for your `$params` array. PHP is getting confused by that. As Mikel says - use a prepared statement instead. – andrewsi Nov 05 '15 at 18:00

2 Answers2

0

In strings PHP will only do rather basic automatic variable expansion. The Issue is with the index operator here: $params['Nume_dep']

Consider to use prepared statements in order to prevent SQL injection. If an attacker can make sure, that your function is called with something like "', 43); drop table department; --" as value for $params['Nume_dep'], you're going to be in big trouble.

cdonat
  • 2,748
  • 16
  • 24
0
$id = $params['Id_manager'];
$nume_dep=$params['Nume_dep'];

$sql = "INSERT INTO departament(Nume_dep,Id_manager) values('$nume_dep', CONVERT($id, UNSIGNED))";
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77