/** * Creates Datagrid object for you and returns it * * @param resource $connection The connection to the database. This can also be an array * containing host/user/pass/dbas parameters to connect to the * database. This can also be used to create a datagrid from * an array data source by supplying an array instead of the * database connection, eg: $grid = Datagrid::Create($myArray); * @param string $sql The SQL query with or without the ORDER BY clause */ public static function Create($connection, $sql = null) { /** * Creates an array based datagrid if the first arg is am array */ if (is_array($connection) and is_null($sql)) { return Datagrid::CreateFromArray($connection); } // Connect if need be if (is_array($connection)) { $host = $connection['hostname']; $user = $connection['username']; $pass = $connection['password']; $dbas = $connection['database']; $connection = mysql_connect($host, $user, $pass) or die('<span style="color: red">Failed to connect: ' . mysql_error() . '</span>'); mysql_select_db($dbas); } /** * Order by */ if (isset($_GET['orderDir']) and !empty($_GET['orderBy'])) { // Store it so the direction indicators appear Datagrid::$orderby['column'] = $_GET['orderBy']; Datagrid::$orderby['direction'] = $_GET['orderDir']; $orderby = 'ORDER BY ' . $_GET['orderBy'] . ' ' . ($_GET['orderDir'] ? 'ASC' : 'DESC'); $sql = preg_replace('/ORDER\\s+BY.*(ASC|DESC)/is', $orderby, $sql); } /** * Perform the query to get the result set */ $resultset = mysql_query($sql, $connection); $grid = new Datagrid($connection, $resultset); // If the query doesn't have an ORDER BY, then disable ordering if (strpos($sql, 'ORDER BY') === false) { $grid->allowSorting = false; } return $grid; }