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.
Related
My problem is that I need to save a value from the link as a variable which will then do something. Below is my main code for this problem.
<table>
<? foreach ($csv as $row) : ?>
<tr>
<td><? echo $row[0]; ?></td>
</tr>
<? endforeach; ?>
</table>
Basically, it prints the first column from my array $csv. However I want to save the '$row[0]' for each link - depending on which one is clicked.
This happens here:
<?php
if (isset($_GET['GoToProfile'])) {
}
?>
This works. E.g. when something is clicked it prints something. But I cannot find a way to save the values from each link. Depending on which one is clicked. I have tried many different methods online, but none seem to work.
I have even tried:
<? echo $row[0]; ?>
Any help would be greatly appreciated.
Thanks!
Use an ampersand (&) instead of a question mark
<? echo $row[0]; ?>
The ? indicates the beginning of the query string, which is the data sent on a GET request. In most cases it is a collection of name/value pairs, separated with & s.
A simple example of a GET request
http://example.com?first=1&second=fifty
You would get the value of the parameters in PHP with $_GET
$first = $_GET['first'];
$second = $_GET['second'];
To see what the server is receiving, you can use var_dump
var_dump($_GET)
I am new to MVC & codeigniter and want to know whether its okay to have following types of code in view files
if(strcasecmp($_SESSION['role'],'author')==0)
{
some code
}
or
if($this->session->flashdata('edition_done_by'))
{
some code
}
i.e. checking existence of a session object or flashdata in a view file
Also,I would want to know whether creating table rows dynamically in a view file using foreach loop construct(like given below) is alright as per MVC
<?php foreach($items as $item){ ?>
<tr>
<td><?php echo $item->name; ?> </td>
<td><?php echo $item->price; ?> </td>
</tr>
<?php } ?>
Its not a good practice to check session values within the view. Check it within controller and pass the relevant data to view
It goes completely against the idea of the Model-View-Controller principe.
In (really) short; the model is responsible for managing data entities, CRUD operations, how a data entity should look like, etc. The controller is responsible for any business logic. Which means; when should I update a record, should this data be available to user x, etc. The view is merely responsible for displaying data that is already available. Nothing more, nothing less.
So in your example; the Controller should check session data, flash data, whatever, and send the processed data to the view. Eg:
if( strcasecmp($_SESSION['role'],'author') === 0 )
{
$can_edit = true;
$message = 'You can edit! Go ahead';
} else {
$can_edit = false;
$message = 'You do not have sufficient rights to edit this entity';
}
Now pass these variables to the view, there you can do something like:
<?php if ( $can_edit ): ?>
<form action="POST">
<p><?php echo $message; ?></p>
<textarea name="content"><?php echo $entity->content; ?></textarea>
<button type="submit">Update</button>
</form>
<?php else: ?>
<p><?php echo $message; ?>
<?php endif; ?>
One Word Answer is Yes! No Problem
It is fine to access Session Variables in Views . Session are variable to store information.
As Long as you are not putting Business Logic Inside Your View . you can use anything in views . The Case you mentioned you are using is What I will call "Display Logic" that is used to check which / What /From Where/ How content will be shown .
From Two Code Samples you Show Following One is Correct to Use with MVC
if($this->session->flashdata('edition_done_by'))
{
some code
}
You For Loop Code is also having no problem with MVC
I'm trying to write a web application in which students enter their timetable. For example: First period of Monday is math, second period of Monday is English,... first period of Tuesday is history, second period of Tuesday is biology,... etc.
So I write a form like this:
<form method="post" action="timetable_handling.php">
<?php
for ($period=1;$period<=9;$period++)
{
echo "<tr>";
for ($day=1;$day<=7;$day++)
{
echo "<td><input name="the_subject_of_the_nth_$period_on_$day" type="text"></td></tr>";
//the problem is here
}
}
?>
</form>
So my question is, are there any ways to pass the many variables to another php file to handle without having to manually write its name explicitly?
Edit 1: I mean is there anyway to encode the period and day information in the name, so that when it sends to timetable_handling.php I can just loop through it to save it into sql database. Something like an array $subject[day][period].
I would be grateful if someone could help me.
Start with the following on your timetable data entry page:
<form method="post" action="timetable_handling.php">
<table>
<?php
for ($period=1; $period<=9; $period++)
{
echo '<tr>';
for ($day=1; $day<=7; $day++)
{
echo '<td><input name="subject_of_period_'.$period.'_on_day_'.$day.'" type="text"></td>';
//the problem is here
}
echo '</tr>';
}
?>
</table>
<input type="submit" value="Submit Form" />
</form>
Then follow up with this script on your timetable_handling.php:
<?php
for ($day=1; $day<=7; $day++)
{
for ($period=1; $period<=9; $period++ )
{
${'subject_of_period_'.$period.'_on_day_'.$day} = htmlspecialchars($_POST['subject_of_period_'.$period.'_on_day_'.$day],ENT_QUOTES);
echo '<p>Subject of Period '.$period.' on Day '.$day.' is '.${'subject_of_period_'.$period.'_on_day_'.$day}.'</p>';
}
}
?>
It's secure and it works.
Yes. If you format a variable name something like
for ($day=1;$day<=7;$day++)
{ ?>
<td><input name="subject['<?= $period ?>'][<?= $day ?>]" type="text"></td></tr>
//the problem is here
<?php }
PHP will turn $_POST['subject'] into a 2D array for you. (Note I make no promise this is free of syntax errors.)
In the form handler you can loop through all the posted fields like this:
foreach($_POST as $field => $value)
{
}
Where $field would be the input-tag name and $value it's value.
If you have other form elements you can check which ones you need with some kind of prefix, like if the fieldname starts with 'the_subject', you know it's one of the fields that were dynamically added.
sure, you already did part of the answer :)
first issue: you are not escaping your string properly:
Here is 1 another way
echo '<td><input name="'.$period.'_on_'.$day.'" type="text"></td></tr>';
As for handling the post here is what you can do. You might need to tweak it around to get the exact desired result. But you are talking about multidimentional array.
if (isset($_POST)){
$something=array();
foreach ($_POST as $single=>$value)
{
array_push($something, array('period_'.substr($single,0,1) => array('day_'.substr($single,-1)=>$value)));
}
}
echo '<pre>'.print_r($something,true).'</pre>';
Good Luck.
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)
I am trying to build a db driven web site in which the user selects from a drop down menu a
value and some Information from a database are returned. I use an ajax post cause i dont want the page to get refreshed:
$("#button").click(function(){
var datastr = ($('#act').val());
var datastr1 = ($('#loc').val());
$.ajax({
type:'POST',
url:'activities_code.php',
data: {datastr:datastr, datastr1:datastr1},
success:function(response){
$("#msg").html(response);
} });});
In the url parameter I have the following php file (this is a part of the php file):
$query = "SELECT PK,title,Information from activities where Activities='$category'";
$result = mysqli_query($dbcon, $query) or die('no available data');
echo "<table>";
$num_results = 0;
$t = 0; //title counter for the id of each title
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Here the columns of title and information are printed
echo "<tr><td>";
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
echo "<br>";
echo $x = $row['PK'];
echo "</td></tr>";
echo "<tr><td>";
echo $row['Information'];
echo "</td></tr>";
// Here I sum up the number of the results
$num_results=$num_results+1;
$t = $t+1;
}
}
As you can see, I have a while loop in which I echo each time a link with an id:
"<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
What I want to do is to use this id of each link later in my code by doing something like this:
document.getElementById("t1").value
My question is, how can I return this id's to the client side? I think I should write something in the success function but I have no idea what.
If you dont understand some part of the code or I didn't explain everything clear, please ask me.
Thanks
D.
This is what I get when I alert(response) in the success function.
<!DOCTYPE HTML>
<table id="container"><tr><td><a href='test.php' id="t0" target="_new" class='pickanchor'>Rafting in Voidomatis</a><br>1</td></tr><tr><td>
<img src="m.jpg" class="textwrap" height="120px" width="120px">
<p style="text-align:left;">Our experienced rafting instructors will show you the best way to enjoy Voidomatis, the river with the most clear waters inSouth Europe. You can also cross the Vikos Gorge by following Voidomatis river in an attractive one and a half hour long walk. Alternatively you can ask for the more demanding Aoos river rafting.</p>
<br>
<br>
<hr></td></tr><tr><td><a href='test.php' id="t1" target="_new" class='pickanchor'>Rafting in Lousios</a><br>4</td></tr><tr><td><img src="raf.jpg" class="textwrap" height="120" width="120">
<p>You will be surprised to know that Greece hides numerous, densely vegetated rivers offering amazing rafting opportunities. In the whole mainland, there is a company base awaiting you, for an amazing � off the beaten track experience!</p>
<br>
<br>
<br>
<hr></td></tr><div id="r2" align="center" id="result_2">2 results for rafting were found!
</div></table> <!-- End of PHP code-->
First, There is problem with ID of your anchor tag. here is correction
"<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Second, Give id to your table like
<table id="container">
Third, give class to your anchor tag.
"<a href='test.php' class='pickanchor' id=\"t.$t\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Now write following code into your success handle after .html() statement
NEW EDIT
$("a.pickanchor").each(function(i){
alert(this.id);
});
In line you presentd you made mistake. In wrong place you have added ".
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
It should be
echo "<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
As simplest solution you could add after the while loop
echo "<script> my_max_id_num=$t </script>"
This will give you knowledge about which ids are present on page. This should give your js script access to my_max_id_num variable. It's not considered best programming practice but is simple.
Second (better) way of solving problem could be returning json instead of html and rewriting your success method. This will be more work to be done:
Rewrite while loop so it returns something like:
{ "data":[
...
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
...
]}
Rewrite your ajax query so it will accept json, and rewrite success method so it will create your links on basis off data returned from server.
This way you will have both, ids and your links in one query. What's more in case of changing requirements it will be easier.
The simplest solution would be to give your elements a class, that way you don't need to select based on the elements id, but you can access it easily:
eg.
test 0
test 1
$('#msg').on('click', '.className', function() {
console.log(this.id);
});
I don't have enough rep points to ask for clarification, but what do you mean by 'return this id's to the client side'? Also what would the 'value' of the element 't1' be?
Lets say you wanted to get the link location it could be something like:
var value = $('#addButton').attr('href');
and then do something with the value (not sure what you mean by 'return this id's to the client side') but perhaps you want the value then to be visible to the client?
So if you have a div somewhere on the page where you want it to show you could populate it with you value, maybe something like:
HTML
<div id="valueBox"></div>
jQuery
$("#valueBox").html(value);