How to insert selected value from select option using checkbox in PHP? - php

how to insert select option value in database using checkbox?When I click checkbox and click enroll button ,select option doesn't inserting selected value.I have 3 options(Regular,Retake,Recourse) in "examtype" table but when I choose more than one subject select option not working perfectly. Here is my code...
here is my select option image
<?php
if (isset($_POST['enroll']))
{
if (!empty($_POST['chk1']))
{
if (isset($_POST['et']))
{
$roll_no = $_SESSION['roll_no'];
//$selectbox1 = $_POST['et'];
foreach($_POST['chk1'] as $checkbox1)
{
foreach($_POST['et'] as $selectbox1)
//for($i=0;$i<sizeof($selectbox1);$i++)
$values = explode("|" , $checkbox1);
$values1= explode("|" , $selectbox1);
$course_id= $values[0];
$semester= $values[1];
$course_name= $values[2];
$selectbox1=$values1[0];
$sql="INSERT INTO pendingcourse(roll_no,course_id,semester,course_name,exam_type,status) VALUES('$roll_no','$course_id','$semester','$course_name','$selectbox1',0)";
$stmt = $connect->prepare($sql);
$stmt->execute();
$checkbox1='';
$selectbox1='';
}
header("location:coursetable.php");
}
}
}
?>
<form action="coursetable.php" method="post" enctype="multipart/form-data">
<div class="container mt-3" >
<div class="accordion mb-4" id="accordionExample" >
<div class="accordion-item" style="background-color: rgb(0, 225, 255);">
<h2 class="accordion-header" id="headingOne">
<button class="accordion-button collapsed fw-bold" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne" style="background: #AAFFA9;">
1st Semester
</button>
</h2>
<div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" >
<div class="accordion-body">
<table class="table table-bordered border-primary text-center">
<thead>
<tr>
<th scope="col-1">Course Id</th>
<th scope="col-1">Semester</th>
<th scope="col-7">Course</th>
<th scope="col-1">Exam Type</th>
<th scope="col-1">Select</th>
<th scope="col-2">Result</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $connect->query("SELECT course_id,semester,course_name FROM coursetable Where semester = '1st' ");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row)
{
$course_id = $row['course_id'];
$semester = $row['semester'];
$course_name = $row['course_name'];
?>
<tr>
<td scope="row"> <?php echo $course_id?></td>
<td > <?php echo $semester ?></td>
<td ><?php echo $course_name ?></td>
<td>
<select name="et[]" class="form-select form-select-sm" aria-label=".form-select-sm example">
<?php
$stmt1 = $connect->query("SELECT * from examtype");
$rows1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
foreach($rows1 as $row1) {
?>
<option value="<?php echo $row1['exam_type']; ?>"><?php echo $row1['exam_type']; ?></option>
<?php
}
?>
</select>
</td>
<td>
<input type="checkbox" name="chk1[]" value="<?php echo $row['course_id']?>|<?php echo $row['semester']?>|<?php echo $row['course_name']?>|<?php echo $row1['exam_type']?>">
<label class="form-check-label" for="flexCheckDefault">
</label>
</td>
<td></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-2 col-xs-6 offset-md-5 mb-3">
<button type="submit" name="enroll" class="btn btn-warning mt-2">Enroll</button>
</div>
</div>
</div>
</form>

Place the input field inside a form and add
enctype="multipart/form-data"

<select name="et[]" class="form-select form-select-sm" aria-label=".form-select-sm example" multiple>
try this
add multiple in select

SOLVED:
<?php
if (isset($_POST['enroll']))
{
if (!empty($_POST['chk1']))
{
if (!empty($_POST['et']))
{
$roll_no = $_SESSION['roll_no'];
$selectbox1 = $_POST['et'];
$selectbox11=implode(',',array_filter($selectbox1));
$i=0;
foreach($_POST['chk1'] as $checkbox1)
{
$selectbox111 = array_diff(explode(",", $selectbox11),array(""));
$selectbox1111 = $selectbox111[$i];
$values = explode("|" , $checkbox1);
$course_id= $values[0];
$semester= $values[1];
$course_name= $values[2];
$sql="INSERT INTO pendingcourse(roll_no,course_id,semester,course_name,exam_type,status) VALUES('$roll_no','$course_id','$semester','$course_name','$selectbox1111',0)";
$stmt = $connect->prepare($sql);
$stmt->execute();
$checkbox1='';
$i++;
}
}
}
}
?>

Related

Enter multiple rows in an MySQL table by pressing the Submit button in a PHP Form

So to preface - I'm trying to implement a "Mark Attendance" feature on my website where I'm printing all the registered students in a table (that is wrapped in ) - each student has a "Present / Absent" radio button and once the admin has selected his preferred option, he presses "Submit" and the form should mark all students Present OR Absent i.e insert multiple rows (equal to the number of total students in the table) with their Attendance Status i.e Absent or Present.
Following is the HTML part of the code (mixed with some PHP):
<form action="adminmarkattendance.php" method="post">
<div class="row">
<div class="col">
<div class="card bg-default shadow">
<div class="card-header bg-transparent border-0">
<div class="form-inline">
<div class="col-lg-6">
<h3 class="text-white mb-0">Registered Students</h3>
</div>
<div class="col-lg-6">
<div class="form-group">
<input style="width: 100%;" class="form-control" name="attendancedate" type="date" required>
</div>
</div>
</div>
</div>
<div class="table-responsive" style="overflow-y: scroll; height: 600px;">
<table class="table align-items-center table-dark table-flush">
<thead class="thead-dark">
<tr>
<th scope="col" class="sort" data-sort="name">Avatar</th>
<th scope="col" class="sort" data-sort="name">Student Name</th>
<th scope="col" class="sort" data-sort="status">Phone Number</th>
<th scope="col" class="sort" data-sort="status">Age</th>
<th scope="col" class="sort" data-sort="status">Gender</th>
<th scope="col" class="sort" data-sort="status">Address</th>
<th scope="col" class="sort" data-sort="status">Action</th>
</tr>
</thead>
<tbody class="list">
<?php
foreach ($getRows as $row) {
$i = 0; ?>
<tr>
<td>
<img src="<?php echo '../profileImages/' . $row['profile_image'] ?>" width="45" height="45" alt="">
<input type="hidden" name="id" value="<?php echo $row['student_id']; ?>">
</td>
<th scope="row">
<div class="media align-items-center">
<div class="media-body">
<span class="name mb-0 text-sm"><?php echo $row['fname'] . ' ' . $row['lname']; ?></span>
</div>
</div>
</th>
<td>
<span class="badge badge-dot mr-4">
<span class="status"><?php echo $row['phonenumber']; ?></span>
</span>
</td>
<td>
<span class="badge badge-dot mr-4">
<span class="status"><?php echo $row['age']; ?></span>
</span>
</td>
<td>
<span class="badge badge-dot mr-4">
<span class="status"><?php echo $row['gender']; ?></span>
</span>
</td>
<td>
<span class="badge badge-dot mr-4">
<span class="status"><?php echo $row['address']; ?></span>
</span>
</td>
<td>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary active">
<input type="radio" name="options" value="present" id="option1" autocomplete="off" checked> Present
</label>
<label class="btn btn-secondary">
<input type="radio" name="options" value="absent" id="option2" autocomplete="off"> Absent
</label>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="text-center">
<button type="submit" name="submit" style="width: 100%;" class="btn btn-warning">Mark Attendance</button>
</div>
</form>
PHP:
if (isset($_POST["submit"])) {
$student_id = $_POST["id"];
$date = $_POST['attendancedate'];
$date = date('Y-m-d', strtotime($date));
$status = $_POST['options'];
$queryInsert = $conn->prepare("INSERT
into attendance
(
student_id,
date,
status
)
values
(
$student_id,
'$date',
'$status'
)
");
$queryInsert->execute();
echo "<script> location.replace('adminmarkattendance.php'); </script>";
}
As you can probably see in the code - I'm only trying to insert the student's ID, date & his present/absent status.
Now, when I press submit, the information of only 1 student is inserted into the Attendance table. Usually, the last student. Which is not what I want - I want X number of rows inserted when I press submit, where X is equal to the number of students in the table.
How do I achieve this? Thank you for reading.
What you need is to submit whole data and then loop through it like this
<input type="hidden" name="id[]" value="<?php echo $row['student_id']; ?>">
<input type="radio" name="options[]" value="absent" id="option2" autocomplete="off"> Absent</label>
Then
if (isset($_POST["submit"]))
{
for($i=0;$i<count($_POST["id"]);$i++)
{
$student_id = $$_POST["id"][$i]];
$date = $_POST['attendancedate'];
$date = date('Y-m-d', strtotime($date));
$status = $_POST['options'][$i]];
$queryInsert = $conn->prepare("INSERT into attendance(student_id,date,status)
values ($student_id,'$date','$status')");
$queryInsert->execute();
}
}
Note Adjust the code according to your need.
Sadly, I can't comment on answers yet.
I feel like I do have something to improve on Adib Javed's answer (the back-end part).
Preferably - don't loop db requests, and try to make a single request.
So you can loop to create the request, and when the loop ends, send that single request:
if (isset($_POST["submit"]))
{
$query = "INSERT into attendance(student_id,date,status) values";
for($i=0;$i<count($_POST["id"]);$i++)
{
$student_id = $$_POST["id"][$i]];
$date = $_POST['attendancedate'];
$date = date('Y-m-d', strtotime($date));
$status = $_POST['options'][$i]];
$query .= " ($student_id,'$date','$status'),";
}
substr_replace($query ,";", -1);
$queryInsert = $conn->prepare($query);
$queryInsert->execute();
}

