Using PHP code in the value of a variable - php

I am trying to send an email in PHP where the content of the email has some conditional checks and some database query lookups.
What I would like to acheive is having my email code as a variable (similar to below) so that I can sent mail() the content to the relevant people.
$emailContent = "<p>My email content</p>";
However the value of this variable would have some code like this:
<table>
<?php
$get_course_units = "SELECT * FROM course_units where course_units.course_code = {$courseCodeExtract}";
$course_units_results = $conn->query($get_course_units);
if ($course_units_results->num_rows > 0) {
while ($courseUnits = $course_units_results->fetch_assoc()) {
?>
<tr>
<td><?php echo $courseUnits["unit_code"]; ?> – <?php echo $courseUnits["unit_name"]; ?> </td>
</tr>
<?php
} //end loop for course units
} //end if for course units
?>
</table>
How should I continue?

Split up your script into an html template file and your php logic.
Use shortcodes in your templates where you want to have custom information and then use str_replace to replace that content with the actual values.
$template_string = file_get_contents('myfile.html');
$shortcodes = array("{{FNAME}}","{{LNAME}}","{{OTHER_STUFF}}");
for(/* all the people you want to mail */){
$custom_info = get_custom_info(/* person */); //eg returns assoc array
$result = $template_string;
foreach($shortcodes as $code){
$result = str_replace($code, $custom_info[$code], $result);
}
//do what you want with result and mail it
}
In the example above, get_custom_info would be returning an associative array with the same values as the shortcodes array, just for convenience.
Now anywhere I put {{FNAME}} in my html, it will be replaced with the value I get back from the custom info function.
You can easily extend this to scrape the template and look for {{ and }} (or whatever shortcode syntax you want) anddetermine what variables you will need from your custom info, shaping the query to only give you what you actually need.
Not sure if this is the best way, but it seems to work pretty well. (also best way is subjective, so might want to ask questions a little differently)

Related

How to pass data in url format

I'm currently making a table where the email and phone number of clients are clickable. When you click it, it will redirect to another page and execute a filter search on that page.
I wanted to send the data of client email or phone number via the URL, but it seems you can only type in the exact filter search. I wanted when the user clicks a hyperlink it will send the clicked data via URL and execute the filter search.
<?php
foreach($checked_columns as $key=>$column){
if ($column){
if ($key == 'client_email'){?>
<td>
<?= $sale['client_email']; ?>
</td>
<?php } elseif ($key == 'client_phone_number') { ?>
<td>
<?= $sale['client_phone_number']; ?>
</td>
<?php } else {?>
<td><?= $sale[$key]; ?></td>
<?php }
}
}
?>
How can I change the last part of the URL so that it can search it via variable.
Your code can be refined/refactored to utilize the variable data.
foreach ($checked_columns as $key => $column) {
if ($column) {
echo "<td>";
if (in_array($key, ['client_email', 'client_phone_number'])) {
echo "{$sale[$key]}";
} else {
echo $sale[$key];
}
echo "</td>";
}
}
The $key value doesn't look like it needs to be encoded for insertion into the url, but the email seems like a good candidate.
By "staying in" php, I think you will find the snippet easier to read.
If I understand you correctly, currently you are outputting static text:
<a href="admin/sales/browse/confirmed-sale?fc=client_phone_number&fv=60192597698" class="style1">
And you want to output variables instead. Consider that you already have an example in your code of how to output the value from a variable:
<?= $sale['client_phone_number']; ?>
Simply apply that same exact operation for your URL. The only addition would be to ensure that you URL-encode the value, in case it has non-URL-friendly characters. Something like this:
<a href="admin/sales/browse/confirmed-sale?fc=client_phone_number&fv=<?= urlencode($sale['client_phone_number']); ?>" class="style1">
There are a variety of ways you can reorganize your code, perhaps putting the HTML into strings and using echo or perhaps applying a PHP templating engine to separate content from markup. How you organize it is really up to personal preference. But at its simplest, if you want to output a value then just output the value like you already do.

autocomplete shows all entries, Does not do any searching

