-1
$new_id = mysqli_insert_id($dbc)    
foreach ($_POST['d_specialty'] as $key => $value) {
      $q = "INSERT INTO d_specialty (d_id, s_id) VALUES ($new_id, (SELECT specialty.id FROM specialty WHERE specialty.name = $value))";
      $r = mysqli_query($dbc,$q);

i want to insert two values, the first one is a variable and the second is a select statement but the code above does not work...

Dharman
  • 30,962
  • 25
  • 85
  • 135
Omar Alhadidy
  • 109
  • 1
  • 9
  • The reason might be that your subquery returns more than 1 row. – Paul Spiegel Aug 13 '16 at 20:07
  • 1
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST` or `$_GET` data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Aug 13 '16 at 22:58

2 Answers2

3

First, use insert . . . select:

INSERT INTO d_specialty (d_id, s_id)
    SELECT $new_id, specialty.id
    FROM specialty
    WHERE specialty.name = $value;

Second, parameterize the query so $new_id and $value are passed in as parameters rather than put directly into the query string. One reason is to prevent SQL injection attacks. Another very important reason is to guard against potential syntax errors.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

When using insert into select you don't need to use values. Remove that and then move the $new_id variable into the select statement:

INSERT INTO d_specialty (d_id, s_id) 
SELECT $new_id, specialty.id 
FROM specialty 
WHERE specialty.name = $value
sgeddes
  • 62,311
  • 6
  • 61
  • 83