Here's a basic class I made a while ago that does something similar..
Once on a page you'll need to do:
$db = new dbObject("localhost", "database", "myuser", "mypassword");
from then on, you can just use:
$db->query("SELECT * FROM wherever");
It'll return just the array of contents of your query.
Once you have the array, you can get the number of rows by:
$num_rows = count($returnedArray);
and you can get the number of fields by:
$num_fields = intval(count(@$returnedArray[0]));
The plan was back then that I could replace the class if I ever moved to
a different database technology.
<?php
class dbObject {
var $server = "localhost";
var $database = "";
var $username = "root";
var $password = "";
var $connection;
function dbObject ($server, $database, $username, $password) {
if ($this->connection = mysql_connect($server, $username,
$password)) {
mysql_select_db ($database, $this->connection);
}
}
function query($sql) {
$dbO = mysql_query($sql, $this->connection);
if (strtolower(substr($sql, 0, 6))=="select") {
$ret = Array();
if (!$dbO) {print "SQL: {$sql} <BR /> FAILED";}
while ($dbR = mysql_fetch_array($dbO)) {$ret[] = $dbR;}
}else{
$ret = $dbO;
}
return $ret;
}
function close() {
mysql_close($this->connection);
}
}
?>
StinkFinger wrote:
All,
This is a function that I use quite often. I pass in my SQL string and
return the results as an array. Does anyone see any optimizations that I can
make (eventually I would like to make a class, but I am still new).
function table_array ($sql_string)
{
$result = mysql_query($sql_string) or die("dead");
$num_rows = mysql_num_rows($result);
$num_fields = mysql_num_fields($result);
$j = 0;
$x = 1;
while ($row = mysql_fetch_array($result)) {
for($j = 0;$j < $num_fields;$j++) {
$name = mysql_field_name($result, $j);
$arr[$x][$name] = $row[$name];
}
$x++;
}
return array('arr' => $arr, 'rows' => $num_rows, 'fields' => $num_fields);
}
Always trying to shave off some access times =)
Thanks.