Jump to content

replace every ? with each word in an array.


turkman

Recommended Posts

Hey i hope the title explains it enough. I'm just trying to get into classes.  I am making a function to make making mysql querys easier.

 

I pass the class the first string

 

$db->inputstring("INSERT INTO ? (?,?) VALUES ('?','?')");

$db->format('mytable','id','name','1','ben');

 

Can someone tell me how the format fuction would look? Im not sure how to swap arrays.

I can show you some ways, but why?  PDO has this: http://us2.php.net/manual/en/pdostatement.bindparam.php and if you're using MySQL you can use this: http://us2.php.net/manual/en/mysqli-stmt.bind-param.php.  These have the benefit of escaping the data for you, and maybe other benefits.

 

If not, then there is always: http://us2.php.net/manual/en/function.sprintf.php.

its not really for functionality its just more out of intrest to see how it would work... can you replace may ?'s with different elements of an array?

 

Also if you want to pass an array to a function, how do you do it.

 

say

 

function acceptarray($arr)

 

would you call that like the followin ---- acceptarray('arr1','arr2','arr3')

 

can someone answer these for me please.

 

Thanks.

This is very convoluted, but I'm tired and I couldn't get the simple solution to work.  I'll revisit it later.  This is still not the right approach for this type of thing, but just to answer the question:

 

$db = new DB;
$db->inputstring("INSERT INTO ? (?,?) VALUES ('?','?')");
$db->format('mytable', array('id'=>1, 'name'=>'ben'));
echo $db->query;

class DB {
public function inputstring($string) {
	$this->query = $string;
}

public function format($table, $data) {
	$replace = array_merge(array($table), array_keys($data), array_values($data));
	$search  = array_fill(0, count($replace), '/\?/');

	$count = true;
	while($count) {
		  $this->query = preg_replace($search, $replace, $this->query, 1, $count);
	}
}
}

 

 

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.