1

As part of MySQL SELECT statement I'm trying to dynamically query the database.

Current code:

$stmt = $pdo->prepare('SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`="assignment" AND `TABLE_NAME`=:table AND `COLUMN_NAME` != :column1 AND `COLUMN_NAME` != :column2;');
  $criteria = [
    'table' => $_GET['section'],
    'column1' => 'jobid',
    'column2' => 'catid'
  ];
  $stmt->execute($criteria);

  $arr = array();

  echo '<form method="POST">';
  foreach ($stmt as $row){
    echo '<label>'.ucwords($row['COLUMN_NAME']).':</label>
    <input type="text" name="'.$row['COLUMN_NAME'].'"/><p>';
    $arr[] = $row;
  }
  echo '<input type="submit" value="Submit" name="submit"/>
      </form>';

  if (isset($_POST['submit']))
    echo $query = implode(',', $arr);

I've got it working just fine using $_POST values but for some reason it outputs:

Array,Array,Array,Array,Array

even though the var_dump() of $arr is:

    0 => 
    array (size=2)
      'COLUMN_NAME' => string 'title' (length=5)
      0 => string 'title' (length=5)
  1 => 
    array (size=2)
      'COLUMN_NAME' => string 'salary' (length=6)
      0 => string 'salary' (length=6)
  2 => 
    array (size=2)
      'COLUMN_NAME' => string 'location' (length=8)
      0 => string 'location' (length=8)
  3 => 
    array (size=2)
      'COLUMN_NAME' => string 'description' (length=11)
      0 => string 'description' (length=11)
  4 => 
    array (size=2)
      'COLUMN_NAME' => string 'category' (length=8)
      0 => string 'category' (length=8)
3
  • 1
    implode() does not work on multidimensional arrays. Commented Jan 6, 2016 at 20:46
  • your var_dump shows that $arr is an array of arrays. is that what you want? Commented Jan 6, 2016 at 20:46
  • Is that pseudo code because I can see a number of reasons it should not get past the first query? Commented Jan 6, 2016 at 20:53

1 Answer 1

3

The implode function doesn't work the way that you want with an array of arrays. It takes the arrays in $arr and makes them into the string 'Array'. You can loop through the array and implode that way, for example,

$list = '';
foreach ($arr as $inner) {
    $list .= $inner['COLUMN_NAME'].',';
}
$list = rtrim($list,',');
Sign up to request clarification or add additional context in comments.

3 Comments

Works great but repeats the elements and I can't figure it out: title,titlesalary,salarylocation,locationdescription,descriptioncategory,category
It's because 'COLUMN_NAME' has the same value as 0. Hang on & I'll edit the answer.
Thank you so much! I've been staring at it for hours

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.