2
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

I have taken the above code from the php manual and the parts I am confused about is here:

$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

Is it valid and equivalent to use this code by first declaring the variables and then passing them to bind_param()?

As such:

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

$stmt->bind_param('sssd', $code, $language, $official, $percent);

I am honestly not sure why the example the manual gives is valid at all, as you are using the variable prior to declaring them.

2
  • Yes it should go into a variable. Commented Sep 3, 2013 at 13:36
  • 4
    Note that bind_param() accepts the variables as references! Commented Sep 3, 2013 at 13:36

2 Answers 2

1

bind_param accepts references, if your unsure what references exactly are then click here for the extract named as "references explained"

This does mean, it is valid to set your variables after the bind_param but then again, it's down to preference how you wish to do it. I for one, prefer declaring the variables prior to the bind

Little observation

The variables are declared prior to the execute, and as PHP works from top to bottom processing. When the variables are actully needed (on the execution) they would have already been set, if you declare your variables after the execute() you will be prompted with SQL Failures and other unwanted php errors

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

1 Comment

So essentially what you are saying is that when calling bind_param(), bind_param() does not actually fire until execute is called?
0

Yes, because mysqli_stmt::bind_param: Binds variables to a prepared statement as parameters and it uses reference to these variables so that whenever you change them the change reflects on them.

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.