Checkbox in PHP foreach loop - all checkboxes activate the 1st

I have a foreach loop providing data to a html table. I have added a form around the table and on each row am adding an input/checkbox with the value set as the row_id from the db call.
When clicking on the first checkbox it selects, when clicking on other rows the 1st checkbox in the table selects not the row you intended.
I was under the impression that setting the name="whatever[]" like so adds the checkbox to an array? So in the form processor I can get it via $_POST['checkbox'] array. Which is working on the form processor part.
I am using bootstrap to style everything so this might be an issue?
I can't for the life of me seem to be able to fix the click one checkbox get only the first checked.
This is my table code:
<form action="<?php echo URLROOT.'/admin/voyage/sendemail'; ?>" method="POST">
<table id="volunteers" class="table table-bordered text-secondary">
<thead class="bg-msp-lightgrey">
<tr>
<th width="35px">
</th>
<th>
Volunteer
</th>
<th>
Position
</th>
<th>
DBS Status
</th>
<th>
Last Training
</th>
<th>
Last Refit
</th>
<th>
Contact
</th>
<th>
Form
</th>
</tr>
</thead>
<tbody>
<?php foreach ($data['volunteerData'] as $volunteer) : ?>
<?php
$result = 'DBS Form to be sent';
$order = 0;
if ($volunteer->volunteer_dbsSent) {
$result = 'DBS Form sent to volunteer - '.date('d/m/Y', strtotime($volunteer->volunteer_dbsSent));
$order = 1;
}
if ($volunteer->volunteer_dbsReceived) {
$result = 'DBS Form returned to us - '.date('d/m/Y', strtotime($volunteer->volunteer_dbsReceived));
$order = 2;
}
if ($volunteer->volunteer_dbsASTO) {
$result = 'DBS Form sent to ASTO - '.date('d/m/Y', strtotime($volunteer->volunteer_dbsASTO));
$order = 3;
}
if ($volunteer->volunteer_dbsReturned) {
$result = 'DBS returned - '.date('d/m/Y', strtotime($volunteer_dbsReturned));
$order = 4;
}
if ($volunteer->volunteer_dbsClear) {
$result = 'DBS clear, cert number: - '.$volunteer->volunteer_dbsCertNum;
$order = 5;
}
?>
<tr>
<td>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="check" name="check[]" value="<?php echo $volunteer->volunteer_id; ?>" />
<label class="custom-control-label" for="check"></label>
</div>
</td>
<td>
<a class="text-msp-lightblue" href="<?php echo URLROOT.'/admin/volunteer/manage/'.$volunteer->volunteer_id; ?>"><?php echo $volunteer->volunteer_firstName.' '.$volunteer->volunteer_lastName; ?></a>
</td>
<td>
<?php echo $volunteer->volunteer_rank; ?>
</td>
<td data-sort="<?php echo $order; ?>">
<?php echo $result; ?>
</td>
<td>
</td>
<td>
</td>
<td>
<a class="text-msp-lightblue" href="mailto:<?php echo $volunteer->volunteer_email; ?>"><?php echo $volunteer->volunteer_email; ?></a><br />
<a class="text-msp-lightblue" href="tel:<?php echo $volunteer->volunteer_mobile; ?>"><?php echo $volunteer->volunteer_mobile; ?></a>
</td>
<td>
<a target="_blank" class="text-msp-lightblue" href="<?php echo URLROOT.'/admin/volunteer/volunteerForm/'.$volunteer->volunteer_id; ?>">View</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="row mt-4">
<div class="col-5">
<div class="input-group">
<select class="custom-select" id="email" name="email">
<option selected>Update DBS Status...</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<div class="input-group-append">
<button class="btn btn-msp-lightblue text-white" type="submit"><i class="fas fa-paper-plane"></i> Send</button>
</div>
</div>
</div>
</div>
</form>
Try this code. Added new variable $type= ""; and passed in checkbox array.
<input type="checkbox" class="custom-control-input" id="check_<?php echo $Inc;?>" name="check[<?php echo $type;?>][]" value="<?php echo $volunteer->volunteer_id; ?>" />
Checkbox Id also made unique.
<tbody>
<?php
$Inc = 1;
foreach ($data['volunteerData'] as $volunteer) : ?>
<?php
$result = 'DBS Form to be sent';
$order = 0;
$type= "";
if ($volunteer->volunteer_dbsSent) {
$result = 'DBS Form sent to volunteer - '.date('d/m/Y', strtotime($volunteer->volunteer_dbsSent));
$order = 1;
$type= "dbsSent";
}
if ($volunteer->volunteer_dbsReceived) {
$result = 'DBS Form returned to us - '.date('d/m/Y', strtotime($volunteer->volunteer_dbsReceived));
$order = 2;
$type= "dbsReceived";
}
if ($volunteer->volunteer_dbsASTO) {
$result = 'DBS Form sent to ASTO - '.date('d/m/Y', strtotime($volunteer->volunteer_dbsASTO));
$order = 3;
$type= "dbsASTO";
}
if ($volunteer->volunteer_dbsReturned) {
$result = 'DBS returned - '.date('d/m/Y', strtotime($volunteer_dbsReturned));
$order = 4;
$type= "dbsReturned";
}
if ($volunteer->volunteer_dbsClear) {
$result = 'DBS clear, cert number: - '.$volunteer->volunteer_dbsCertNum;
$order = 5;
$type= "dbsClear";
}
?>
<tr>
<td>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="check_<?php echo $Inc;?>" name="check[<?php echo $type;?>][]" value="<?php echo $volunteer->volunteer_id; ?>" />
<label class="custom-control-label" for="check"></label>
</div>
</td>
<td>
<a class="text-msp-lightblue" href="<?php echo URLROOT.'/admin/volunteer/manage/'.$volunteer->volunteer_id; ?>"><?php echo $volunteer->volunteer_firstName.' '.$volunteer->volunteer_lastName; ?></a>
</td>
<td>
<?php echo $volunteer->volunteer_rank; ?>
</td>
<td data-sort="<?php echo $order; ?>">
<?php echo $result; ?>
</td>
<td>
</td>
<td>
</td>
<td>
<a class="text-msp-lightblue" href="mailto:<?php echo $volunteer->volunteer_email; ?>"><?php echo $volunteer->volunteer_email; ?></a><br />
<a class="text-msp-lightblue" href="tel:<?php echo $volunteer->volunteer_mobile; ?>"><?php echo $volunteer->volunteer_mobile; ?></a>
</td>
<td>
<a target="_blank" class="text-msp-lightblue" href="<?php echo URLROOT.'/admin/volunteer/volunteerForm/'.$volunteer->volunteer_id; ?>">View</a>
</td>
</tr>
<?php
$Inc++;
endforeach; ?>
</tbody>

