MyBB Community Forums

Full Version: insert_query & update_query
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
As suggestion the functions should check if $value starts with SELECT and don't add quotes for these values.

Or add an optional array/string param which contains fieldnames which don't need quotes.

This could make the live sometimes easyer.

The function can look like:
	function insert_query($table, $array, $ignore = null)
	{
		if(!is_array($array))
		{
			return false;
		}
		foreach($array as $field => $value)
		{
			$query1 .= $comma.$field;
			if (is_string($ignore) && $field == $ignore)
				$query2 .= $comma.$value;
			elseif (is_array($ignore) && array_key_exists($field, $ignore))
				$query2 .= $comma.$value;
			else
				$query2 .= $comma."'".$value."'";
			$comma = ", ";
		}
		return $this->query("INSERT INTO ".$table." (".$query1.") VALUES (".$query2.");");
	}
I think it's a good idea especially if you need to use a MySQL function for some reason.
Actually, I noticed this before - when tyring to do a simple postnum=postnum+1 in the new handler I couldn't because it was being quoted. This also breaks sub query capabilities like you said.

I'm thinking of adding it as an optional paramater similarly to what you suggested - checking if it starts with select would be bad due to post messages which may start with it - etc.

Cheers,
Chris
Hmmm my suggestion seems only to work if included select use another table.

this query based on my exampe don't run:
$setting_group = array(
  "gid" => "NULL",
  "name" => "Groupname",
  "description" => "",
  "disporder" => "(select max(disporder)+1 FROM ".TABLE_PREFIX."settings)",
  "isdefault" => "no",
);
$db->insert_query(TABLE_PREFIX."settinggroups", $setting_group, "disporder");

Querys which SELECT from same table seems to look like:
INSERT INTO mybb_settinggroups (disporder,name) SELECT MAX(disporder)+1, 'Groupname' FROM mybb_settinggroups
	/**
	 * Build an insert query from an array.
	 *
	 * @param string The table name to perform the query on.
	 * @param array An array of fields and their values.
	 * @return resource The query data.
	 */
	function insert_query($table, $array, $ignore_quotes='')
	{
		$comma = $query1 = $query2 = "";
		if(!is_array($array))
		{
			return false;
		}
		$comma = "";
		$query1 = "";
		$query2 = "";
		foreach($array as $field => $value)
		{
			$query1 .= $comma.$field;
			if(is_array($ignore_quotes) && in_array($field, $ignore_quotes))
			{
				$query2 .= $comma.$value;
			}
			else
			{
				$query2 .= $comma."'".$value."'";
			}
			$comma = ", ";
		}
		return $this->query("INSERT INTO ".$table." (".$query1.") VALUES (".$query2.");");
	}

That _should_ work - I haven't played around with it yet though.
Mr. Chris Boulton Wrote:
is_array($ignle_quotes)
Is it just me or is that supposed to be $ignore_quotes Smile
Yeah.

Fixed it up.