I'm trying to pull a field from a table in MySQLi witih a prepared statement in php, but I keep getting an empty result. I know the field is in the table, but nothing gets pulled. Here's my code:
if (!($stmt = $conn->prepare("SELECT password from members WHERE username = \"Bill\"")))
{
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->bind_result($result)){
echo "Bind failed";
}
$sql_searched_password = $result;
echo $sql_searched_password."
Calling $stmt->bind_result($result)
means that
result will be binded to
$result
variable.
See - will be binded
? bind_result
not fetches your rows from db. Fetching rows done with fetch
:
$stmt->bind_result($result);
while ($stmt->fetch()) {
$sql_searched_password = $result;
}
echo $sql_searched_password;
/* close statement */
$stmt->close();
Refer to manual .
You are forgetting to call ->fetch()
which is the command that pulls data from the result set into your bound variable.
You can also make your query easier to read and therefore debug, specially when the queries get more complex by using single quotes inside a double quoted string literal
if (!($stmt = $conn->prepare("SELECT password from members WHERE username = 'Bill'")))
{
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->bind_result($result)){
echo "Bind failed";
}
$stmt->fetch();
echo $result;
In fact the point of preparing a query is so that you can pass parameters to it after preparation, and possibly so you can call the prepared statement multiple times, with different parameters.
So this might be a better example
if (!($stmt = $conn->prepare("SELECT password from members WHERE username = ?")))
{
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->bind_param("s", 'Bill')) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->bind_result($result)){
echo "Bind failed";
}
$stmt->fetch();
echo $result;
// bind a new value to the existing prepared query
if (!$stmt->bind_param("s", 'William')) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->bind_result($result)){
echo "Bind failed";
}
$stmt->fetch();
echo $result;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.