Calling a PHP code within a single quote - php

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';
}

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 :)

Related

How to preserve single and double quotes in a link using REGEX?

I have a regex code which finds all URLs and replaces them with a HTML link. Here is my code:
// initializing
$str = "this is a good website www.example.com/classname/methodname/arg";
$rexProtocol = '(https?://)?';
$rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]+?)?';
function callback($match){
// Prepend http:// if no protocol specified
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
$DetectProperName = strlen($match[2].$match[3].$match[4]) > 20 ? "...".substr($match[2].$match[3].$match[4],0,20) : $match[2].$match[3].$match[4];
return ''.$DetectProperName. '';
}
echo $str = preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",'callback', htmlspecialchars($str));
Also here is the output:
this is a good website ...www.example.com/clas
Also here is a fiddle
Well, that's ok and it works as well for links. Now my question is about when input is containing a quote ' or ". That regex will add a \ next to it. How can I fix it? I want such a regex be not sensitive to quotes.
Here is an example:
Input:
$str = 'this is a " (quote)';
Current Output:
this is a \" (quote)
What I want:
this is a " (quote)
How can I do that?
Edit: According to some tests, I figured out that change single/double quotes to ASKII code. How can I prevent it?

echo php variable and html in Wordpress

I am playing around with wordpress and wondering, why this line of code works:
echo "<a href='....'>$name</a>";
I learned it this way:
echo "<a href='....'>".$name."</a>";
Is there something special defined in WP to make this work?
In PHP, there are two types of String.
The first type uses the single quotes, as follows.
$val = 'this is a simple string';
The second type is as follows:
$val = "This is a not so simple string";
With the latter type, any variables included in the string will be resolved to their values, so:
$val = "Hello there";
$message = 'Dave says $val';
// Literally equals: Dave says $val
$message2 = "Dave says $val";
// Literally equals: Dave says Hello there
There are lots of other differences, which you can read about here.

Issues while using Quotes in PHP

I have Learnt that Quotes doesn't matter in PHP.
But in the following code, if I try to use single quotes in eval(); I get error, on the other hand code works fine with Double Quotes.
$a = '2';
$b = '3';
$c = '$a+$b';
echo $c.'<br/>';
eval("\$c = \"$c\";");
//eval('\$c = \'$c\';'); //Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
echo $c;
PHP.net says that escape sequences are not expanded when using single quotes.
Quotes do matter ;-)
<?php
$color = "red";
echo "My car is $color"; // Outputs "My car is red"
echo 'My car is $color'; // Outputs "My car is $color"
?>
Unlike double quotes, PHP does not parse variables in single quotes.
Example:
$name = 'John';
echo 'hello $name'; // hello $name
echo "hello $name"; // hello John
More Information
FYI, it isn't good idea to use eval in production environment for security reasons.
Using eval is a bad idea but if you are doing this for learning purpose then the correct way is
eval("\$c = \$c;");
.
don't use eval and update your string-quoting skills here:
The following example was lifted from: The PHP Manual
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

What is the difference between double and single quotes in PHP? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between single quote and double quote string in php
I am new to PHP and in programming i have seen use of both "" and ' '.
What is the difference between "" and ' '?
And in declaring a link i have used the following ,but it does not seem to work there must be something wrong in quotation:
$abc_output .='' Back to Main Menu'';
echo $abc_output;
What might be the error here?
You want to keep the text inside of your string:
$abc_output .='Back to Main Menu';
The difference between ' and " is that you can embed variables inside of a double quoted string.
For example:
$name = 'John';
$sentence = "$name just left"; // John just left
If you were to use single quotes, then you'd have to concatenate:
$name = 'John';
$sentence = $name.' just left'; // John just left
PS: Don't forget that you always have to escape your quotes. The following 2 are the same:
$double = "I'm going out"; // I'm going out
$single = 'I\'m going out'; // I'm going out
Same applies the other way around:
$single = 'I said "Get out!!"'; // I said "Get out!!"
$double = "I said \"Get out!!\""; // I said "Get out!!"
Double quotes allow additional expressions, such as "$variable \n", which single quotes don't. Compare:
$variable = 42;
echo "double: $variable,\n 43\n";
echo 'single: $variable,\n 43';
This outputs:
double: 42,
43
single: $variable,\n 43
For more information, refer to the official documentation.
Text in double quotes are parsed.
For example:
$test = 'something';
print('This is $test');
print("This is $something");
would result in:
This is $test
This is something
If you don't need the string to be parsed you should use single quotes since it's better performance wise.
In your case you need to do:
$abc_output .='Back to Main Menu';
echo $abc_output;
Or you will get an error.
The Back to Main Menu wasn't in the string.

How to echo with PHP this MySQL command

The following code gives me the following:
$getexpenses = "SELECT sum(expense_amount) FROM projects_expense WHERE project_id=$project_id";
$showexpenses = #mysqli_query ($dbc, $getexpenses); // Run the query.
echo ' . $showexpenses . ';
Gives me a result of
' . $showexpenses . '
instead of the actual sum...
I'm sure it's something simple I'm missing... thanks!
echo " . $showexpenses . " will work for you. You need double quotes, not single.
I added a call to mysqli_fetch_assoc($showexpenses)to make it fully functional.
I also sanitized $project_id to avoid injections and used an alias to make the sum accessible through an associative array.
$getexpenses = "SELECT SUM(`expense_amount`) as `sum_amount` FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_assoc($showexpenses);
$sum = $sums['sum_amount'];
echo $sum;
We could also have used mysqli_fetch_row like this:
$getexpenses = "SELECT SUM(`expense_amount`) FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_row($showexpenses);
$sum = $sums[0];
echo $sum;
The alias is not needed anymore since we know the first column (0) is a match.
NB: you probably also need to GROUP BY project_id if you want to use SUM()
use
echo $showexpenses;
or
echo "My query is: {$showexpenses}";
Further to Nik's response, PHP treats strings differently based on whether you use Single Quotes or Double Quotes around them.
Single-Quotes interpret text as literal text except for '\'' which would output a single quote mark and '\' which would output a slash mark. For this reason, using single quotes would output your variable name instead of the value.
Examples:
CODE | OUTPUT
-----------------+------------------
echo '\t'; | \t
echo '\r'; | \r
echo '$foo'; | $foo
Double-Quotes interpret certain escape sequences for special characters and also interpret variables. For instance, "\n" ouputs a linefeed and "\r" outputs a carriage return. For this reason, echoing "$myvariable" outputs the value instead of the variable name.
Examples:
CODE | OUTPUT
-----------------+------------------
echo "\t"; | {tab space}
echo "\r"; | {carriage return}
echo "$foo"; | bar
More reading: http://www.php.net/manual/en/language.types.string.php

Categories