Mike Schmid
Mike Schmid

Reputation: 21

PHP - mysqli_stmt_bind_param group multiple $types

Is there a way to somehow "group" multiple type-identifiers of the same class in mysqli_stmt_bind_param() function? e.g. '10*s' instead if 'ssssssssss'.

Assume I have the following string $prep_sql and a statement $stmt.

$prep_sql = "INSERT INTO table (foo1, foo2, ..., fooN) VALUES (?, ?, ..., ? )";
$stmt = mysqli_prepare($connection, $prep_sql);

Now I need to bind the statement to parameters. Let's assume there are ten string parameters. Do I really need to specify every parameters type individually ('s'), like this:

mysqli_stmt_bind_param($stmt, 'ssssssssss', $var1, $var2, ..., $var10);

Or is there a way to group the types, maybe with something like:

mysqli_stmt_bind_param($stmt, '10*{s}', $var1, $var2, ..., $var10);

Upvotes: 2

Views: 88

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157828

No, there is no way to do it directly. The identifiers string should be always explicit.

However, given the fact that most of time you can use "s" for any parameter, you can use a mysqli helper function such as one I wrote:

function prepared_query($mysqli, $sql, $params, $types = "")
{
    $types = $types ?: str_repeat("s", count($params));
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    return $stmt;
}

just add it to your configuration file and make all your mysqli interactions 2 times less verbose. It would solve your current problem as well, by generating the types string automatically:

$sql = "INSERT INTO table (foo1, foo2, ..., fooN) VALUES (?, ?, ..., ? )";
$parameters = [$var1, $var2, ..., $var10];
prepared_query($connection, $sql, $parameters);

Upvotes: 2

Related Questions