Code igniter shopping cart joining and selecting from multiple tables - php

I'm learning code igniter and I'm currently trying to create a shopping cart that works over multiple tables. I can make it so it works using 1 table but when I try the JOIN method it always gives "Product does not exist".
The model I'm using is:
class Cart_model extends CI_Model {
function tvs(){
$query = $this->db->get('tvs');
return $query->result_array();
}
function computers(){
$query = $this->db->get('computers');
return $query->result_array();
}
function laptops(){
$query = $this->db->get('laptops');
return $query->result_array();
}
function validate_update_cart(){
$total = $this->cart->total_items();
$item = $this->input->post('rowid');
$qty = $this->input->post('qty');
for($i=0;$i < count($item);$i++)
{
$data = array(
'rowid' => $item[$i],
'qty' => $qty[$i]
);
$this->cart->update($data);
}
}
function validate_add_cart_item(){
$id = $this->input->post('product_id'); // Assign posted product_id to $id
$qty = $this->input->post('quantity'); // Assign posted quantity to $cty
$this->db->select('*');
$this->db->from('tvs');
$this->db->join('computers', 'computer.id = tv.id and computer.name = tv.name and computer.price = tv.price');
$this->db->join('laptops', 'laptops.id = tv.id and laptops.name = tv.name and laptops.price = tv.price');
$this->db->where('tvs.id', $id);
$query = $this->db->get();
return $query->result();
}
foreach($this->cart->contents() as $item) {
if($item['id'] == $id) {
$data = array(
'rowid' => $item['rowid'],
'qty' => $item['qty'] + $qty
);
$this->cart->update($data);
return TRUE;
}
}
$row = $query->row();
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $row->price,
'name' => $row->name
);
this->cart->insert($data);
return TRUE;
{
}else{
return FALSE;
}
}
}
This is the item list:
<ul class="products">
<?php foreach($TV as $p): ?>
<li>
<h1>
<a href="<?php echo current_url();?>/
<?php echo $p['link']; ?>" />
<?php echo $p['name']; ?>
</a>
</h1>
<img src="<?php echo base_url(); ?>assets/image/products/<?php echo $p['image']; ?>" alt="<?php echo $p['name']; ?>" />
<h3>
<?php echo $p['description']; ?>
</h3>
<small>£<?php echo $p['price']; ?></small>
<?php echo form_open('/testcart/home/add_cart_item'); ?>
<fieldset>
<label>Quantity</label>
<?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
<?php echo form_hidden('product_id', $p['id']); ?>
<?php echo form_submit('add', 'Add to Cart'); ?>
</fieldset>
<?php echo form_close(); ?>
</li>
<?php endforeach;?>
</ul>`
Controller:
function add_cart_item(){
if($this->cart_model->validate_add_cart_item() == TRUE){
if($this->input->post('ajax') != '1'){
redirect('');
}else{
echo 'true';
}
}
}
The javascript
$(document).ready(function() {
var link = baseurl;
$("ul.products form").submit(function() {
// Get the product ID and the quantity
var id = $(this).find('input[name=product_id]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "home/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "home/show_cart", function(cart){
$("#cart_content").html(cart);
});
}else{
alert("Product does not exist");
}
});
return false;
});
$(".empty").live("click", function(){
$.get(link + "home/empty_cart", function(){
$.get(link + "home/show_cart", function(cart){
$("#cart_content").html(cart);
});
});
return false;
});
});
I'm not too sure where it's going wrong as I'm relatively new to all this, whether it's the Javascript or the PHP.

This is your error free method. You were making mistake selecting from table tvs and using tv in joins
function validate_add_cart_item()
{
$id = $this->input->post('product_id'); // Assign posted product_id to $id
$qty = $this->input->post('quantity'); // Assign posted quantity to $cty
$this->db->select('*');
$this->db->from('tvs as tv');
$this->db->join('computers', 'computer.id = tv.id and computer.name = tv.name and computer.price = tv.price');
$this->db->join('laptops', 'laptops.id = tv.id and laptops.name = tv.name and laptops.price = tv.price');
$this->db->where('tv.id', $id);
$query = $this->db->get();
return $query->result();
}

Related

PHP link same page with link and send data via $_POST

I have a database table with (NumSection (id) and NomSection)
In my page I want display all data from 'NomSection' like a link. And when I click on the link I want open my actual page with a $_POST['nomSection'] and display data of this section.
From my page index.php :
<div>
<?php
$array = returnAllSection();
foreach ($array as $section) {
// link to same page but with a $_POST['NomSection'], For the //moment I just display it.. I don't know how do with php
echo $section['NomSection'].'<br/>';
}
?>
</div>
<div>
<?php
// here I want have $array = returnAll('NomSection) or returnAll() //if empty (this function return ALL if empty or All of a section, can I just //put returnAll($_POST[nomSection]) ?
$array = returnAll();
foreach ($array as $section) {
echo 'Titre: ' .$section['TitreArticle'].'<br/>';
echo 'Date: ' .$section['DateArticle'].'<br/>';
echo 'Texte: ' .$section['TexteArticle'].'<br/>';
echo '<br/>';
}
?>
</div>
my functions: (works good)
function returnAll($arg = 'all') {
global $connexion;
if($arg == 'all'){
$query = "select
NumArticle,
TitreArticle,
TexteArticle,
DateArticle,
RefSection,
NomSection
from Articles, Sections where
RefSection = NumSection or RefSection = null;";
$prep = $connexion->prepare($query);
$prep->execute();
return $prep->fetchAll();
}
else {
$query = "select NumArticle,
TitreArticle,
TexteArticle,
DateArticle,
RefSection,
NomSection
from Articles, Sections where
RefSection = NumSection and NomSection = :arg;";
$prep = $connexion->prepare($query);
$prep->bindValue(':arg', $arg, PDO::PARAM_STR);
$prep->execute();
return $prep->fetchAll();
}
}
function returnAllSection() {
global $connexion;
$query = "select * from Sections;";
$prep = $connexion->prepare($query);
$prep->execute();
return $prep->fetchAll();
}
In order to post you'll need to use a form or javascript ajax post, as far as I know. Here I show a clunky form post approach that might work for what you are trying to accomplish.
<?php
function returnAllSection() {
return array(
array('NomSection' => 'foo'),
array('NomSection' => 'bar'),
array('NomSection' => 'baz'),
);
}
?>
<?php
$array = returnAllSection();
foreach ($array as $section) { ?>
<form action="" method="POST">
<button type="submit">NomSection</button>
<input type="hidden" name="NomSection" value="<?php echo htmlspecialchars($section['NomSection']); ?>">
</form>
<?php } ?>
<?php
if (isset($_POST['NomSection'])) {
error_log(print_r($_POST,1).' '.__FILE__.' '.__LINE__,0);
// do something with NomSection...
}
?>

How to generate link for the data fetched from MYSQL on webpage

For a quiz i am Fetching some random questions from a table and displaying the questions (one question at a time) on the webpage.
Now by taking count of the questions fetched i am displaying the numbers starting from 1 as a tab.
i.e. suppose i have fetched 10 questions then it will display tabs as 1 2 3 4 5 6 7 8 9 10. and currently what ever question is displaying on webpage that tab will be highlighted.
my question is how can i make these tabs as link so that when i click on that tab it will show that question on the webpage.
View:
<div id="container">
<?php echo "<br />" ?>
<?php
$attributes=array('id'=>'testForm');
echo form_open('attemptTest/getquestion/',$attributes);
?>
<div id="body">
<?php
$totq=explode(",",$test['random_question_no']);
$totq=array_sum($totq);
$totalQuestions=array_sum(explode(",",$test['random_question_no']));
$selected_answers=explode(',',$result['selected_answers']);
$selected_answers=$selected_answers[$qno-1];
?>
<input type="hidden" name="qno" value="<?=$qno?>" id="qno">
<input type="hidden" name="direction" value="N" id="direction">
<input type="hidden" name="submitTest" value="0" id="submitTest">
<input type="hidden" name="time1" value="<?php $time_taken=explode(',',$result['time_taken']); echo (array_sum($time_taken)+$result['iniTime']);?>" >
<code><table><tr><td valign="top" >Q<?=$qno?>) </td><td style="word-break: break-word;"><?=$question['question']?></td></tr></table></code>
<?php $option=explode(',',$question['options']);
foreach($option as $option){
$ans="ans".$qno;
?>
<div id="qoption">
<table><tr><td style="width:18px;" valign=top ><input type="radio" value="<?=$option?>" name="answer" <?php if($selected_answers==$option){ echo "checked";} ?> > </td><td><?=$option?></td></tr></table>
</div>
<?php
}
?>
<br/>
<table><tr><td><?php if($qno>="2"){ ?><div class="big_button" style="width:70px;"><center><a href="javascript:document.getElementById('direction').value='B';document.getElementById('testForm').submit();" id="big_button" >Back</a></center></div><?php } ?></td><td> </td><td>
<?php if($qno<$totalQuestions){ ?><div class="big_button" style="width:70px;"><center>Next</center></div> <?php } ?>
</td><td> </td>
<td>
<div class="big_button" style="width:120px;"><center>
Submit Test
</center></div>
</td></tr></table>
<br/>
</div></div>
<table id="all_questions">
<tr>
<?php $i=0; foreach($questions_all as $key=>$value){$i++;?>
<td class="<?php if($qno==$key+1){echo "active ";}?> <?php if(isset($_COOKIE['answered_'.$value])){if($_COOKIE['answered_'.$value]!=0){ echo "green";}} ?>" ><?=$key+1?></td><?php if($i==4){$i=0; echo "</tr><tr>";}?>
<?php }?>
</tr>
</table>
<style>
#all_questions td{
width:40px;
height:40px;
border-radius:3px;
margin:5px;
text-align:center;
vertical-align:middle;
}
.active {
background-color:red;
}
.green {
background-color:green;
}
</style>
Controller:
<?php
class attemptTest extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('test_model');
$this->load->model('attempt_model');
$this->load->helper('html');
$this->load->helper('url');
$this->load->library('session');
// if not logged in redirect
if(($this->session->userdata('logged_in'))!='TRUE'){ redirect('login'); }
}
public function index($tid='',$access_token='0')
{
$this->load->helper('cookie');
$this->load->library('form_validation');
// if test cookies exist bypass to getquestion function
if(isset($_COOKIE['tid']) && isset($_COOKIE['qids']) && isset($_COOKIE['resultid']) && isset($_COOKIE['qno']) && isset($_COOKIE['access_token']))
{
$this->getquestion($_COOKIE['qno'],$_COOKIE['qids'],$_COOKIE['tid']);
}
else
{
// else started new test so check access token cookie exist for test if not redirect
if(!isset($_COOKIE['access_token'])){
redirect('test/view/'.$tid);
}
// getting test data
$data['test'] = $this->test_model->get_test($tid,'0');
// getting multi dimensonal arrays of question ids which are going to assign user
$data['qids'] = $this->attempt_model->get_questions_id($data['test']);
// make one dimensonal array
$qid=array();
foreach($data['qids'] as $question)
{
$qid[]=$question['qid'];
}
// convert array into string
$qids=implode(",",$qid);
// insert result row
$data['resultid']=$this->attempt_model->insert_result_row($data['test'],$qids);
// creating required cookies
$cookie = array('name'=>'resultid','value'=>$data['resultid'],'expire'=>'86500');
$this->input->set_cookie($cookie);
$cookie = array('name'=>'qids','value'=>$qids,'expire'=>'86500');
$this->input->set_cookie($cookie);
$cookie = array('name'=>'tid','value'=>$data['test']['tid'],'expire'=>'86500');
$this->input->set_cookie($cookie);
$cookie = array('name'=>'qno','value'=>'0','expire'=>'86500');
$this->input->set_cookie($cookie);
$this->getquestion('0',$qids,$tid,$data['resultid']);
}
}
public function getquestion($qno=0,$qids=0,$tid=0,$resultid=0)
{
if(!isset($_COOKIE['access_token'])){
redirect('index');
}
$this->load->helper('cookie');
$this->load->library('form_validation');
//define question ids
if(isset($_COOKIE['qids'])){
$qids=$_COOKIE['qids'];
}else{
$qids=$qids;
}
$eqid=explode(",",$qids);
//addition od code by vivek
$data['questions_all'] = $eqid;
//define test id
if(isset($_COOKIE['tid'])){
$tid=$_COOKIE['tid'];
}else{
$tid=$tid;
}
if(isset($_COOKIE['resultid'])){
$resultid=$_COOKIE['resultid'];
}
$iniTime = $this->attempt_model->get_result($resultid);
$test_time = $this->test_model->get_test($tid,'0');
// check time
if(((($test_time['test_time']*60)-(time()-$iniTime['iniTime']))<="0") || ((time())>($test_time['end_time']))){
$this->submit('Time Over');
return;
}
// define question no.
if(isset($_POST['qno'])){
$qno=$_POST['qno'];
$pqid=$eqid[$qno-1];
if(isset($_POST['answer'])){
$answer=$_POST['answer'];
$time1=$_POST['time1'];
}else{ $answer='NULL'; $time1=$_POST['time1']; }
$this->attempt_model->submit_answer($_COOKIE['resultid'],$qno,$_COOKIE['tid'],$pqid,$answer,$time1);
}
if(isset($_POST['submitTest']))
{
if($_POST['submitTest']=='1')
{
$this->submit();
return;
}
}
// next question
if(isset($_POST['direction']))
{
// if direction is for next question add one
if($_POST['direction']=='N'){
$data['qno']=$qno+1; $qid=$eqid[$qno];
}
else
{
// else subtract one
$data['qno']=$qno-1;
$qid=$eqid[$qno-2];
}
}
else{
$data['qno']=$qno+1;
$qid=$eqid[$qno];
}
// getting earlier submitted answer if any
$data['result'] = $this->attempt_model->get_result($resultid);
// getting test data
$data['test'] = $this->test_model->get_test($tid,'0');
// getting question data
$data['question'] = $this->attempt_model->get_question($qid);
// load header page
$this->load->view('header_attemptTest.php',$data);
// load attempt test body page
$this->load->view('attemptTest',$data);
// load footer
$this->load->view('footer');
// update cookies with question number
$cookie = array('name'=>'qno','value'=>$data['qno'],'expire'=>'86500');
$this->input->set_cookie($cookie);
}
public function submit($msg='')
{
$this->load->helper('cookie');
$this->attempt_model->submit_test($_COOKIE['resultid'],$_COOKIE['tid']);
// page title meassage
$data['title']="Test Submitted";
$data['msg']=$msg;
$data['resultid']=$_COOKIE['resultid'];
$this->load->view('header.php',$data);
$this->load->view('submitTest',$data);
$this->load->view('footer');
// unset test cookies
$cookie = array('name'=>'resultid','value'=>'','expire'=>'1');
$this->input->set_cookie($cookie);
$cookie = array('name'=>'qids','value'=>'','expire'=>'1');
$this->input->set_cookie($cookie);
$cookie = array('name'=>'tid','value'=>'','expire'=>'1');
$this->input->set_cookie($cookie);
$cookie = array('name'=>'qno','value'=>'','expire'=>'1');
$this->input->set_cookie($cookie);
$cookie = array('name'=>'access_token','value'=>'','expire'=>'1');
$this->input->set_cookie($cookie);
}
}
?>
Model:
<?php
class attempt_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_questions_id($test)
{
$noqs=explode(',',$test['random_question_no']);
$sids=explode(',',$test['subject_ids']);
foreach($noqs as $key => $noq){
$sid=$sids[$key];
if($key==0){
$sql="(select qid from questionBank where sid='$sid' order by rand() LIMIT $noq )";
}else{
$sql=$sql."UNION (select qid from questionBank where sid='$sid' order by rand() LIMIT $noq )";
}
}
$query = $this->db->query($sql);
$questions=$query->result_array();
return $questions;
}
// return single question
public function get_question($qid)
{
$sql="select * from questionBank where qid='$qid' ";
$query = $this->db->query($sql);
$questions=$query->row_array();
return $questions;
}
// return multiple questions
public function get_questions($qids)
{
$sql="select * from questionBank where qid in($qids) ORDER BY FIELD(qid, $qids) ";
$query = $this->db->query($sql);
$questions=$query->result_array();
return $questions;
}
public function get_result($resultid)
{
$sql="select * from result where result_id='$resultid' ";
$query = $this->db->query($sql);
$result=$query->row_array();
return $result;
}
public function submit_answer($resultid,$qno,$tid,$qid,$posted_answer,$time1)
{
$sql="select * from result where result_id='$resultid' ";
$query1 = $this->db->query($sql);
$result=$query1->row_array();
// getting correct answer from question
$sql="select answer from questionBank where qid='$qid' ";
$query = $this->db->query($sql);
$answer=$query->row_array();
//compare posted answer with correct answer
$correct_answer=explode(",",$result['correct_answer']);
$selected_answers=explode(",",$result['selected_answers']);
$time_taken=explode(",",$result['time_taken']);
$time2=(time()-$time1);
$time_taken[$qno-1]=($time_taken[$qno-1])+$time2;
if($posted_answer!='NULL'){
if($posted_answer==$answer['answer']){ $correct_answer[$qno-1]="1"; }else{ $correct_answer[$qno-1]="0"; }
$selected_answers[$qno-1]=$posted_answer;
}
$correct_answer=implode(",",$correct_answer);
$selected_answers=implode(",",$selected_answers);
$time_taken=implode(",",$time_taken);
// Update result row
$data = array('correct_answer' => $correct_answer,'selected_answers' => $selected_answers,'time_taken' => $time_taken);
$this->db->where('result_id', $resultid);
$this->db->update('result', $data);
}
public function submit_test($resultid,$tid)
{
// getting test data
$sql="select * from test where tid='$tid' ";
$query1 = $this->db->query($sql);
$test=$query1->row_array();
// getting result data
$sql="select * from result where result_id='$resultid' ";
$query2 = $this->db->query($sql);
$result=$query2->row_array();
// calculating result
$correct_answer=$result['correct_answer'];
$correct_answer=str_replace("2","0",$correct_answer);
$correct_answer=explode(",",$correct_answer);
$correctans=array_sum($correct_answer);
$wrong_answer=$result['correct_answer']; $wrong_answer=explode(",",$wrong_answer); $wrong_ans=count( array_keys( $wrong_answer, "0" ));
$total_marks=$correctans-$wrong_ans*$test['minus_mark'];
$percentage=($total_marks/$result['total_question'])*100;
if($percentage>=$test['reqpercentage'])
{
$status="1";
}
else
{
$status="0";
}
// update result row
$data = array('obtained_percentage' => $percentage,'status' => $status,'submitTime'=>time());
$this->db->where('result_id', $resultid);
$this->db->update('result', $data);
}
public function insert_result_row($test,$qids)
{
$totq=explode(",",$test['random_question_no']);
$totqs=array_sum($totq);
$temp_value=array();
for($i=0; $i < $totqs; $i++)
{
$temp_value[$i]='2';
}
$temp_value=implode(",",$temp_value);
$temp_time=array();
for($j=0; $j < $totqs; $j++)
{
$temp_time[$j]='0';
}
$temp_time=implode(",",$temp_time);
$uid=$this->session->userdata('uid');
// insert row
$data=array('uid'=>$uid,'tid'=>$test['tid'],'total_question'=>$totqs,'correct_answer' => $temp_value,'time_taken' => $temp_time, 'selected_answers' => $temp_value,'question_ids'=>$qids,'status'=>'2','iniTime'=>time());
$this->db->insert('result', $data);
return $this->db->insert_id();
}
}
?>
I heaven't read your code but I suppose you would want this ;)
In this case, we assume this code is all in index.php file.
This is how you link to your question (or you can redirect there in any other way you want):
<?php
$id = -1;
if (isset($_GET["questionid"])) {
$id = $_GET["questionid"];
}
?>
<a href="index.php?questionid=1" <?php if($id == 1){echo " class='active'"} ?>>Question 1</a>
<a href="index.php?questionid=2" <?php if($id == 2){echo " class='active'"} ?>>Question 2</a>
<a href="index.php?questionid=3" <?php if($id == 3){echo " class='active'"} ?>>Question 3</a>
And here is the code how to show question with id questionid.
<?php
if ($id > -1) {
showQuestion($id);
// = your code to show question with id questionid
}
else {
echo "No question selected";
}
?>

When my controller function loads a view, the URL has the controller name and function still in the URL. How can I get rid of this?

Basically my function checks to see if something is in a database. If it's found it returns true and carries on to the next view. However, if it returns false it reloads the home.php view but it seems to still leave URI segments in the URL...
example:
www.example.com/index.php/home/checkSearchFields
How to I get it to get rid of the 'home/checkSearchFields'?
Thanks for your help.
home.php (view)
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var base_url = window.location.origin;
function getStates(value) {
$.post(base_url + "/buildings/getstates.php",{partialState:value},function(data){
$("#results").html(data);
});
}
function myFunction(){
var target = event.target || event.srcElement;
var str = target.innerHTML;
console.log(str);
document.getElementById("stateSearch").value = str ;
$( "#results" ).empty();
}
</script>
</head>
<body>
<div id="container">
<h1>Room Finder</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('home/checkSearchFields'); ?>
<div class="searchfield">
Building: <br/>
<input type="text" name="building" onkeyup="getStates(this.value)" id="stateSearch" autocomplete="off"/>
</div><!-- closes searchfield -->
<div class="searchfield">
Room #: <br/>
<input type="text" name="roomNum" autocomplete="off"/><br/>
</div><!-- closes searchfield -->
<div class="submit">
<input type="submit" value="Submit" name="submit" />
</div><!-- closes submit -->
</form>
<div id="results"></div>
home.php (Controller)
class home extends CI_Controller {
public function index()
{
$this->load->view('home');
}
public function checkSearchFields(){
$this->form_validation->set_rules('building', 'Building', 'required|callback_verifyBuilding');
$this->form_validation->set_rules('roomNum', 'RoomNum', 'required');
$roomNumber = $this->session->userdata('roomNumber'); // going to be checked to see if null
if($this->form_validation->run() == false){
$this->load->view('home');
}else{
$this->load->view('worked');
}
}
public function verifyBuilding(){
$buildings = $this->input->post('building');
$roomNum = $this->input->post('roomNum');
$this->load->model('BuildingModel');
if($this->BuildingModel->userSearch($buildings, $roomNum)){
return true;
}else{
$this->form_validation->set_message('verifyBuilding', 'Incorrect Building Name or Room Number... Please try again...');
return false;
}
}
}
buildingmodel.php (Model)
class BuildingModel extends CI_Model{
public function userSearch($buildings, $roomNum){
$this->db->select('*');
$this->db->from('buildings');
$this->db->where('buildingName', $buildings);
$query = $this->db->get();
if($query->num_rows() == 1){
foreach($query->result_array() as $row)
{
$buildingID = $row['buildingID'];
$buildingName = $row['buildingName'];
$buildingLocation = $row['buildingLocation'];
$imagePath = $row['imagePath'];
}
$userSearch = array(
'buildingID' => $buildingID,
'buildingName' => $buildingName,
'buildingLocation' => $buildingLocation,
'imagePath' => $imagePath,
);
$this->session->set_userdata($userSearch);
//query DB for the room numbers
$this->db->select('*');
$this->db->from('rooms');
$this->db->where('buildingID', $buildingID);
$this->db->where('roomNumber', $roomNum);
$query2 = $this->db->get();
if($query2->num_rows() == 1){
foreach($query2->result_array() as $row)
{
$roomID = $row['roomID'];
$roomNumber = $row['roomNumber'];
$roomCode = $row['roomCode'];
$office = $row['office'];
$location = $row['location'];
$roomName = $row['roomName'];
}
$userSearch = array(
'roomID' => $roomID,
'roomNumber' => $roomNumber,
'roomCode' => $roomCode,
'office' => $office,
'location' => $location,
'roomName' => $roomName,
);
$this->session->set_userdata($userSearch);
}
return true;
}else{
return false;
}
}
}
As you said, it just loads the view. Which view is loaded, has nothing to do with how the URL looks like.
You could replace this:
if($this->form_validation->run() == false){
$this->load->view('home');
}else{
$this->load->view('worked');
}
with this:
if($this->form_validation->run() == false){
redirect('home');
}else{
$this->load->view('worked');
}
When it fails, it redirects you to the homepage.

Shopping cart code is not working. getting error for undefined variable

I found this tutorial on making a shopping cart app and It's not working. I get an error about undefined variable bookFound on line 22 where it says if(!$bookFound). I see maybe why it is not defined, I'm thinking maybe because it was defined in the if statement previously in the code and that is not returning true. Any ways I'm having problems fixing it so if you can make this code work that will be great. The user should be able to click the button and the div should be updated with calculated results.
<?php
session_start();
$booksInfo = $_SESSION['cart'];
if(count($booksInfo) > 0)
{
$bookFound = false;
for($i=0; $i< count($booksInfo); $i++)
{
if($booksInfo[$i]['bookId'] == $_POST['bookId'])
{
$booksInfo[$i]['quantity'] = $_POST['quantity'];
$bookFound = true;
break;
}
}
}
if(!$bookFound) //line 22 where error was found
{
$book = array('bookId' => $_POST['bookId'], 'quantity' => $_POST['quantity']);
array_push($booksInfo, $book);
}
$_SESSION['cart'] = $booksInfo;
$grossTotal = 0;
for($i=0; $i< count($booksInfo); $i++)
{
$aBook = $booksInfo[$i];
$bookName = getBookName($booksInfo[$i]['bookId']);
$bookPrice = getPriceForBook($booksInfo[$i]['bookId']);
$totalPrice = $bookPrice * $booksInfo[$i]['quantity'];
$grossTotal+= $totalPrice;
$str.= '<strong>Name - </strong>'.$bookName;
$str.= '<br/>';
$str.= ' <strong>Copies - </strong>'.$booksInfo[$i]['quantity'];
$str.= '<br/>';
$str.= '<strong>Price - </strong>$'.$bookPrice. ' * ' .$booksInfo[$i]['quantity'].' = $'.$totalPrice;
$str.= '<br/><br/>';
}
$str.= '<strong>Net Amount - </strong>$'.$grossTotal;
echo $str;
function getBookName($id)
{
$objXML = simplexml_load_file('books.xml');
foreach($objXML->book as $book)
{
if($book['id'] == $id)
{
return $book->name;
}
}
return false;
}
function getPriceForBook($id)
{
$objXML = simplexml_load_file('books.xml');
foreach($objXML->book as $book)
{
if($book['id'] == $id)
{
return $book->price;
}
}
return false;
}
?>
Index:
<body>
<div class="cart">
<strong>Your cart</strong>
<p id = "cart">Cart is empty</p>
</div>
<?php
$objXML = simplexml_load_file('books.xml');
foreach($objXML->book as $book)
{
echo '<div>';
echo 'Name - ' . $book->name, '<br />';
echo 'price - $'. $book->price, '<br/>';
?>
Quantity -
<select name="" id="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
-
<input type="hidden" value = "<?php echo $book['id']; ?>">
<input type="button" value = "Select this book ">
<?php
echo '</div>';
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('input:button').click(function(){
$.post('calculate.php',
{
bookId : $(this).prev('input:hidden').val(),
quantity: $(this).prev().prev('select').val()
},
function(data)
{
$('#cart').html(data);
}
)
});
});
</script>
</body>
Try moving the $bookFound = false; statement above the if(count($booksInfo) > 0) statement. If the if(count($booksInfo) > 0){} block is not executed, $bookFound is not initialized for when you get to the if(!$bookFound){} block.

codeigniter validating from textbox value(jquery) from array(php)

I want to validate whether my 3 input's are the same as the value in the array.
<?php
$aylength = 0;
$resultacyear = array();
foreach($academicyear->result() as $ay)
{
$item = array(
'tahunakademik' => $ay->Tahun_Akademik,
'idsemester' => $ay->ID_Semester,
'idlevelyear' => $ay->ID_Level_Year
);
$resultacyear[]= $item;
$aylength++;
}
?>
<script type="text/javascript">
$('#btn_save').click(function() {
<?php $inc = 0; ?>
for(i=0;i<parseInt(<?php echo $aylength?>);i++)
{
if($('#txt_tahunAkademik').val()=="<?php echo $resultacyear[$inc]['tahunakademik'] ?>" && $('#cb_semester').val()=="<?php echo $resultacyear[$inc]['idsemester'] ?>" && $('#cmb_YearLevel').val()=="<?php echo $resultacyear[$inc]['idlevelyear'] ?>")
{
alert ("Data already exists!!");
return false;
break;
}
else
{
<?php $inc++; ?>
return false;
}
}
});
</script>
When i tried, it didn't validate or even checks the value.
Is something wrong with my validation??

Categories