No Code Attached Yet
avatar mariograf
mariograf
26 Nov 2024

Steps to reproduce the issue

Create a simple prepared statement with a parameter, which is used more than once, and bind it to a variable. The following code example doesn't make sense but shows the problem:

$db = \Joomla\CMS\Factory::getContainer()->get('DatabaseDriver');
$someValue = 2;
$query = $db->getQuery(true)
    ->select('*')
    ->from('#__action_logs')
    ->where('id < :someValue AND user_id < :someValue ;')
    ->bind(':someValue', $someValue);
$db->setQuery($query);
$db->execute();

Expected result

All occurences of the parameter (:someValue) should be replaced and the query should be executed successfully.

Actual result

Exception: The number of variables must match the number of parameters in the prepared statement

System information (as much as possible)

Joomla 4.4.9

Additional comments

The error occurs using Joomla 4.4.9 but seems to be fixed in Joomla 5.2.1. Of course, there is an easy workaround (using different placeholders) but it took me a while to understand the problem (my original Sql statement was more complicated), so I think its worth to fix it to save others from having the same problem.

avatar mariograf mariograf - open - 26 Nov 2024
avatar mariograf mariograf - change - 26 Nov 2024
Labels Removed: ?
avatar joomla-cms-bot joomla-cms-bot - change - 26 Nov 2024
Labels Added: No Code Attached Yet
avatar joomla-cms-bot joomla-cms-bot - labeled - 26 Nov 2024
avatar mariograf mariograf - change - 26 Nov 2024
The description was changed
Title
Creating prepared statements using bound variable multiple times throws exception
Creating prepared statements using a bound variable multiple times throws exception
avatar mariograf mariograf - edited - 26 Nov 2024
avatar Quy Quy - change - 26 Nov 2024
Status New Closed
Closed_Date 0000-00-00 00:00:00 2024-11-26 19:06:07
Closed_By Quy
avatar Quy Quy - close - 26 Nov 2024
avatar Quy
Quy - comment - 26 Nov 2024

It's possible to use one variable for all bind values and ParameterTypes.
See example in manual: https://manual.joomla.org/docs/general-concepts/database/select-data/

$query = $this->db->getQuery(true)
	->select($this->db->quoteName(array('id', 'password')))
	->from($this->db->quoteName('#__users'))
	->where($this->db->quoteName('username') . ' = :username')
	->where($this->db->quoteName('password') . ' = :password')
	->bind([':username', ':password'], $credentials['username']);
avatar mariograf
mariograf - comment - 26 Nov 2024

@Quy Thank you for the quick response! Yes, I read the docs and saw this, but did not find any hint mentioning, that a parameter is not allowed to be used more than once. Even weirder that there is a different behaviour in different versions of joomla (4.4.9 / 5.2.1) without any documentation.

avatar fgsw
fgsw - comment - 28 Nov 2024

@mariograf Can you update the docs?

Add a Comment

Login with GitHub to post a comment