Quiz Approach in Codeigniter Gone wrong - php

Following this Question, im also creating an quiz approach in Codeigniter. here is the snippet of my code.
Controller :
function quiz(){
$this->load->model('belajar_model');
$data['data']=$this->belajar_model->quiz();
$this->load->view('quiz',$data);
}
function getQuiz($id){
$this->load->model('belajar_model');
$data['data']=$this->belajar_model->getQuiz($id);
$this->load->view('quiz',$data);
$this->load->model('belajar_model');
$data['data']=$this->belajar_model->quiz();
if($this->input->post()){
$jawab = $this->belajar_model->getQuiz($id);
$soal = $this->belajar_model->getQuiz($id);
if($jawab['benar']==$this->input->post('jawab')){
}
$data['jawab'] = $soal;
$data['next'] = $id+1;
$this->load->view('quiz', $data);
}
else{
$jawab = $this->belajar_model->getQuiz(1);
$data['soal'] = $soal;
$data['next'] = 2;
$this->load->view('quiz', $data);
}
}
and here is the model :
function quiz(){
//$this->db->where('id = 1');
$query = $this->db-> get('kuis');
return $query->result_array();
}
function getQuiz($data){
$this->db->where('id',$data);
$query = $this->db-> get('kuis');
return $query->result_array();
}
and here is the snippet of the view (my friend did the view) :
<h3>Pilihlah salah satu jawaban yang benar!</h3>
<?php foreach ($data as $list){
echo"<p>".$list['soal']."</p>";
echo"<table>
<tr><td><label><input type='radio' name='jawab' value='a'>".$list['ansA']."</label></td></tr>
<tr><td><label><input type='radio' name='jawab' value='b'>".$list['ansB']."</label></td></tr>
<tr><td><label><input type='radio' name='jawab' value='c'>".$list['ansC']."</label></td></tr>
<tr><td><label><input type='radio' name='jawab' value='d'>".$list['ansD']."</label></td></tr>
";
}?>
<tr><td><button type='submit' >Submit</button><td></tr><table>
after trying to implement it, with some modification make it work on the page, the page is jumbled like this, it's jumbled because the question and the answer is not displayed correctly. it also didn't receive the inputs from the quiz and there are some errors displayed.
my question is : where did it go wrong? is it from the view or either the models/controller not right? FYI, some of the attributes are written on my native language(Indonesian) to fulfill my studies, to make the code understandable to both my friend and my lecturer.
thanks for answering! it'll means a lot for me to get the webpage work because it's my final project and i didn't adapt enough (yet) in php and codeigniter.

Before going further, you should first clean your code to make sure you don't have any unforseable side effects:
In your getQuiz() method in your controller, you load your model two times and you also render the view twice. Once at the beginning and once after you checked the presence of $this->input->post().
PS for the mods: I know this is more comment material, but I can't comment yet.

Related

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();

codeigniter: I have rows in database (think like a blog post, title, postbody etc). What methods are there to present a form + save the submission?

