velkoon
velkoon

Reputation: 962

MySQLi - Get table value as string instead of object

I'm trying to use php to retrieve both the name and userEmail values from my Users MySQL table seen here: enter image description here

I'm using the following code in attempt to grab the currently logged-in user's name and userEmail:

<?php
session_start();
#connect to MySQL database
require_once("settings.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

#get username of current session
$username = $_SESSION['username'];

#get userEmail of logged-in user from database
$sql = "SELECT userEmail from Users WHERE username LIKE '{$username}' LIMIT 1";
$result = $mysqli->query($sql);
$replyTo = mysqli_fetch_field($result);

#get name of logged-in user from database
$sql2 = "SELECT name from Users WHERE username LIKE '{$username}' LIMIT 1";
$result2 = $mysqli->query($sql2);
$name = mysqli_fetch_field($result2);
?>

Then I try passing the $replyTo and $name values into a function that only accepts strings (the setFrom() function from PHPmailer to be precise):

$mail->setFrom($replyTo, $name);

...and get the following errors:

Warning: trim() expects parameter 1 to be string, object given in /var/www/phpmailer/class.phpmailer.php on line 489 (this object was $replyTo)

Catchable fatal error: Object of class stdClass could not be converted to string in /var/www/phpmailer/class.phpmailer.php on line 490 (this object was $name)

Using Chrome Logger to debug, I found these to be the values of $userEmail and $name:

enter image description here

Upvotes: 1

Views: 1122

Answers (1)

Veshraj Joshi
Veshraj Joshi

Reputation: 3579

I think you can get email and name with single query - make use of prepared statement for security reason(SQLIA)

#get userEmail of logged-in user from database
$sql = "SELECT userEmail,name from Users WHERE username = ? LIMIT 1";
// this is prepared statement and prevent form sql injection attack
$statement = $mysqli->prepare($sql);
$statement->bind_param('s',$username);
$statement->execute();
$result = $statement->get_result();
// fetch first record in associative array
$userDetail = $result->fetch_assoc();
if($userDetail)
{
   $replyTo = $userDetail['userEmail'];
   $name = $uerDetail['name'];
   $mail->setFrom($replyTo, $name);
}
else
{
   echo 'user not found';
}

Upvotes: 2

Related Questions