Marcus Krueger
Marcus Krueger

Reputation: 163

Function to shorten Queries not working

Here is my code:

function query($query, $variables = NULL) {
    $execute = sprintf($query, $variables);
    $execute = mysql_query($execute);

    return $execute;
}

$insert = query("INSERT INTO accounts (username, email, password, validation_code, registration_timestamp, registration_ip) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')", "$username, $email, $passwordEncrypted, $validationCode, $timestamp, $ip");

If there is only one variable, it will work. But with any after that it wont. Any suggestions on how to fix & improve this function? Thanks guys!

Upvotes: 1

Views: 82

Answers (3)

zerkms
zerkms

Reputation: 255005

rewrite it to:

function query($query, $variables = array()) {
    $execute = vprintf($query, $variables);
    $execute = mysql_query($execute);

    return $execute;
}

$insert = query("INSERT INTO accounts (username, email, password, validation_code, registration_timestamp, registration_ip) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')", array($username, $email, $passwordEncrypted, $validationCode, $timestamp, $ip));

Btw, I absolutely agree with @Alex and you need to move to mysqli/PDO prepared statements instead.

PS: don't forget to apply mysql_real_escape_string to each variable.

Upvotes: 2

RobertPitt
RobertPitt

Reputation: 57268

try something like this:

function query()
{
    $query = call_user_func_array('sprintf',func_get_args());
    return mysql_query($query);
}

and then use like so:

$insert = query(
    "INSERT INTO accounts (username, email, password, validation_code, registration_timestamp, registration_ip) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
    $username,
    $email,
    $passwordEncrypted,
    $validationCode,
    $timestamp,
    $ip
);

Upvotes: 0

alex
alex

Reputation: 490433

Don't pass a string when you should be passing it directly an array to your function.

However, you shouldn't me making a wrapper for mysql_query() when better alternatives exist, such as PDO.

Upvotes: 1

Related Questions