mysqli::bind_param(); variables

2019-02-26 01:40发布

问题:

$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.

回答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



回答2:

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.