CCM Fabian CCM Fabian - 7 months ago 15
PHP Question

How to store a single column of a single row out of a MySQLi prepared statement in a PHP variable?

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.

Answer

You need to add to your code the binding of the result to a specific variable

$emailsql->bind_result($emailResult);  

And the result it will be always an array, in this case its length is 1 but it doesn't matter, 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.

Hope this helps you