ILovephp123 ILovephp123 - 6 months ago 10
SQL Question

Not sure how to echo out the Selected data from mysql

$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if ($stmt->affected_rows > 0) {
echo "Exists";
}


Instead of echoing out
Exists
, I want it to echo out
nameData
. How can I go about doing that?

Answer

First of all, if you want only one row then append LIMIT 1 to your SELECT query, like this:

$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");

So there are two approaches to display nameData:

Method(1):

First bind the variable $nameData to the prepared statement, and then fetch the result into this bound variable.

$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
    $stmt->bind_result($nameData);
    $stmt->fetch();
    echo $nameData;
}else{
    echo "No result found";
}

Method(2):

First use get_result() method to get the result set from the prepared statement, and then use fetch_array to fetch the result row from the result set.

$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
    $row = $result->fetch_array()
    echo $row['nameData'];
}else{
    echo "No result found";
}