Elaine Byene Elaine Byene - 3 months ago 16
PHP Question

Calling a PHP code within a single quote

I have an output like this in PHP. I want to show the

Username
but can't get it to work. How should I call the Username in the
$formLayout
so it reads something like:

Thank You Elaine Byrne for your submission
:

// Define the maximum number of submissions.
$max = 1;
// Get the current logged in user.
$user = JFactory::getUser();
// Get a database connection.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Setup the query.
$query->select('COUNT('.$db->qn('Username').')')
->from($db->qn('#__rsform_submissions'))
->where($db->qn('FormId').'='.$db->q($formId))
->where($db->qn('Username').'='.$db->q($user->get('username')));
// You can also count by User ID, just replace the above with:
// ->where($db->qn('UserId').'='.$db->q($user->get('id')));
$db->setQuery($query);
$counter = $db->loadResult();
if ($counter >= $max){
$formLayout = 'Thank You Username for your submission';
}

Answer

TL;DR

$formLayout = 'Thank You ' . $user->get('username') . ' for your submission';

LONGER VERSION

To chain strings PHP uses the . sign. It works with both double quotes " or single quotes '. The main difference between double and single quotes is that we can pass variables to the string without using the dot character to chain it tho the original string while with single quotes we always need to "break" the string and chain the variable in.

$addition = 'World';
$double_quotes = "Hello, $addition!";
$single_quotes = 'Hello, ' . $addition .'!';

echo $double_quotes; //echoes Hello, World!
echo $single_quotes; //echoes Hello, World!

as far as PHP functions, arrays or objects whether we use single or double quotes we are always required to use the dot character to chain the strings.

$addition = array('World', 'Tony', 'Elaine');

for($i=0;$i<count($addition);$i++)
{
    echo "Hello, " . $addition[$i] . "!<br>";
}

//echoes Hello, World!
//       Hello, Tony!
//       Hello, Elaine!

Hope it's clear enough :)

Comments