Update shopping cart quantity without update other products

I'm trying to work out how to update my shopping cart without updating other products. Should I be working with sessions here or not? MY current issue is that whenever I change the quantity it updates the other products as well and sets the quantity in the box back to 1. How would I go about changing this?
This is what I currently have, I understand why it updates all the products but I can't figure out how to do it otherwise.
<?php
session_start();
include("header.php");
include_once("dbconnect.php");
include("functies.php");
if (empty($_SESSION['cart'])) {
echo "U heeft geen producten in uw winkelwagen";
} else {
$items = $_SESSION['cart'];
$cartitems = explode(",", $items);
?>
<div align="center">
<?php titel(); ?>
<h1 Winkelwagen <h1>
</div>
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-10 col-md-offset-1">
<table class="table table-hover">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Total</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php
$total = 0;
$i=1;
foreach ($cartitems as $key=>$id) {
$sql = "SELECT * FROM products WHERE id = $id";
$res=mysqli_query($conn, $sql);
$r = mysqli_fetch_assoc($res);
$sqlb = "SELECT * FROM brewery WHERE code = $r[brewery_code]";
$resb=mysqli_query($conn, $sqlb);
$rb = mysqli_fetch_assoc($resb);
if (isset($_POST['submit'])) {
$amount = $_POST['amount'];
} else $amount = 1;
?>
<tr>
<td class="col-sm-8 col-md-6">
<div class="media">
<img class="thumbnail pull-left" src="Images/<?php echo $r['name'] ?>.jpg" width="85" height="152" alt="..." >
<div class="media-body">
<h4 class="media-heading"><?php echo $r['name']; ?></h4>
<h5 class="media-heading"> by <?php echo $rb['name'];; ?></a></h5>
<span>Status: </span><span class="text-success"><strong>In Stock</strong></span>
</div>
</div></td>
<td class="col-sm-1 col-md-1" style="text-align: center">
<form action="" method="post">
<input type="number" class="form-control" name="amount" value="1" min="1">
<input type="submit" name="submit" class="btn btn-primary btn-sm">
</form>
</td>
<?php
$total = $total + $r['price'];
$i++;
$producttotal = $amount * $r['price'];
?>
<td class="col-sm-1 col-md-1 text-center"><strong>€ <?php echo number_format($r['price'],2);?> </strong></td>
<td class="col-sm-1 col-md-1 text-center"><strong>€ <?php echo number_format($producttotal,2);?> </strong></td>
<td class="col-sm-1 col-md-1">
<button type="button" class="btn btn-danger">
Verwijderen
</button></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td>   </td>
<td>   </td>
<td>   </td>
<td><h5>Subtotal<br>Estimated shipping</h5><h3>Total</h3></td>
<td class="text-right"><h5><strong>$24.59<br>$6.94</strong></h5><h3>$31.53</h3></td>
</tr>
<tr>
<td>   </td>
<td>   </td>
<td>   </td>
<td>
<button type="button" class="btn btn-primary"> Continue Shopping </button></td>
<td>
<button type="button" class="btn btn-primary"> Checkout </button>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<?php } ?>
Your form needs to contain an indicator for which product you want to increase the quantity. For example, like this:
<form action="" method="post">
<input type="number" class="form-control" name="amount[<?php echo $id;?>]" value="1" min="1">
<input type="submit" name="submit" class="btn btn-primary btn-sm">
</form>
You can then evaluate the id like this:
if (isset($_POST['submit']) && isset($_POST['amount'][$id])) {
$amount = $_POST['amount'][$id];
} else {
$amount = 1;
}
I don't understand why you would set the amount to 1 if it hasn't be set in the $_POST. I think you have to store the amount per product in the session, not just the ids as you are doing now.
Maybe like this:
if (isset($_POST['submit']) && isset($_POST['amount'][$id])) {
$amount = intval($_POST['amount'][$id]);
} else {
if(isset($_SESSION['amounts'][$id])) {
$amount = $_SESSION['amounts'][$id];
} else {
$amount = 1;
}
}
if(!isset($_SESSION['amounts'])) $_SESSION['amounts'] = array();
$_SESSION['amounts'][$id] = $amount;

Codeigniter: how to do hit counter for each news

I'm developing website which advertises used cars for sell in codeigniter. I want to do hit counter for each news by method in controller. When user clicks to news the modal of this news opens and it should add 1 to my hitCounter column in database. I tried many codes and ways to do this but it is not working. If someone please can suggest what to do in this case. Thanks in advance!
Here my controller's method code:
public function clickCounter($id)
{
$this->news_model->set_counter($id);
}
Here my views code:
<?php foreach ($news as $news_item): ?>
<div class="font-icon-list col-lg-3 col-md-3 col-sm-4 col-xs-12" style="padding: 15px;" onclick="document.getElementById('<?php echo $news_item['id']; ?>').style.display='block'; ">
<div class="font-icon-detail"><img src="<?php echo base_url(); echo "images/thumb/images/"; echo $news_item['image_path']; ?>" alt="" style=" max-width: 220px; height:100%;">
<input type="text" value="<?php echo $news_item['location']; echo " - "; echo $news_item['price']; ?>">
<input type="text" value="<?php echo $news_item['telno']; ?>">
</div>
</div>
<div id="<?php echo $news_item['id']; ?>" class="w3-modal">
<div class="w3-modal-content w3-animate-zoom" >
<header class="w3-container">
<span onclick="document.getElementById('<?php echo $news_item['id']; ?>').style.display='none'"
class="w3-closebtn">×</span>
</header>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12" style="background-color: white; padding:0;">
<table class="table table-hover table-striped" style="white-space:wrap; overflow:hidden;">
<tr>
<td colspan="2" class="text-center"><?php echo $news_item['title']; ?></td>
</tr> <tr>
<td>Сана</td><td><?php echo $news_item['date']; ?></td>
</tr>
<tr >
<td>Нархи</td><td><?php echo $news_item['price']; ?></td>
</tr>
<tr>
<td>Исми ва шарифи</td><td><?php echo $news_item['name']; ?></td>
</tr>
<tr>
<td>Телефон рақам</td><td><?php echo $news_item['telno']; ?></td>
</tr>
<tr>
<td colspan="2" class="text-center">Қўшимча маълумот:</td>
</tr>
<tr>
<td class="text-justify" colspan="2"><?php echo $news_item['info']; ?></td>
</tr>
</table>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
Here my model code:
public function set_counter($id)
{
$sql = "SELECT * FROM avto WHERE id = ?" ;
$query = $this->db->query($sql, $id);
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data['hitCounter'] = $row['hitCounter'];
}
$numHits= $data['hitCounter'];
$numHits = $numHits + 1;
$data = array(
'hitCounter' => $numHits,
);
$this->db->where('id', $id);
$this->db->update('avto', $data);
}
return false;
}
Step 1: Call controller function onClick
<button type="button" class="btn btn-success"
onclick="<?php echo base_url()?>controller/function">Click Here</button>
Step 2: In Controller define respective function and add update query..
you have to update count in table because in real-time counter can't be stored in session as there are multiple users are using website
now add table named as tbl_count and apply below query
$qry = "UPDATE `tbl_count` SET `hits`=`hits` +1 WHERE `news_id` = '".$news_id."'";
Your model function should be something like this
public function set_counter($id)
{
if($id>0)
{
$sql = "UPDATE avto SET hitCounter = hitCounter + 1 WHERE id = ".$id ;
$this->db->query($sql);
}
}

