SQL Fetch Array using Foreach Array
Posted: Sat Apr 13, 2013 1:45 am
SQL Server 2008.
I'm trying to create a function that I can use to dynamically grab values from a database, what I'm having trouble understanding is how to use an array to assist me with grabbing named items from a SQL server within a while loop.
So, let's say I have something simple like:
Typically you'd hard code it as such:
But what I would like to do is use an array to grab those instead, this is how I would imagine that it would look, but this is not working for me:
EDIT: Found errors in my initial code, I'm able to pull data now, but it won't iterate through the different columns in the array.
Is this closer?
Any help is appreciated!
Thanks!
I'm trying to create a function that I can use to dynamically grab values from a database, what I'm having trouble understanding is how to use an array to assist me with grabbing named items from a SQL server within a while loop.
So, let's say I have something simple like:
Code: Select all
CREATE TABLE [dbo].[test](
[firstname] [varchar](50),
[lastname] [varchar](50)
)Code: Select all
<?php
include('config.inc.php'); // db connections details
$items = array (
"1" => "firstname",
"2" => "lastname");
$sql = "SELECT * FROM dbo.test";
$result = "sqlsrv_fetch_array($db, $sql);
while ($row = sqlsrv_fetch_array($result)) {
echo $row['firstname'];
}
?>
Code: Select all
<?php
include('config.inc.php'); // db connections details
$items = array (
"1" => "firstname",
"2" => "lastname");
$sql = "SELECT * FROM dbo.test";
$result = "sqlsrv_fetch_array($db, $sql);
while ($row = sqlsrv_fetch_array($result)) {
foreach ($items as $array => $value) {
echo $row[$value];
}
}
?>
Is this closer?
Code: Select all
<?php
foreach ($items as $array => $value) {
$i = 0;
while ($i < $row = sqlsrv_fetch_array($result)) {
echo "<tr><td>" . $row[$value] . "</td></tr>";?><?php
}
}
?>Thanks!