0

Is it possible to create variable inside foreach loop that each variable name depend on column that I select?

Here is my code:

    //sql select string declaration
    $sql = "select [Rec_ID],[Bike_ID],[Station],['Line']
            from [rfttest].[dbo].[RFT_Records_Log]
            where [Rec_ID] = '{$_GET['recid']}'";
    $query = sqlsrv_query($conn,$sql); //query
    //if query fail print out error
    if($query === false)
    {
        die(print_r(sqlsrv_errors(),true));
        sqlsrv_close($conn);
    }
    //continue with fetch array
    $recdata = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC);
    //foreach to declare variable
    foreach($recdata as $x => $a)
    {
        $"$x" = $"$a";
    }

In this code I should successfully declare variable like:

$Rec_ID , $Bike_ID , $Station , $Line

I still get a syntax error:

Parse error: syntax error, unexpected '"', expecting variable (T_VARIABLE) or '$'

Andrea
  • 11,801
  • 17
  • 65
  • 72

3 Answers3

2

Simply you can do this:

foreach($recdata as $x => $a)
{
    $x = $a;
}

Use following query:

$sql = "select [Rec_ID],[Bike_ID],[Station],['Line']
        from [rfttest].[dbo].[RFT_Records_Log]
        where [Rec_ID] = '{".$_GET['recid']."}'";

or escape ' with \ like:

$sql = "select [Rec_ID],[Bike_ID],[Station],['Line']
    from [rfttest].[dbo].[RFT_Records_Log]
    where [Rec_ID] = \'{$_GET['recid']}\'";
Manwal
  • 23,450
  • 12
  • 63
  • 93
0

try without quotes

$$x = $$a;

.

0

I think an array is want you need.

  $data["$x"] = $a;
Saty
  • 22,443
  • 7
  • 33
  • 51
Jason K
  • 1,406
  • 1
  • 12
  • 15