Generating a button on php checkbox selection from mysql - php

I have this project where the user selects items using a checkbox and then a button is generated from that item's name.
<!DOCTYPE html>
<html>
<head>
<title>webs</title>
</head>
<body>
<h2>Select User:</h2>
<div>
<form method="POST">
<table border="1">
<thead>
<th></th>
<th>Subject</th>
</thead>
<tbody>
<?php
include('get.php');
$query=mysqli_query($conn,"select * from `subjects`");
while($row=mysqli_fetch_array($query)){
?>
<tr>
<td><input type="checkbox" value="<?php echo $row['subject']; ?>" name="id[]"></td>
<td><?php echo $row['subject']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div>
<h2>Subjects selected:</h2>
<button class="button"><span><?php
if (isset($_POST['submit'])){
foreach ($_POST['id'] as $id):
$sq=mysqli_query($conn,"select * from `subjects` where subject='$id'");
$srow=mysqli_fetch_array($sq);
echo $srow['subject']."<br>";
endforeach;
}
?></span></button>
</div>
I did make a button but the output was just one big button formed from all selections.
How do I make buttons individually per item? Thanks.
Also, additionally, how can I make this dynamic? no need for a "Submit" button?

You Should try Following code For generate Separate Button.
<!DOCTYPE html>
<html>
<head>
<title>webs</title>
</head>
<body>
<h2>Select User:</h2>
<div>
<form method="POST">
<table border="1">
<thead>
<th></th>
<th>Subject</th>
</thead>
<tbody>
<?php
include('get.php');
$query=mysqli_query($conn,"select * from `subjects`");
while($row=mysqli_fetch_array($query)){
?>
<tr>
<td><input type="checkbox" value="<?php echo $row['subject']; ?>" name="id[]"></td>
<td><?php echo $row['subject']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div>
<h2>Subjects selected:</h2>
<?php
if (isset($_POST['submit'])){
foreach ($_POST['id'] as $id):
$sq=mysqli_query($conn,"select * from `subjects` where subject='$id'");
$srow=mysqli_fetch_array($sq);
?>
<button class="button">
<span>
<?php echo $srow['subject']; ?>
</span>
</button>
<?php
endforeach;
}
?>
</div>

I think you will use JavaScript for this I'm giving you syntax in JavaScript, because JavaScript is the best way to make it dynamic.
First arrange PHP code
include 'get.php';
$query = mysqli_query($conn, "select * from `subjects`");
while ($row = mysqli_fetch_array($query)) {
$subject = $row['subject'];
echo "<tr>
<td><input type='checkbox' onclick='validate()' value='".$subject."' name='id[]' id='myCheck'></td>
<td> ".$subject."</td>
</tr>";
?>
Then JavaScript
function validate() {
var check = document.getElementById("myCheck").checked = true;
var val = document.getElementById("myCheck").value;
document.getElementById("myCheck").style.display = "none";
document.getElementById("myBtn").style.display = "block";
document.getElementById("myBtn").value = val;
}
Button
<button class="button animate" id="myBtn">
Adding animation to button
.animate {
-webkit-animation: animatezoom 0.6s;
animation: animatezoom 0.6s
}
#-webkit-keyframes animatezoom {
from {-webkit-transform: scale(0)}
to {-webkit-transform: scale(1)}
}
#keyframes animatezoom {
from {transform: scale(0)}
to {transform: scale(1)}
}

You need to put <button class="button"> inside foreach, mitkosoft thats right.

Related

PHP delete function?

PHP beginner here, probably bind to this mistake. Got a crud function going on here, trying to get the delete button to work. Users would currently be on the /crud/view.php. It's currently asking "do you want to delete" followed by the screen refreshing and nothing happening.
<?php
session_start();
if(isset($_SESSION['u_uid'])){
$uid = $_SESSION['u_id'];
require_once('connect.php');
$ReadSql = "SELECT * FROM `contact` WHERE users_id=$uid ORDER BY Name";
$res = mysqli_query($connection, $ReadSql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Motoko</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</head>
<body>
<div class="container">
<div class="row">
<table class="table">
<tr>
<th><strong>Extras</strong></th>
</tr>
<?php
while($r = mysqli_fetch_assoc($res)){
?>
<tr>
<td>Edit
</td>
<td><input type="button" onClick="deleteme(<?php echo
$r['u_uid']; ?>)" name="Delete" value="Delete"></td>
</tr>
<script language="Javascript">
function deleteme(delid)
{
if(confirm("Are you sure you want to Delete?")){
window.location.href='delete.php';
}
}
</script>
<?php } ?>
</table>
</div>
</body>
</html>
<?php
}else{
header("Location: http://motoko.sorainsurance.com.au");
}
?>
With the /delete.php being:
<?php
if(isset($_SESSION['u_uid'])){
require_once('connect.php');
$select = "DELETE from contact where id='".$_GET['del_id']."'";
$query = mysqli_query($connection, $select) or die($select);
}else{
header("Location: http://motoko.sorainsurance.com.au/crud/view.php");
}
?>
Change these lines
<input type="button" onClick="deleteme('<?php echo
$r['u_uid']; ?>')" name="Delete" value="Delete">
function deleteme(delid){
if(confirm("Are you sure you want to Delete?")){
window.location.href='delete.php?del_id='+delid;
}
}
Always preferred to write you php code at top of HTML script
<?php
session_start();
if(!isset($_SESSION['u_uid'])){
header("Location: http://motoko.sorainsurance.com.au");
}
$uid = $_SESSION['u_id'];
require_once('connect.php');
$ReadSql = "SELECT * FROM `contact` WHERE users_id=$uid ORDER BY Name";
$res = mysqli_query($connection, $ReadSql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Motoko</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</head>
<body>
<div class="container">
<div class="row">
<table class="table">
<tr>
<th>
<strong>Extras</strong>
</th>
</tr>
<?php while($r = mysqli_fetch_assoc($res)){ ?>
<tr>
<td>
Edit
</td>
<td>
<input type="button" onClick="deleteme('<?php echo $r['u_uid']; ?>')" name="Delete" value="Delete">
</td>
</tr>
<?php } ?>
</table>
</div>
</body>
</html>
<script language="Javascript">
function deleteme(delid){
if(confirm("Are you sure you want to Delete?")){
window.location.href='delete.php?del_id=delid';
}
}
</script>
<form>
<input type="button" value="Search Contact 1.0" onclick="window.location.href='http://motoko.sorainsurance.com.au/crud/searchone.php'" />
</form>
<form>
<input type="button" value="Search Contact 2.0" onclick="window.location.href='http://motoko.sorainsurance.com.au/crud/search.php'" />
</form>
<html>
<head>
<title>Motoko</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<table class="table">
<tr>
<th><strong>Name</strong></th>
<th><strong>Company</strong></th>
<th><strong>Title</strong></th>
<th><strong>Phone</strong></th>
<th><strong>Email</strong></th>
<th><strong>Address</strong></th>
<th><strong>Extras</strong></th>
</tr>
<?php
while($r = mysqli_fetch_assoc($res)){
?>
<tr>
<td><?php echo $r['Name']; ?></td>
<td><?php echo $r['Company']; ?></td>
<td><?php echo $r['Title']; ?></td>
<td><?php echo $r['Phone']; ?></td>
<td><?php echo $r['Email']; ?></td>
<td><?php echo $r['Address']; ?></td>
<td>Edit</td>
<td> <input type="button" onClick="deleteme(<?php echo $r['u_uid']; ?>)" name="Delete" value="Delete">
</tr>
<script language="Javascript">
function deleteme(delid) {
if(confirm("Are you sure you want to Delete?")){
window.location.href='delete.php?del_id='+delid;
}
}
</script>
<?php } ?>
</table>
</div>
</body>
</html>
<?php
}else{
header("Location: http://motoko.sorainsurance.com.au");
}
?>
Could you try ?
$select = "DELETE from contact where id='".$_GET['u_uid']."'";

Get class element

I make Jquery to read data from db and when I click the list it shown roe data on detail box.
But.... problem: I make div where I show content. I load page with Jquery to div.
but when I do this the row click dont work. I can not understan why. It is shild element but id i understan right when I use getElementById it should to take current row, but no.
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<?php include './config/init.php'; ?>
<html>
<head>
<meta charset="UTF-8">
<title>Biisilista</title>
<script src="./js/jquery-3.2.1.js"></script>
<link href="css/basic.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>KaraokeBiisit </h1>
<div id="edit" style="display:none">
<div>
<form name="formedit" method="post" action="">
<table id="edittable" border="1" cellspacing="2" cellpadding="1">
<tbody>
<tr>
<td>
<label>Nimi:</label>
</td>
<td>
<input id="nimi" name="nimi" placeholder="Kappaleen nimi" type="text">
</td>
<td>
<label>Levy:</label>
</td>
<td>
<input id="levy" name="levy" placeholder="Levyn tunnus" type="text" width="10px">
</td>
</tr>
<tr>
<td>
<label>Artisti:</label>
</td>
<td>
<input id="artisti" name="artisti" placeholder="Kappaleen esittäjä" type="text">
</td>
<td>
<label>Kieli:</label>
</td>
<td>
<input id="kieli" name="kieli" placeholder="Alkuperäiskieli" type="text" width="20">
</td>
</tr>
<tr>
<td>
<label>Numero:</label>
</td>
<td>
<input id="numero" name="numeron" placeholder="Numero" type="text">
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
<div id="pageContent">
</div>
<script src="./js/jquery-3.2.1.js"></script>
<script src="./js/script.js"></script>
</body>
</html>
jQuery(document).ready(function ($) {
$("#pageContent").click(function () {
$('tr').removeClass('selected');
$(this).addClass('selected');
var selectedRow;
selectedRow = $(rivi);
var td = $(selectedRow).children('td');
$('#nimi').val(td[0].innerText);
$('#artisti').val(td[1].innerText);
$('#levy').val(td[2].innerText);
$('#kieli').val(td[3].innerText);
$('#numero').val(td[4].innerText);
console.log("test");
});
$(".clickable-row").on('click', () => {
$('#edit').show();
});
$('#pageContent').load('container.php');
// $('#pageContent').load('biisit.php');
});
function showBiisit() {
console.log("Näytetään sisältö");
$('#pageContent').load('container.php');
}
<?php include './config/init.php'; ?>
<?php
//luodaan tietokantaobjekti
$db = new DataBase();
// tehdään kysely
$db->query("SELECT * FROM kappaleet");
//query("SELECT `id`,`nimi`,`artisti`,`levy`,`kieli`,`numero` FROM `kappaleet`;");
//yhdistetään hakutulokseen
$kappaleet = $db->resultset();
?>
<table id="dataTable">
<tr>
<th>Nimi</th>
<th>Artisti</th>
<th width="100" align="left">Levy</th>
<th width="100" align="left">Kieli</th>
<th width="100" align="left">Numero</th>
</tr>
<?php foreach ($kappaleet as $biisi): ?>
<tr class='clickable-row' >
<td><?php echo $biisi->nimi ?></td>
<td><?php echo $biisi->artisti ?></td>
<td><?php echo $biisi->levy ?></td>
<td><?php echo $biisi->kieli ?></td>
<td><?php echo $biisi->numero ?></td>
</tr>
<?php endforeach; ?>
</table>
try this
...
$("body").on('click', '.clickable-row', function () { //i change this line
$('tr').removeClass('selected');
$(this).addClass('selected');
var selectedRow = $(this);
//selectedRow = $(rivi); idk what is this
var td = selectedRow.children('td');
$('#nimi').val(td[0].innerText);
$('#artisti').val(td[1].innerText);
$('#levy').val(td[2].innerText);
$('#kieli').val(td[3].innerText);
$('#numero').val(td[4].innerText);
console.log("test");
});
...

How can I change the background color of div if the condition is met?

Here is the code for notification code:
<?php if(isset($notification) && $notification->result() >0 ){?>
<div class="panel-heading pull-right col-md-6"
style="height:140px; margin-top:-140px; background-color:white; overflow-y: scroll;">
<h5><strong>Student with 3 Consecutive Absences</strong></h5>
<table class="table">
<thead>
<th>Course Code-Section</th>
<th>Student Name</th>
<th>View</th>
</thead>
<tbody>
<?php foreach($notification->result() as $notif)
{
if($notif->Total >=3)
{
?>
<tr>
<td><?php echo $notif->Course_Code_Section?</td>
<td><?php echo $notif->Student?></td>
<td>
<form action="<?php echo base_url();?>index.php/attendance/check" method="post" target="_blank">
<input type="hidden" name="CID" value="<?php echo $notif->CID;?>">
<button class="btn btn-xs btn-success"><i class="icon-eye-open"></i> View</button>
<?php echo form_close();?>
</td>
</tr>
</div>
<?php }?>
<?php }?>
</tbody>
</table>
</div>
<?php }?>
Here is the notification view, the default background color is white. Therefore, I want it to make the background color red when the condition met.
Try this:
<?php
$style = '';
if(isset($notification) && $notification->result() > 0 )
{
$style = 'style="color:red"';
// Put your css style property here
}
?>
Html:
<div <?php echo $style ?>>
</div>
You can do as -
<?php
if(your condition)
{
?>
<style>
#your_div
{
background:red !important;
}
</style>
<?php
}
else
{
?>
<style>
#your_div
{
background:white !important;
}
</style>
<?php
}
?>
If your condition is true in PHP you can just this line in your tag:
<tr bgcolor="#FF0000">
I don't know if my html code will appear or not. Please refer this site:
https://www.w3schools.com/tags/att_tr_bgcolor.asp
Please try this code ,i hope this is your condition
<?php
$bcolor ='background-color:white';
if(isset($notification) && $notification->result() >0 ){
$bcolor ='background-color:white';
}?>
<div class="panel-heading pull-right col-md-6"
style="height:140px; margin-top:-140px; <?php echo $bcolor ;?> overflow-y: scroll;">
<h5><strong>Student with 3 Consecutive Absences</strong></h5>
<table class="table">
<thead>
<th>Course Code-Section</th>
<th>Student Name</th>
<th>View</th>
</thead>
<tbody>
<?php foreach($notification->result() as $notif)
{
if($notif->Total >=3)
{
?>
<tr>
<td><?php echo $notif->Course_Code_Section?</td>
<td><?php echo $notif->Student?></td>
<td>
<form action="<?php echo base_url();?>index.php/attendance/check" method="post" target="_blank">
<input type="hidden" name="CID" value="<?php echo $notif->CID;?>">
<button class="btn btn-xs btn-success"><i class="icon-eye-open"></i> View</button>
<?php echo form_close();?>
</td>
</tr>
</div>
<?php }?>
<?php }?>
</tbody>
</table>
</div>
try
<?php
$bg_red = '';
if (condition) {
$bg_red = '<style="background-color: red;">';
}
?>
<tr <php? echo $bg_red; ?>>
<td></td>
<td></td>
<td></td>
</tr>

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>

Errors appear in searching if a record not found using searchtext

SearchText works if record is found but errors appear when record not found.
Here are the errors. Notice: Undefined variable: sample_list in C:\xampp\htdocs\viewsample\samplelist.php on line 166
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\ viewsample\samplelist.php on line 166
If I click the search button again, errors disappear.
Is it possible to return to home page if record not found?
I searched here a possible solution to my problem but I found none.
Please help.
Thank you and more power.
Here's the code.
Index.php
//Perform Search from our database
if(isset($_POST['action_type']))
{
echo 'Welcome';
if ($_POST['action_type'] == 'search')
{
$search = mysqli_real_escape_string($link, strip_tags($_POST['searchText']));
$sql = "select samp_id, daterecv, datecoll, modcoll, aperson, estabname, estabadd, gname, bname, prodcat, dform, dstrength, from sample
where gname like '%$search%' or bname like '%$search%' or estabname like '%$search%'";
$result = mysqli_query($link, $sql);
if(!$result)
{
echo mysqli_error($link);
exit();
}
//Loop through each row on array and store the data to $sample_list[]
while($rows = mysqli_fetch_array($result))
{
$sample_list[] = array('samp_id' => $rows['samp_id'],
'daterecv' => $rows['daterecv'],
'datecoll' => $rows['datecoll'],
'modcoll' => $rows['modcoll'],
'apers' => $rows['apers'],
'estabname' => $rows['estabname'],
'estabadd' => $rows['estabadd'],
'gname' => $rows['gname'],
'bname' => $rows['bname'],
'prodcat' => $rows['prodcat'],
'dform' => $rows['dform'],
'dstrength' => $rows['dstrength']);
}
include 'samplelist.php';
exit();
}
}
samplelist.php
<?php
session_start();
$role = $_SESSION['sess_userrole'];
if(!isset($_SESSION['sess_username']) && $role!="sampler"){
header('Location: index.php?err=2');
}
?>
<?php
include_once 'index.php';
?>
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function GotoHome(){
window.location = 'index.php';
}
{
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
}
</script>
</head>
<body>
<div class="wrapper">
<div class="content">
<p>Logout</p>
<p><center><b><font style="arial" color="black">SAMPLE COLLECTION</font></b></center></p>
<div style="margin-bottom: 10px;">
<form method="POST" action="index.php">
<input type="text" id="searchText" name="searchText" style="width:300px"/>
<input type="hidden" name="action_type" value="search" onfocus="Clear (this);"/>
<input type="submit" value="search"/>
</form>
</div>
<div style="max-height: 740px; overflow:auto; max-width: 1600; overflow:auto;">
<table class="pbtable">
<thead>
<tr>
<th>
Date Received
</th>
<th>
Date Collected
</th>
<th style = "display:none">
Mode of Collection
</th>
<th style = "display:none">
Assigned Personnel
</th>
<th>
Establishment Name
</th>
<th style = "display:none">
Establishment Address
</th>
<th>
Generic Name
</th>
<th>
Brand Name
</th>
<th>
Product Category
</th>
<th style = "display:none">
Dosage Form
</th>
<th style = "display:none">
Dosage Strength
</th>
</thead>
<tbody>
<?php foreach($sample_list as $collection) : ?>
<tr>
<td>
<?php echo $collection["daterecv"]; ?>
</td>
<td>
<?php echo $collection["datecoll"]; ?>
</td>
<td style = "display:none">
<?php echo $collection["modcoll"]; ?>
</td>
<td style = "display:none">
<?php echo $collection["aperson"]; ?>
</td>
<td>
<?php echo $collection["estabname"]; ?>
</td>
<td style = "display:none">
<?php echo $collection["estabadd"]; ?>
</td>
<td>
<?php echo $collection["gname"]; ?>
</td>
<td>
<?php echo $collection["bname"]; ?>
</td>
<td>
<?php echo $collection["prodcat"]; ?>
</td>
<td style = "display:none">
<?php echo $collection["dform"]; ?>
</td>
<td style = "display:none">
<?php echo $collection["dstrength"]; ?>
</td>
<form method="post" action="index.php">
<input type="hidden" name="ci"
value="<?php echo $collection["samp_id"]; ?>" />
<input type="hidden" name="action" value="edit" />
<input type="submit" value="Edit" />
</form>
<tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
If no records are found in DB the $sample_list array is empty.
So samplelist.php needs this check before foreach loop,
if (empty($sample_list))
{
header('Location: http://www.homesweet.home/');
exit;
}
foreach($sample_list as $collection) :
...
endforeach;

Categories