I have written a function to print database table to an array like this
$db_array=
Array(
ID=>1,
PARENTID =>1,
TITLE => LIPSUM,
TEXT =>LIPSUM
)
My function is:
function dbToArray($table)
{
$allArrays =array();
$query = mysql_query("SELECT * FROM $table");
$dbRow = mysql_fetch_array($query);
for ($i=0; $i<count($dbRow) ; $i++)
{
$allArrays[$i] = $dbRow;
}
$txt .='<pre>';
$txt .= print_r($allArrays);
$txt .= '</pre>';
return $txt;
}
Anything wrong in my function. Any help is appreciated about my problem. Thanks in advance
If you mean to have multiple records to store in the array then you should do something like this:
function dbToArray($table){
$allArrays = array();
$query = mysql_query("SELECT * FROM $table");
while($dbRow = mysql_fetch_assoc($query)){
$allArrays[] = $dbRow;
}
$txt .='<pre>';
$txt .= print_r($allArrays, true);
$txt .= '</pre>';
return $txt;
}
And your output should look like this:
Array
(
[0] => Array
(
[ID] => 1
[PARENTID] => 1
[TITLE] => LIPSUM
[TEXT] => LIPSUM
)
[1] => Array
(
[ID] => 2
[PARENTID] => 2
[TITLE] => LIPSUM
[TEXT] => LIPSUM
)
)
And one more thing, consider function print_r, there should be second parameter true to return the contents. Otherwise print_r returns the value inline.
Hi rajug;
Edited: Its workin perfect, thanks alot
Rajug’s amended function correctly returns a value, whereas your previous implementation displayed output immediately.
You need to instruct php to echo
out the return value.
echo dbToArray($table);
AnthonySterling:
Rajug’s amended function correctly returns a value, whereas your previous implementation displayed output immediately.
You need to instruct php to echo
out the return value.
echo dbToArray($table);
Yes I know but my file index file is: (is this a good method?)
<?php
$txt='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
.
.
.
</html>
';
echo $txt;
?>
Rajug’s code is perfect and i am writting something wrong in my script!
What do you mean? Why are you storing all in a variable and echo at the end of the page? Without understanding why you are compelled to write the code like this, I cannot say but I do not write myself in that way. I normally use MVC pattern. Also I assume that the example above is just an example there should be more in between?
BTW, what is the purpose of storing the output of print_r function in a variable?
Please dont bother me. I “understand” what im writting as well as you understand.
Im newbee, like you in passing years!!