Let's say I have 3 columns/divs/sections in my html layout, let's call them cat1, cat2, cat3. Then I have a database with a table called "Content". In that table I have the fields id, title, content, category.
Now I want to populate those 3 columns with their corresponding content from my mysql table. For example - get all the content from table where category = cat1(corresponding to the first column).
I could just make 3 functions that each have their own parameter, but I don't want to repeat code. How can I do this with a single function, but just using a different parameter?
I was thinking something like this:
public function displayAll_with_category ($category) {
$sql = $con->prepare("SELECT * FROM Table WHERE Category=?");
$sql->bindParam(1, $category);
$sql->execute();
while ($row = $sql->fetch()) {
echo $row['Title'];
}
}
Then in my HTML:
<div id="cat1">
// Using a central class
<?php include('class.php'); $obj = new handler; $obj->displayAll_with_category(); ?>
</div>
So far so good, I need to somehow be able to alter the $category parameter so I can use the same function to call the contents for cat1/2/3. I have no idea how to do that, usually I need to send something to the PHP function via a button or form, but this time that's not the case. Is this even doable in pure PHP? I can think of doing this with AJAX, but for now I want to know if it can be done with PHP.
I'm not sure if this is what you want.
This would get you the data for category 1, 2 and 3.
I just created a loop in the view to call the function with different parameters:
<?php
for($cont = 0; $cont<4; $cont++){
?>
<div id="cat1">
// Using a central class
<?php include('class.php'); $obj = new handler; $obj->displayAll_with_category($cont); ?>
</div>
<?php
}
?>
Oh and if I were you i would try to separate the logic from the view and I will print the result of the function in the view instead of doing it inside it.
Related
I am new to codeigniter. I have successfully stored the data to database from view. Now thing is i want to retrieve the data from database and show it in the view. Anyone can help from another link or atleast tell me the flow of passing the data. I m working on a form with text fields and buttons
To retrieve the rows in questions, you want to do something like this:
$data['rows'] = $this->db->get_where('table_name')->result();
And then pass this variable to your view:
$this->load->view('index', isset($data)?$data:'');
And then access it:
var_dump($rows);
Here is an example of one of mine
Controller
$data['title'] = "title";
$this->db->select("title, content, date")->from("posts")->where('parent', $parent)->where('status', 'publish')->order_by("id", "asc");
$query = $this->db->get();
if($query->result()){
$data["mainContent"] = $query->result();
}
$this->load->view("pages/header/head", $data); //this sends the mysql to the page
$this->load->view("pages/van");
$this->load->view("pages/footer/footer");
View (this is for an unordered list
<?php foreach($mainContent as $row):?> Note maincontent above as well.
<ul>
<li> <?php echo $row->title;?></li>
<li> <?php echo $row->content;?></ul>
</ul>
<?php endforeach;?>
You would do the same for tables, or posts or whatever. The foreach will echo data until it runs out
With help from #teresko I've managed to create dynamic pages (& their urls) for my site using the loop below. My problem is how do i get the newly created page at ahref to combine data I have in database with the template (which I already have ready), so that when the user clicks on it, she/he goes to the page populated with the data. Am i supposed to use a javascript click function (would rather not). How would i do it with php and html?
Here is the loop generating the URLs:
<?php foreach ($reciperow as $recipe) { ?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php } ?>
Would really appreciate a solution that stays clear of routing, since my site's a basic project and I plan to get to MVC and PHP routing in the next projects. Thanks.
If you meant How, when user clicks generated link, show him page with data from database accordingly to "id" he/she selected, then do the following:
<?php
$id = intval($_REQUEST['id']);
if ($id) { // user get here by clicking on link with id
$data = ... // fetch data from database
?>
<sometag>Some data from database:<?php echo $data['somecollumn']; ?></sometag>
...
<?php
} else {
// user just opened first page
// generate links list as usual
...
foreach ($reciperow as $recipe) {
?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php
}
...
}
?>
Edit:
Is this how it is normally done for simple sites?
Depends.
If you has only one entity in datadabe, then there will be no arguments clash, id is identifier only for recipies, but if you intent to show also details for, f.e. ingredients, furniture and/or more, then you must add specificators.
Like, links will look like
<a href="?show=recipie&id=<?php echo $recipe['uniqno'];?>">
<a href="?show=ingredient&id=<?php echo $ingredients['id'];?>">
... and then data must be fetched and displayed correspondingly:
$id = ...;
if ($id)
switch ($_REQUEST['show']) {
case 'recipie':
// show recipie data
break;
case 'ingredient':
// show ingredient data
break;
case ...
default:
// show start page
}
But with addition of another entities yours .php file will grow. Another solution will be to add separate scripts for handling each entity:
// generate links list as usual
...
foreach ($reciperow as $recipe) { // look at `recipie.php` portion of link's href
?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php
}
And add recipie.php file in the same folder as base script with following contents:
<?php
$id = intval($_REQUEST['id']);
if ($id) { // user get here by clicking on link with id
$data = ... // fetch data from database
?>
<sometag>Some data from database:<?php echo $data['somecollumn']; ?></sometag>
...
<?php
} else {
?>
<h1 class="error">No recipie ID specified</h1>
<?php
}
<?
Further exploring will bring you to concepts of MVC and routing via human-friendly-links format, when links looks like /home, /recipie/12 and/or /recipie/?id=12 or even /recipie/12-cream-pie. But that's story for another time...
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)
Thanks for taking time to look at this.
I have two drop down menus. The first is a list of clients, the second is a list of projects.
All projects are tied to just one client, so I'd like for the code to get user input for the client, then read that value, and modify the PHP code to only print out the values in the second drop down menu that correspond to the client selected.
Here's some code. For the first drop down menu:
<div class="item">
<label for='clSel' id='tsClLabel'>Client:</label>
<select name='clSel' id='wClient' onChange="bGroup();">
<option></option>
<?php
$cQuery = "SELECT * FROM Clients ORDER BY Client_Name";
$cResult = mysql_query($cQuery);
while($cData = mysql_fetch_assoc($cResult)) {
echo '<option id="Cid" value="'.$cData['Id'].'">'.$cData['Client_Name'].'</option>';
}
?>
</select>
Here's my jQuery function to get the user-selected value from the first drop down:
<script>
function bGroup(){
val1 = $("#wClient").val();
// window.alert(val1);
// $('#div1').html(val1);
return val1;
}
</script>
And the code for the second drop down menu:
<label for='billGroupId'>Billing Group: </label>
<select name='billGroupId'>
<option value=''></option>
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
echo "<option value='".$row['Id']."' > ".$row['Name']."</option>";
echo "<script> bGroup(); </script>"
}
}
?>
</select>
I know I need to include a WHERE statement in the second drop down menu
Basically Select * FROM Clients WHERE Client_ID == $jsVAR.
I already have the value I need in the var1 JavaScript variable. How can I get this little piece of data either read by PHP or sent to PHP via JS code?
Thanks!!
You can SELECT all records from the database, and then insert them to your page HTML using json_encode(). Something like that:
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
$projectData = array();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
$projectData[$row['Client_Id']][] = $row;
}
}
echo '<script type="text/javascript">var projects=', json_encode($projectData), ';</script>';
?>
Then, in your JS, you use the variable projects as an associative array (object), eg.:
<script type="text/javascript">
for (p in projects[clientId]) {
alert(projects[p].Name);
}
</script>
Tricky one,
You have a choice. One way is to use Ajax to grab the second level menu structure upon getting the first level choice, and populate the second level once that succeeds. That's likely to be a problem, as there will likely be some sort of network delay while that happens, of which you have no control (unless you are in a closed environment). So from a user point of view it could be counter intuitive and sluggish feeling, especially on a slow connection or shared hosting solution where timings can vary enormously.
The other way is to somehow pull all values possible and filter them (so hide the ones that don't apply) using jQuery, perhaps utilising classes or some other attribute as a method of filtering data. Using jQuery you can assign data to elements so you could also use that too. The second method may not be so good if there's a lot of data (can't tell from the scenario you've described). Looking at your second level code I don't see a WHERE condition so I'm not sure how the value from the first level is affecting that of the second level, so it's hard to know how to deal with that for this method.
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();