Please help me ...
I'm a newbie! Please tell me what to do.
processed.php
<?php
include_once('../../dbConnect.inc.php');
$sql="SELECT name FROM artist";
$artist = select($sql);
disconnect();
$output_items = array();
while($row = mysql_fetch_array($artist))
{
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
?>
index.php
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#artist").autocomplete(
{
source: 'processed.php',
});
});
</script>
I have this problem: http://jsbin.com/alaci5
Autocomplete expects the source (when an URL is specified to filter out the results).
From documentation:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
So in your PHP code you have to do:
include_once('../../dbConnect.inc.php');
$sql="SELECT name FROM artist WHERE `name` like '%".mysql_real_escape_string($_GET['term'])."%'";
$artist = select($sql);
$output_items = array();
while($row = mysql_fetch_array($artist)) {
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
That autocomplete function is probably passing a few variables to your processed.php page.
Use var_dump($_GET) to see all the things you're being passed.
Inside one of those $_GET elements, you'll have the contents of the text box as they exist on the page. For the sake of demonstration, I'm going to use $_GET['text']. You'll need to find out which part holds the data you need.
What you'll need to do is search the database using this value for a list of results to return.
$sql="SELECT name FROM artist";
$artist = select($sql);
This is your script as it exists. What it may end up looking similar to is this.
$text_input = mysql_escape_string($_GET['text']);
$sql="SELECT name FROM artists WHERE name LIKE '%$text_input%'";
$artist = select($sql);
You'll want to get results that are similar to the inputted text on the user-facing page.
A few notes for you
I used mysql_escape_string() solely to may what you already have. While this does work (driving around a busted-ass chevy pacer works too, but there are much better ways though), its not recommended, which sets us up for point 2.
Using the old mysql extension is not really a good idea, its been replaced by mysqli, and PDO.
you'll need to escape your data, this is how its done with mysqli.

How to display results of a php method in an html page

I've built a contest system where users submit tickets then one is randomly chosen to win, and now I'm trying to figure out a way to display to users the tickets they have already submitted. Each ticket has an id, a date, and an invoicenumber. I want to display all the invoice numbers that a user has submitted so far.
Here is the method I have in my methods page. (I've organized my methods into one php file and then i just call them when needed.)
function GetSubmittedBallots()
{
if(!$this->CheckLogin())
{
$this->HandleError("Not logged in!");
return false;
}
$user_rec = array();
if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
{
return false;
}
$qry = "SELECT invoicenumber FROM entries WHERE user_id = '".$user_rec['id_user']."'";
$result = mysql_query($qry,$this->connection);
while($row = mysql_fetch_array($result))
{
echo $row['invoicenumber'];
}
}
and then on my html page that I want it to echo on, i just call it
<?php GetSubmittedBallots(); ?>
Sadly, this doesn't work. So my question is, how would i go about displaying the $row array on my html page?
<?php
require("methods.php"); // Include the file which has the "GetSubmittedBallots" function or method, if it's in a separate file
GetSubmittedBallots(); // Run the function / method
?>
If this doesn't work, please let us know any errors you receive.
Does it echo "Array"?
That's because you are trying to echo an array.
You should use something like print_r or var_dump, given that you are just trying to access the queried results. In my opinion the method should build a multidimensional array with the records, and then the template logic should loop through them and echo the values in a nice way. Be it a table or nicely arranged HTML.
If I'm not wrong, $this keyword is indicating you're in a class? If so, you need first to init that class and try to call GetSubmittedBallots function after init;
// assuming that class's name is Users
$users = new Users();
$users->GetSubmittedBallots();

Variable inside a php echo function

I have a php function which displays a rating bar with the arguments. I have a variable called itemID inside my php page which holds the unique item number. I need to send this value to my function and also echo command must stay. Is there a way to achieve this?
Here is the code, which does not work. When I try it on the server, it does not show the id of item, it prints the variable name as it is.
<?php echo rating_bar('$as',5) ?>
What I get at html file:
<div id="unit_long$as">
instead of the item id in place of $as.
Single Quotes do not support variable replace,
$as = "test";
echo '$as'; //$as in your end result
echo "$as"; // test in your end result
echo $as; // test in your end result
//For proper use
echo " ".$as." "; // test in your end result
Update for newer PHP versions you should now use Template Syntax
echo "{$as}"
If I get what you are saying, this is what you are asking.
<?php echo rating_bar($itemID,5); ?>
With the limited code you are providing, thats what looks like you are asking.

PHP Template system output

I'm using template system in php, so my code is like that for example...
$template->addVar ( 'thenameoftemplate', 'thenameofsubtemplate',"what to output");
And this code i output in the html file like... {thenamefsubtemplate}..
But i have a problem, when i try to output from database something with in the template like the above example but from database, it isn't working, only 1 output from the rows, but when echo it outside of the template it works..
I tryed to output with, foreach,while eaven with for from the database and output it in the template but it's showing just one result.
How to fix that, i wan't to row all the result and output them .
Update
Actualy i don't know what is the template system, some script was gaved to me and.. everythingwas ok until the database output..
Here is my last try with the for..
if (check_group_access_bool('show_admin_panel_button')) {
$template->addGlobalVar('admin','<BR>виж Ñмъкваните пеÑни<BR><img src="/images/icons/edit-user-32x32.png" hspace="2" alt="редактирай" align="absmiddle">редактирай');
}
$sudtwo = $_SESSION['user']['id'];
$fvsmt = mysql_query("select * from fav where user_id=$sudtwo");
if(isset($_SESSION['user']['id'])){
while($rowings = mysql_fetch_array($fvsmt)) {
$template->addVar( 'userprofile', 'userprofiletwo',"<tr><th nowrap valign=\"TOP\" align=\"LEFT\"> ñòèë: ".$rowings['name']." <form method=\"post\"><input type=\"submit\" value=\"premahni ot liubimi\" name=\"del\"></form>></th></tr>");
if(isset($_POST['del']))
{
mysql_query("DELETE FROM fav WHERE name_id=".$rowings['name_id']."");
}
echo"".$rowings['name']."<br>";
}
}
This is in the php and here is the HTML
<template:tmpl name="userprofile">
{USERPROFILETWO}
</template:tmpl>
That's how it outputs..
In the php code, where is my echo it works, but here in the html outputs only one row.
edit: OK, you're using something called patTemplate, which hasn't been updated in a few years. I found some documentation though, and once you've set up your PHP correctly, this in your html should work:
<table>
<patTemplate:tmpl name="userprofile">
{userprofiletwo}
</patTemplate:tmpl>
</table>
BUT, your PHP is a bit of a mess. What you have is basically:
for () {
$rowings = ...;
//you are overwriting the variable each time here
$template->addVar('userprofile', 'userprofiletwo', $rowings);
}
And I think what you want is something like:
$rowings = array();
for () {
// make an array of your data
$rowings[] = ...;
}
// and call addVar *once*
$template->addVar('userprofile', 'userprofiletwo', $rowings);
Now {userprofiletwo} is an array, and you can loop over that in your template.
Also, I'm not sure what the purpose of this bit of code is:
if(isset($_SESSION['user']['id'])){
}
as it doesn't really do anything...

Categories