Jump to content

Recommended Posts

I have an array like this:

 

$tran = array(
	array('libAddSetting', array('key' => 'foo', 'value' => 'bar') ),
	array('libUpdateSetting', array('value' => 'moo', 'key' => 'foo') ),
);

 

The first value in each array is an identifier for a query (since it's going to be specific per driver) and the second is an array containing the appropriate binds.

 

Here are the queries for those from the MySQL driver:

	// Add setting
	public function libAddSetting(){
		return "INSERT INTO `settings` (`key`, `value`) VALUES (:key, :value)";
	}
	// Update setting
	public function libUpdateSetting(){
		return "UPDATE `settings` SET `value` = :value WHERE `key` = :key";
	}

 

$tran is going to be passed to a function which prepares the queries and executes them - you can probably work out the idea here is to insert a record into the 'settings' table with the key 'foo' and the value 'bar' and then update that record so the value is 'moo'.

 

Here is the function that will handle that:

	public function transaction($queries=array())
	{
		try
		{
			$this->pdo->beginTransaction();
			foreach ($queries as $q)
			{
				$stmt = $this->pdo->prepare($this->$q[0]());
				foreach ($q[1] as $key => $value)
				{
					$stmt->bindParam(":{$key}", $value); 
				}
				$stmt->execute();
			}
			$this->pdo->commit();
		}
		catch (PDOException $e)
		{
			$this->pdo->rollback();
			throw new Exception($this->returnError($e), 1);
		}
	}

 

But it doesn't work, it inserts a record with the key and value both 'bar'. I can't for the life of me work out why. If I use this, it works fine:

 

	public function transaction($queries=array())
	{
		try
		{
			$this->pdo->beginTransaction();
			foreach ($queries as $q)
			{
				$stmt = $this->pdo->prepare($this->$q[0]());
				$stmt->bindParam(':key', $q[1]['key']);
				$stmt->bindParam(':value', $q[1]['value']);
				// foreach ($q[1] as $key => $value)
				// {
				// 	$stmt->bindParam(":{$key}", $value); 
				// }
				$stmt->execute();
			}
			$this->pdo->commit();
		}
		catch (PDOException $e)
		{
			$this->pdo->rollback();
			throw new Exception($this->returnError($e), 1);
		}
	}

 

Any ideas?

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.