Jump to content

[SOLVED] MySQL Fetch Array Function


per1os

Recommended Posts

Hi All,

 

I am trying to re-build a function of mine to allow for more customization but I have hit a road block in a sense on which would be better.

 

Here is my current function:

 

<?php
function fetchArr2($dataArr, $type='select') {
	// Should only be SELECT
	if (checkType($type) > 1) {
		return error(LANG_DB_ERR_WRONGTYPE);
	}

	if (ereg($dataArr, "Resource")) {
		$result = $dataArr;
		return mysql_fetch_assoc($result);
	}

	if (!is_array($dataArr)) {
		return error(LANG_DB_ERR_DATAARR);
	}		

	//array("columns" => "userid, username, email", "table" => "users", "where" => "username='frost'");
	$sql = "SELECT " . $dataArr['columns'] . " FROM " . replaceTable($dataArr['table']) . " WHERE " . $dataArr['where'] . " " . $dataArr['orderby'] . " " . $dataArr['limit'];

	$result = query($sql) or error("SQL Error: " . mysql_error();
                return mysql_fetch_assoc($result);
}
?>

 

The question is how I am passing the data into this to be built the function in action would look like such

 

<?php
$newArray = fetchArr2(array("columns" => "userid, username, email", "table" => "users", "where" => "username='frost'"), 1);
?>

 

I am wondering if there is a better way to go about this. The goal here is to be able to have it all dynamic, meaning the table users is actually test_users which is replaced inside the function, but I could change it to be my_users and not have a problem.

 

Any ideas or opinions on that? Appreciate it.

Link to comment
https://forums.phpfreaks.com/topic/43370-solved-mysql-fetch-array-function/
Share on other sites

"columns" (even if it's just "*") and "tablename" are a mandatory minimum requirement so you should check they are present.

 

You should then check if things like ['where'], or ['orderby'] exist and, if so, add that particular clause to the query

Yea, I am actually in the midst of re-doing the design to be a ton better, I will post that one for ideas once it is done. Thanks for the feedback Barand, that is actually part of the reason why I am re-doing it. I found that it needs to be more complicated =)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.