How to echo with PHP this MySQL command - php

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

Related

Explode() String Breaking Array Into Too Many Elements

I am working on scraping and then parsing an HTML string to get the two URL parameters inside the href. After scraping the element I need, $description, the full string ready for parsing is:
<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>
Below I use the explode parameter to split the $description variable string based on the = delimiter. I then further explode based on the double quote delimiter.
Problem I need to solve: I want to only print the numbers for MeetingID parameter before the double quote, "773".
<?php
echo "Description is: " . htmlentities($description); // prints the string referenced above
$htarray = explode('=', $description); // explode the $description string which includes the link. ... then, find out where the MeetingID is located
echo $htarray[4] . "<br>"; // this will print the string which includes the meeting ID: "773">Description</a><br>"
$meetingID = $htarray[4];
echo "Meeting ID is " . substr($meetingID,0,3);
?>
The above echo statement using substr works to print the meeting ID, 773.
However, I want to make this bulletproof in the event MeetingID parameter exceeds 999, then we would need 4 characters. So that's why I want to delimit it by the double quotes, so it prints all numbers before the double quotes.
I try below to isolate all of the amount before the double quotes... but it isn't seeming to work correctly yet.
<?php
$htarray = explode('"', $meetingID); // split the $meetingID string based on the " delimiter
echo "Meeting ID0 is " . $meetingID[0] ; // this prints just the first number, 7
echo "Meeting ID1 is " . $meetingID[1] ; // this prints just the second number, 7
echo "Meeting ID2 is " . $meetingID[2] ; // this prints just the third number, 3
?>
Question, why is the array $meetingID[0] not printing the THREE numbers before the delimiter, ", but rather just printing a single number? If the explode function works properly, shouldn't it be splitting the string referenced above based on the double quotes, into just two elements? The string is
"773">Description</a><br>"
So I can't understand why when echoing after the explode with double quote delimiter, it's only printing one number at a time..
The reason you're getting the wrong response is because you're using the wrong variable.
$htarray = explode('"', $meetingID);
echo "Meeting ID0 is " . $meetingID[0] ; // this prints just the first number, 7
echo "Meeting ID1 is " . $meetingID[1] ; // this prints just the second number, 7
echo "Meeting ID2 is " . $meetingID[2] ; // this prints just the third number, 3
echo "Meeting ID is " . $htarray[0] ; // this prints 773
There's an easier way to do this though, using regular expressions:
$description = '<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>';
$meetingID = "Not found";
if (preg_match('/MeetingID=([0-9]+)/', $description, $matches)) {
$meetingID = $matches[1];
}
echo "Meeting ID is " . $meetingID;
// this prints 773 or Not found if $description does not contain a (numeric) MeetingID value
There is a very easy way to do it:
Your Str:
$str ='<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>';
Make substr:
$params = substr( $str, strpos( $str, 'ItemID'), strpos( $str, '">') - strpos( $str, 'ItemID') );
You will get substr like this :
ItemID=18833&MeetingID=773
Now do whatever you want to do!

Echo text including double quotes in PHP

I have a $_GET[q] from the URL. I am trying to ECHO the search term back into the search box. Sometimes people might submit queries encapsulated in quotes and in these cases the ECHO interprets the search term
ECHO $_GET[q];
as:
ECHO ""search term"";
and as a result I get a blank search box. Search queries with a single quote, like: Peter's house, work fine.
When I use:
mysqli_real_escape_string($conn, $_GET[q])
I only get a backslash in the search box.
How could I populate the search box with a search term encapsulated in double quotes?
You could also use:
echo str_replace('"','',$_GET[q]);
This will of course remove all double quotes, so if they may be valid somewhere in the search term then better might be:
echo str_replace('"','"',$_GET[q]);
Haven't tested this but this might also work:
echo html_entity_decode(htmlentities($_GET[q))
You could use addslashes
like this:
$t = 'peter "pan"';
echo addslashes($t); // outputs: peter \"pan\"
You can try:
$str = "Hello World!";
echo $str . "<br>";
echo chop($str,"");
Ouptput:
Hello World
Explanation:
The chop() function, helps you chop off the quotes anyone might add to string.
You can manipulate as appropriate for your code.
$str = preg_replace( '["|\']','', $_REQUEST['q'] );
echo( $str ); //no double, no single quotes, faster than str_replace when you have to make more than 1 call to str_replace
or...
$str = str_replace( '"','', $_REQUEST['q'] ); //no double quotes, faster than preg_replace when you only make one call to str_replace
echo( $str ); //no double quotes

Replacing array string values which contains multiple special characters in php

I would like to replace array string values which contains multiple special characters to normal one.
Tried Code (array values):
$data['ENV_TEST'] = "rambo";
$data['ENV_DEV'] = "Project Bribara<"${ENV_TEST}"#gmail.com>"
echo str_replace("${ENV_TEST}", $data['ENV_DEV'], $data['ENV_DEV']);
also tried
echo str_replace("\"${ENV_TEST}\"", $data['ENV_DEV'], $data['ENV_DEV']);
Expected:
"Project Bribara<rambo#gmail.com>"
Actual:
"Project Bribara<"${ENV_TEST}"#gmail.com>"
How can I get the expected output?
You should on PHP strings sometime. The important part about double quoted strings for your question is that you need to put a backslash before every $ and every " inside your string. Your code will then look like this:
$data['ENV_TEST'] = "rambo";
$data['ENV_DEV'] = "Project Bribara<\"\${ENV_TEST}\"#gmail.com>";
echo str_replace("\${ENV_TEST}", $data['ENV_TEST'], $data['ENV_DEV']);
//also tried
echo "\n\n";
echo str_replace("\"\${ENV_TEST}\"", $data['ENV_TEST'], $data['ENV_DEV']);
If you use single quoted strings you don't need to escape $ (see the manual), and instead of \", you would need to escape single quotes (but there aren't any in your example).
$data['ENV_TEST'] = "rambo";
$data['ENV_DEV'] = 'Project Bribara<"${ENV_TEST}"#gmail.com>';
echo str_replace("\${ENV_TEST}", $data['ENV_TEST'], $data['ENV_DEV']);
//also tried
echo "\n\n";
echo str_replace('"${ENV_TEST}"', $data['ENV_TEST'], $data['ENV_DEV']);
I also fixed a missing semicolon and replaced DEV with TEST in one place.
String concatenation in PHP is done through the . operator. Your code would be:
$data['ENV_DEV'] = "Project Bribara<".$data['ENV_TEST']."#gmail.com>"

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

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.

Categories