问题
I usually use this code to read/get the result of an prepared MySQL SELECT:
$sqlname = $conn->prepare("SELECT name FROM test1 WHERE test2 = ?");
$sqlname->bind_param('s',$test);
$sqlname->execute();
$result = $sqlname->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$testname = $row['name'];
}
}
But when I know that there will only be one row in the result: Do I have to use a while loop with fetch_assoc anyway or is there a better way?
回答1:
When you know the name of the column that you are returning in the result set, you can bind the result to an output variable -- which makes things a little nicer to work with in my opinion.
if (!$stmt = $conn->prepare("SELECT name FROM test1 WHERE test2 = ?")) {
echo "Prepare Syntax Error"; // $conn->error
} elseif (!$stmt->bind_param("s", $test) || !$stmt->execute() || !$stmt->bind_result($name)) {
echo "Statement Error"; // $stmt->error
} else {
$stmt->fetch();
var_export($name); // this will show the value or NULL
}
Or if you don't want to bind the result value to a variable:
...
} elseif (!$stmt->bind_param("s", $test) || !$stmt->execute() || !$result = $stmt->get_result()) {
echo "Statement Error"; // $stmt->error
} elseif (!$row = $result->fetch_row()) { // No need to use assoc() keys
echo "empty result";
} else {
var_export($row[0]); // access the first column value
}
来源:https://stackoverflow.com/questions/52719594/best-way-to-get-result-of-prepared-mysql-statement-with-maximum-of-one-row