问题
I'm very new to PHP and MySQL and I'm looking for a solution to store a single value of a database row in a variable using a prepared statement.
Right now this is the prepared statement and execution:
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
I tried get_result()
, fetch()
, fetch_object()
and I'm out of ideas and google search results.
回答1:
You need to add to your code the binding of the result to a specific variable
$emailsql->bind_result($emailResult);
And you fetch it :
while($emailsql->fetch()){
printf ($emailResult);
}
So this should be it:
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
$emailsql->bind_result($emailResult);
while($emailsql->fetch()){
printf ($emailResult);
}
In case you need the variable outside the loop I would take this approach:
$theEmail;
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
$emailsql->bind_result($emailResult);
while($emailsql->fetch()){
$theEmail=$emailResult;
}
Note that you would need an array in order to query more than one email.
Another cleaner approach as @YourCommonSense suggested would be avoiding the loop like so:
$theEmail;
$emailsql = $conn->prepare("SELECT email FROM User WHERE email = ? limit 1;");
$emailsql->bind_param('s', $email);
$emailsql->execute();
$emailsql->bind_result($emailResult);
$emailsql->fetch();
printf($emailResult);
回答2:
There are two ways. Either that bind-result way explained in the other answer, or a conventional method of fetching a regular array
$stmt = $conn->prepare("SELECT 1 FROM User WHERE email = ?;");
$stmt->bind_param('s', $email);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_row();
$value = $row ? $row[0] : null;
Given all that, you may consider the how bad mysqli's usability is, compared to PDO:
$stmt = $conn->prepare("SELECT 1 FROM User WHERE email = ? limit 1;");
$stmt->execute([$email]);
$value = $stmt->fetchColumn();
来源:https://stackoverflow.com/questions/37116740/how-to-store-a-single-column-of-a-single-row-out-of-a-mysqli-prepared-statement