7

I am trying to bind params to a INSERT INTO MySQLi prepared statement if that variable exists, otherwise insert null.

This is what I have, but it is not working:

if (!empty($name)) {
    $result->bind_param('ss', $name, $url_friendly_name);
} else {
    $result->bind_param('ss', null, null);
}

if (!empty($description)) {
    $result->bind_param('s', $description);
} else {
    $result->bind_param('s', null);
}

Does anyone know of a better way of doing this or is there just a minor issue with my code. I am doing the above for each variable in the prepared statement.

5
  • Can you use an empty string there, e.g. '' ? Commented Mar 7, 2011 at 0:39
  • Are you trying to leave a field out of the query if it is empty? Commented Mar 7, 2011 at 0:50
  • @tandu yeah if I can leave a field out, that would be work too. Do you have a better way of doing it? Commented Mar 7, 2011 at 3:53
  • You would have to conditionally construct the query .. I think that is what I would do though. I don't use mysqli (that is what you're using, right?) So I don't know so much in this case.. Commented Mar 7, 2011 at 3:56
  • Doing that would not allow me to use a prepared statement. Commented Mar 7, 2011 at 11:44

2 Answers 2

4

bind_param works by reference. That means that it takes a variable, then uses the value of that variable in execute.

null is not a variable.

Try setting a variable to null and then binding that variable instead.

(Also consider using PDO instead of mysqli, where the execute method can take a simple array and you can bypass wacky binding methodology of mysqli.)

Sign up to request clarification or add additional context in comments.

Comments

1

Keep in mind that you can't use bind_param twice, because the last statement will replace the first. Try to find a way to use bind_param just once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.