Image

Imagespilltheblood wrote in Imagephp

Mysql Statement class

Hi folks, I'm new here, so "hi". I have a Mysql statement class that prepares a sql query. However, i have way to many if/else statements in this specific method, and was wondering what i could do to cut down some of the code.

for reference, $parameters is an array. parameters are set using a method like this:


$db->select_db('test');
$sql = "SELECT * FROM articles WHERE ( article_cat_id = ? ) ORDER BY article_id DESC LIMIT 0,10";
$stmt = $db->create_statement($sql);
$stmt->set_parameter(1, 1); // Set category ID to '1'
$rs = $stmt->execute();


here is the method in question...



function get_prepared_sql()
{
	$sql_parts = explode('?', $this->sql);
	$sql = $sql_parts[0];
	$max = count($sql_parts);
	 		
	if ( substr_count($this->sql, '?') >= 1 )
	{
		if ( substr_count($this->sql, '?') == count($this->parameters) )
		{
			for ( $i = 1; $i < $max; $i++ )
			{
				if ( !array_key_exists($i, $this->parameters) )
	 			{
	 				$err_str = 'The specified index[\'' . $i . '\'] could not be found.';
	 				return new mysql_error_mgr($this->conn_obj->get_connection_id(), $err_str);
	 			}
	 			else
	 			{
	 				$sql .= $this->parameters[$i] . $sql_parts[$i];
	 			}
	 		}	 				
	 	}
	 	else
	 	{
	 		$err_str = 'All required parameters have not been set.';
	 		return new mysql_error_mgr($this->conn_obj->get_connection_id(), $err_str);
	 	}	 			
	 }	
	 else
	 {
	 	$sql = $this->sql;
	 }
	 return $sql;
}