Using PHP have a MySQL statement into multiple PHP variables

Solution:
There are some issue with your code. At first glance, I was missing the PDO object. On closer inspection, I've noticed you were using the wrong concatenation operator and you didn't seem to use Prepared Statements either.
Prepared Statements will protect you from SQL injection as well as users using characters that might cause issues for your MySQL database. I've written the following code for you that shoul deal with all your issues. Please make sure to take a look at the comments inside:
<?php
session_start();
//Get Username
$username = $_SESSION['username'];
//MySQL Server Data
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//PDO Object
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
// Set PDO options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instance
try{
$pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
// Catch any errors
catch(PDOException $e){
print $e->getMessage();
exit;
}
try {
//Setup Query
$sql = "SELECT * FROM users WHERE username = :username";
//Prepare Query
$pdo->prepare($sql);
//Bind Values (to prevent SQL injection)
$pdo->bindParam(':username', $username);
//Execute Query
$pdo->execute();
//Fetch Data
$data = $pdo->fetch(PDO::FETCH_ASSOC);
//Combine results
$signature = $data['firstname']. " " .$data['lastname'];
echo $signature;
} catch (PDOException $e) {
print $e->getMessage();
exit;
}
?>
Answer
Solution:
Try this
$resultName = $connName->query($sqlName);
$signature = 'Created by : ';
foreach ($resultName as $row) {
$signature .= $row['firstname'] . ' ' . $row['lastname'];
}
echo $signature;
Answer
Solution:
$username = $_SESSION['username'];
$sqlName = "SELECT * FROM users WHERE username = $username";
$connName->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$resultName = $connName->query($sqlName);
foreach ($resultName as $row) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
}
$signature=$firstname.' '.$lastname;
Answer
Solution:
Unless your sample code up there was just some form of pseudo code, the concatenation operator in PHP is ".", not "+". Just use that to combine the 2 values returned into a variable:
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$signature = $firstname . ' ' . $lastname;
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xmlhttprequest error flutter
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.