Call php function when click a button

I have a code :
<?php
getPriceListHeader();
function getPriceListDetail($PriceListCode)
{
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = "SELECT * FROM pricelisdetail where pricelist_code='".$PriceListCode."'";
$results = $readConnection->fetchAll($query);
echo "<table id='tbdata'>
<thead>
<tr>
<th>Price List Code</th>
<th>Price List Name</th>
<th>Effective From</th>
<th>Effective To</th>
</tr>
</thead>
<tbody> ";
foreach ($results as $row)
{
echo "<tr>";
echo "<td> ".$row[entity_id];
echo "<td> ".$row[sku];
echo "<td> ".$row[sku];
echo "<td> ".$row[sku];
};
echo " </tbody>
</table> ";
}
function getPriceListHeader()
{
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = 'SELECT * FROM pricelistheader';
$results = $readConnection->fetchAll($query);
echo "
<h2>Price List</h2>
<div>
<h3>Please select Price List</h3>
<div>
<select class='element select large' id='pricelist' name='element_2'>";
foreach ($results as $row)
{
echo '<option value="' . $row[entity_id]. '">' . $row[sku] . '</option>';
}
echo "</select>
</div>
<input type='button' class='button' name='insert' value='Get Data' onclick='getPriceListDetail(pricelist.value)'/>
";
getPriceListDetail('');
}
?>
I have a dropdown list, a button, a table
When I select a value from dropdown list, then I click button , table will be filled data again. There are 2 method, getPriceListHeader(): load data header when load the page, getPriceListDetail : load data detail when click a button. I try to put event getPriceListDetail(value) to button, but when I click, nothing happens
Please help me how to do this.
Yes, you can call php via ajax request to server like this (very simple):
Note that the following code uses jQuery
jQuery.ajax({
type: "POST",
url: 'my_php_function.php',
dataType: 'name_the_data_type',
success: function (data) {
// here you will get the response your function
}
});
and my_php_function.php like this:
<?php
// here is your php code or function
?>
from the source How can I call PHP functions by JavaScript?
You can't attach PHP function to HTML. PHP is server-side language, so after it's displayed in users browser you can't refer to PHP again, unless you reload page.
There are 3 options I think you can do:
Reload page after changing select page and using GET prepare new data.
Send all data to user browser and than show only part of it related to selected option.
Use AJAX and ask server for new data in background.
Finally, I found out the way.It works for me. Now, I do not understand the code , I am trying to read and get it clearly.
Thanks all for your comments.
$to="";
$from="";
$show_order_statuses = 0;
$orserstatus = "";
$result_order = 0;
//var_dump($results);
//return;
if(!empty($_REQUEST['filter_type']))
{
$orders_row = array();
$filter_type = $_REQUEST['filter_type'];
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = " SELECT * FROM pricelistitem where pricelist_code='".$filter_type."' ";
// $query = 'SELECT * FROM pricelistheader1';
$results = $readConnection->fetchAll($query);
foreach ($results as $rowid)
{
$result_order=10;
$orders_row[]=array($rowid['pricelist_code'],$rowid['product_code'],number_format( $rowid['unitprice'],2),$rowid['UOM']);
// $orders_row[]=array(1,1,1,1,1);
}
}
?>
<div id="anchor-content" class="middle">
<div id="page:main-container">
<div class="content-header">
<table cellspacing="0">
<tbody>
<tr>
<td style="width:50%;"><h3 class="icon-head head-report-sales-sales"><?php echo $this->__("Price List");?></h3></td>
<td class="form-buttons"><button style="" onclick="filterFormSubmit.submit()" class="scalable " type="button" id="id_<?php echo Mage::getSingleton('core/session')->getFormKey() ?>"><span>Show Report</span></button></td>
</tr>
</tbody>
</table>
</div>
<div>
<div class="entry-edit">
<form method="get" action="<?php echo Mage::helper('core/url')->getCurrentUrl();?>" id="filter_form">
<?php /*?><input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" /><?php */?>
<div class="entry-edit-head">
<h4 class="icon-head head-edit-form fieldset-legend">Filter</h4>
<div class="form-buttons"></div>
</div>
<div id="sales_report_base_fieldset" class="fieldset">
<div class="hor-scroll">
<table cellspacing="0" class="form-list">
<tbody>
<tr>
<td class="label"><label for="sales_report_filter_type">Filter By <span class="required">*</span></label></td>
<td class="value">
<select class="required-entry select" name="filter_type" id="sales_report_filter_type" onchange="myFunction();">
<?php
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = " SELECT * FROM pricelistheader ";
$results = $readConnection->fetchAll($query);
$so=1;
foreach ($results as $row)
{
$selected='';
if ($filter_type==$row[pricelist_code])
$selected= ' selected=selected';
else
$selected='';
echo '<option value="' . $row[pricelist_code]. '" '.$selected.' >' . $row[pricelist_name].' '. $row[pricelist_code] . '</option>';
}
?>
</select>
</tr>
<tr>
<td class="label"><label for="effect_from">Effect From </label></td>
<td class="value">
<?php
foreach ($results as $row)
{
if ($filter_type==$row[pricelist_code])
echo $row[pricelist_fromdate];
}
?>
</td>
</tr>
<tr>
<td class="label"><label for="effect_from">Effect To </label></td>
<td class="value">
<?php
foreach ($results as $row)
{
if ($filter_type==$row[pricelist_code])
echo $row[pricelist_todate];
}
?>
</td>
</tr>
</tbody>
<script>
function myFunction() {
// document.getElementById("tbdata").deleteRow(1);
var rowCount = tbdata.rows.length;
for (var i = rowCount - 1; i > 0; i--) {
tbdata.deleteRow(i);
}
srt.value=pricelist.options[pricelist.selectedIndex].value;
";
//$('#tbdata').empty();
}
</script>
</table>
</div>
</div>
</form>
</div>
<script type="text/javascript">
//<![CDATA[
var filterFormSubmit = new varienForm('filter_form');
//]]>
</script>
<script type="text/javascript"> new FormElementDependenceController({"sales_report_order_statuses":{"sales_report_show_order_statuses":"1"}}); </script>
<style type="text/css">
.no-display{display:none;}
</style>
</div>
<div>
<?php if($result_order>0){?>
<table cellspacing="0" class="actions">
<tbody>
<tr>
<td class="pager"> </td>
<td class="export a-right">
<form method="post" action="<?php echo $this->getUrl('*/*/exportCsv')?>" id="csv_form_customer">
<input name="form_key_customer" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />
</form>
<script type="text/javascript">
//<![CDATA[
var csvFormSubmitcustomer = new varienForm('csv_form_customer');
//]]>
</script>
</td>
<td class="filter-actions a-right">
<img class="v-middle" alt="" src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);?>skin/adminhtml/default/default/images/icon_export.gif"> Export to:
<select style="width:8em;" id="sales_order_grid_export_customer" name="sales_order_grid_export_customer">
<option value="<?php echo $this->getUrl('*/*/exportCsv')?>">CSV</option>
</select>
<button onclick="csvFormSubmitcustomer.submit()" class="scalable task" type="button"><span>Export</span></button>
</td>
</tr>
</tbody>
</table>
<?php } ?>
<div id="id_customer<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" class="print_customer<?php echo Mage::getSingleton('core/session')->getFormKey() ?>">
<div class="grid">
<div class="hor-scroll">
<table cellspacing="0" id="id_customer<?php echo Mage::getSingleton('core/session')->getFormKey() ?>_table" class="data">
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr class="headings">
<th class=" no-link"><span class="nobr">Price List Code</span></th>
<th class=" no-link"><span class="nobr">Cust Code</span></th>
<th class=" no-link"><span class="nobr">Cust Name</span></th>
</tr>
</thead>
<tbody id="">
<?php
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = " SELECT * FROM " . $resource->getTableName('catalog/product');;
$customercount=0;
$customerresults = $readConnection->fetchAll($query);
$customerresults = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('erp_pricelistcode_1', $filter_type)
// ->addFieldToSelect (array('created_at','customer_id','increment_id','updated_at','status','entity_id','state'))
;
// ->addAttributeToFilter('erp_pricelistcode_1','00')->load();
$so=1;
foreach ($customerresults as $row) {
$customercount++;
}
// var_dump(#$customerresults);
if($customercount>0){
foreach($customerresults as $singlerows){
$cot=0;
{
echo "<tr>";
{
$cot++;
?>
<td>
<?php
echo $singlerows->getData('erp_pricelistcode_1');
?>
</td>
<td>
<?php
echo $singlerows->getFirstname();
?>
</td>
<td>
<?php
echo $singlerows->getName();
?>
</td>
<?php
}
echo "</tr>";
}
}
}else{
?>
<tr class="even">
<td colspan="13" class="empty-text a-center">No records found.</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<div>
<?php if($result_order>0){?>
<table cellspacing="0" class="actions">
<tbody>
<tr>
<td class="pager"> </td>
<td class="export a-right">
<form method="post" action="<?php echo $this->getUrl('*/*/exportCsv')?>" id="csv_form">
<input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />
</form>
<script type="text/javascript">
//<![CDATA[
var csvFormSubmit = new varienForm('csv_form');
//]]>
</script>
</td>
<td class="filter-actions a-right">
<img class="v-middle" alt="" src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);?>skin/adminhtml/default/default/images/icon_export.gif"> Export to:
<select style="width:8em;" id="sales_order_grid_export" name="sales_order_grid_export">
<option value="<?php echo $this->getUrl('*/*/exportCsv')?>">CSV</option>
</select>
<button onclick="csvFormSubmit.submit()" class="scalable task" type="button"><span>Export</span></button>
</td>
</tr>
</tbody>
</table>
<?php } ?>
<div id="id_<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" class="print_<?php echo Mage::getSingleton('core/session')->getFormKey() ?>">
<div class="grid">
<div class="hor-scroll">
<table cellspacing="0" id="id_<?php echo Mage::getSingleton('core/session')->getFormKey() ?>_table" class="data">
<colgroup>
<col>
<col>
<col>
<col>
</colgroup>
<thead>
<tr class="headings">
<th class=" no-link"><span class="nobr">Price List Code</span></th>
<th class=" no-link"><span class="nobr">Product Code</span></th>
<th class=" no-link"><span class="nobr">Unit Price</span></th>
<th class=" no-link"><span class="nobr">UOM</span></th>
</tr>
</thead>
<tbody id="">
<?php
$cot=0;
if(count($orders_row)>0){
foreach($orders_row as $singlerows){
$cot=0;
if(!empty($singlerows)){
echo "<tr>";
foreach($singlerows as $value){
$cot++;
?>
<td>
<?php
if ($cot==3 )
echo "<div style='float:right;width:30%;'>";
echo $value;
echo "</div>";
?>
</td>
<?php
}
echo "</tr>";
}
}
}else{
?>
<tr class="even">
<td colspan="13" class="empty-text a-center">No records found.</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>

Categories