从php中查询创建变量[关闭]

Just wondering how the selects from the table can be created into variables. Totally unsure how this can be done. I know with arrays it's quite simple. Somewhat new to php.

Here is my code:

    function get($table_name, $conn)
    {
    try
    {
        $result = $conn->query("SELECT archive, projectname, description, clientid FROM $table_name ORDER BY projectname ASC");

        return ($result->rowCount() > 0)
            ? $result // if
            : false; // else
    }

    catch(Exception $e)
    {
        return false;
    }
    }

    <?php foreach($archives as $archive): ?>
    <tr>
        <td><?php echo $archive; ?></td>
    </tr>
    <?php endforeach; ?> 

Any help at all will be great,

Thanks in advance.

If your array is an associative array then you can use extract()

$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size
";

// This will give you 
blue, large, sphere, medium

So in your example you can use something like the following

extract($result, EXTR_OVERWRITE);

// now you have 
//$archive
//$projectname
//$description
//$clientid

However using EXTR_OVERWRITE as PHP will cause:

If there is a collision, overwrite the existing variable.

More accuracy toward your goal: Assuming the result array has more than one row, and you want to fill the arrays

$archives = array();

foreach($result as $r){
    extract($r, EXTR_PREFIX_SAME);
    $archives[] = $archive
}

Then you can do

foreach($archives as $a){
    echo $a
}

Without Using Extract()

$archives = array(); 
foreach($result as $r){

    $archives[] = $r['archive'] // or $r[0]
}