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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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);
	}
}
}

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.