Basically I am using codeigniter and have LOTS of fields in each row for a database table.
(for this example I'll pretend its a blog entry with just title/postbody but thats only to keep it simple)
I know i could manually code in something like this:
(psedudo code)
if (!$submitted) {
$data = get_existing_data_from_db();
$showform=true;
}
if ($submitted) {
if (process_and_save_data_if_all_valid_data()) {
echo "done";
}
else {
$data = get_data_from_submitted_data();
$showform=true;
}
}
if ($showform) {
echo "<form>";
echo "<input type='text' name='title' value='{$data->title}' />";
}
but is there any CI class or library that would let me do something more along the lines of this (again, pseudo code)
$fields_to_edit = array('title','postbody');
$this->form_helper->edit_table_with_fields('posts', $fields_to_edit);
and the form_helper thing would automatically validate (obviously id set the rules) + show the form to the user, and save it (update mysql) if all correct
does something like this exist for code igintor?
This form builder may make things easier for you. http://formigniter.org/
I think what you're looking for is a "codeigniter CRUD generator", just Google this and you will find quite a few. Picking one is up to you. Example 1, Example 2...

Removing article with ID from URL

Im building this blogg site and finally got everything considering uploading multiple pictures to one news article done.
Now my second step is to remove an article with following pictures to it.
Everything is set in the database so all i need is an ID from the news article.
When i press remove button on a article it shows the ID up in the URL... Im wondering how to get the specifik ID int from the URL and IF there is an smarter approach. It must be OOP and objectoriented apporach.
Code looks like this:
This is the looping out each article and notice $current_id that i put into a button to show in the url when its pressed
public function doOutputArticles($newsList, $pictureList)
{
$result = '';
foreach($newsList as $news)
{
$result .= '<ul>';
$current_id = $news->dbNewsID;
$result .= '<li class="bloggNewsHeader">'.$news->dbHeader.'</li>';
$result .= '<li class="bloggNews">'.$news->dbNews.'</li>';
$result .= '<li class="bloggNewsDate">'.$news->dbNewsDate.'</li>';
foreach($pictureList as $pic)
{
if($pic->dbNewsID == $current_id)
{
$result .= '<li class="bloggNewsPicID">'.$pic->dbPictureID.'</li>';
$result .= '<img class="bloggNewsPic" src="./images/'.$pic->dbPicture.'"alt="some_text">';
}
}
$result .= "
<form id='' method='get'>
<input type='hidden' name='$current_id'/>
<input type='submit' name='removeArticle' value='Ta bort inlägg' />
</form>";
$result .= '</ul>';
}
return "<div id='filesLoaded'>". $result ."</div>";
}
`
After this is done, i press a button to remove specific article and then the ID shows in the URL, now this method is meant to GET the specific INT/NUMBER ID in the URL but HOW?
public function GetSelectedID()
{
$ID = $_GET[self::$articleId];
echo $ID;
if(is_null($ID) || empty($ID))
{
return null;
}
else
{
echo $ID;
return $ID;
}
}
`
Kind regards /Haris
You don't really need a form, a simple link would do and be clearer. You should be using a different endpoint for deletion rather than looking for "removeArticle". This would be more OO since it would pave the path towards creating a specific Action Controller for each function rather than having one sprawling endpoint full of conditionals. Then you can have a consistent parameter (ideally within the URL path) of something like "articleId" that you are extracting from the URL. You'd also ideally want to redirect to the listing page upon completion to keep functionality focused in each method and also as a practice to avoid double posting issues (though this example is idempotent so it wouldn't be overly important).

symfony image inside a button?

I'm trying to include an image inside a button using symfony1.4 with this code:
<?php
echo button_to(image_tag('icon.png')."button_name",'url-goes-here');
?>
But the result i get, instead of what i want is a button with "img src=path/to/the/icon.png button_name" as the value of the button. I've google'd it long enought and found nothing, so i'll try asking here.
In other words:
i'd like to find the way to generate html similar to:<button><img src=..>Text</button> but with a symfony url associated in the onclick option
How can i do it to put an image inside a button with symfony? Am i using the helpers wrong?
Thank you for your time!
You are using Symfonys button_to function incorrectly. From the documentation:
string button_to($name, $internal_uri, $options) Creates an
button tag of the given name pointing to a routed URL
As far as I can tell, the button_to function does not allow for image buttons. Instead, you will probably create the button tag yourself and use symfonys routing to output the url.
I finally created my own helper to display this kind of buttons. I know is not very efficient and flexible but works in my case. Here is the code
function image_button_to($img,$name,$uri,$options){
$sfURL = url_for($uri);
$sfIMG = image_tag($img);
if(isset($options['confirm'])){
$confirm_text = $options['confirm'];
$jsFunction = 'if(confirm(\''.$confirm_text.'\')){ return window.location=\''.$sfURL.'\';}else{return false;}';
}else{
$jsFunction = 'window.location="'.$sfURL.'";';
}
$onclick = 'onclick="'.$jsFunction.'"';
if(isset($options['title'])){
$title = 'title=\''.$options['title'].'\' ';
}else{
$title = '';
}
if(isset($options['style'])){
$style = 'style=\''.$options['style'].'\' ';
}else{
$style = '';
}
return '<button type="button" '.$onclick.$title.$style.' >'.$sfIMG." ".$name.'</button>';
}
With this function as helper, in the templates i just have to:
<?php echo image_button_to('image.png',"button_name",'module/actionUri');?>
hope this be useful for someone ;)

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