how to solve Undefined offset: error in php - php

I have a html code where I create a table and two radio button on each row. for giving different name to radio button on each row I used while loop and I++ way.
that is
<form action = "submit_varification.php" method = "POST" onclick = "return validate()">
<div style="position: absolute; left: 50px; top: 90px;">
<label class="right"><font color="white">Date:</font></label>
<input type="text" id = "frmDate" /><br>
<p id="date"></p>
</div>
<div style="position: absolute; left: 250px; top: 91px;">
<label class="right"><font color="white">V-ID:</font></label>
<input type="text" id = "myText" name = "reviewer" value = ""/><br>
</div>
<div style="position: absolute; left: 900px; top: 91px;">
<button type="button" name="show" id="show" onclick = "" >History</button>
</div>
<div style="position: absolute; left: 900px;">
<input type="submit" name="test" id="test" value="Submit" /><br/>
</div>
<script>
var date = new Date();
document.getElementById("frmDate").value = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
</script>
</body>
<table style="position: absolute; width:95%; left: 20px; top: 150px;" id = "table1">
<?php
$myDate = date('m/d/Y');
?>
<tr>
<th>Date</th>
<th>Time</th>
<th>Alias</th>
<th>Machine_Name</th>
<th>Build_Name</th>
<th>Build_version</th>
<th>WinDBG</th>
<th>.Net_Framework</th>
<th>Status</th>
</tr>
<?php
//get records from database
$sql3 = "SELECT * FROM data WHERE `Date` = '".$myDate."' ORDER BY id DESC";
$query = $conn->query($sql3);
if($query->num_rows > 0){
$i = 0 ;
while($row = $query->fetch_assoc()){ ?>
<tr>
<td><?php echo $row['Date']; ?></td>
<td><?php echo $row['Time']; ?></td>
<td><?php echo $row['Alias']; ?></td>
<td><?php echo $row['Machine_Name']; ?></td>
<td><?php echo $row['Build_Name']; ?></td>
<td><?php echo $row['Build_Version']; ?></td>
<td><?php echo $row['WinDBG']; ?></td>
<td><?php echo $row['.NET_Framework']; ?></td>
<td style='white-space: nowrap'><form><label class = "ready"><input type="radio" name="[<?php $i ?>]" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="[<?php $i ?>]" value = "Not Ready" >Not Ready</label></form></td>
</tr>
<?php $i++ ; } } ?>
</table>
</form>
and I want to store the value of each row to a database. so I used POST method on the form. and I am trying to take the value of radio button to database but I am facing a error like
Notice: Undefined offset: 0 in C:\wamp64\www\submit_varification.php on line 33
Notice: Undefined offset: 1 in C:\wamp64\www\submit_varification.php on line 33
Notice: Undefined offset: 2 in C:\wamp64\www\submit_varification.php on line 33
and the PHP code:
$query = $conn->query($sql4);
if($query->num_rows > 0){
$i = 0 ;
while($row = $query->fetch_assoc()){
//...insert into your DB.
$row1 = $row["Date"];
$row2 = $row["Time"];
$row3 = $row["Alias"];
$row4 = $row["Machine_Name"];
$row5 = $row["Build_Name"];
$row6 = $row['Build_Version'];
$row7 = $row["WinDBG"];
$row8 = $row[".NET_Framework"];
$status = $_POST["$i"]; // this is the error
$sql5 = "INSERT INTO history (`Date`, `Time`, `Alias`, `Machine_Name`, `Build_Name`, `Build_version`, `WinDBG`, `.NET_Framework`, `Status`, `Reviewed_By`)
VALUES ('".$row1."','".$row2."','".$row3."','".$row4."','".$row5."','".$row6."','".$row7."','".$row8."', '".$status."', '".$reviewer."') ";
if ($conn->query($sql5) === TRUE) {
//echo "New record created successfully";
//echo nl2br("\n");
echo "";
} else {
echo "Error: " . $sql5 . "<br>" . $conn->error;
}
$i++ ;
}
}
is anyone have any solution for this ?

Dump the array that populates $i for each loop. I would wager the array does not have the array key that the name="[<?php $i ?>]" is expecting.

Can you remove the brackets in the name attribute and see if its working correct. Below is the code:
<td style='white-space: nowrap'>
<form><label class = "ready">
<input type="radio" name="<?php $i ?>" value = "Ready">Ready</label>
<label class = "notready"><input type="radio" name="<?php $i ?>" value = "Not Ready" >Not Ready</label>
</form>
Plus it would be better if you have some static text appended to the name column and in server side, you can loop it:
<td style='white-space: nowrap'>
<form><label class = "ready">
<input type="radio" name="status_<?php $i ?>" value = "Ready">Ready</label>
<label class = "notready"><input type="radio" name="status_<?php $i ?>" value = "Not Ready" >Not Ready</label>
</form>
Let me know if this helps..

You make nested forms. replace the line
<td style='white-space: nowrap'><form><label class = "ready"><input type="radio" name="[<?php $i ?>]" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="[<?php $i ?>]" value = "Not Ready" >Not Ready</label></form></td>
with this:
<td style='white-space: nowrap'><label class = "ready"><input type="radio" name="<?php $i ?>" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="<?php $i ?>" value = "Not Ready" >Not Ready</label></td>
Also remove the brackets, like gopal panadi mentioned.
Furthermore I am not sure if you can have input tags inside labels. shouldn't they be next to each other?
Edit: after that if it fails, dump the $_POST array and see how/if the radio values are in $_POST. var_dump($_POST);die();

Related

jQuery generated elements not recognized on $_POST

I'm developing a Wordpress plugin using PHP and jQuery, the function below is called when the <select> input is changed, so far it works as intended and the inputs are generated properly but when I submit the form, the generated elements are undefined when called in $_POST.
<?php
function random_event() {
global $wpdb;
//Table for all the event details
$tablename = $wpdb->prefix."random_event";
// Table to store all banner stores
$tablename2 = $wpdb->prefix."random_event_banner_stores";
//Table for store all poster
$tablename4 = $wpdb->prefix."random_event_poster";
// Table storing all user registrations
$tablename3 = $wpdb->prefix."random_event_winners";
//Junction table to map the poster to banner store
$tablename5 = $wpdb->prefix."random_event_poster_banner";
//Junction table to map the poster to event
$tablename6 = $wpdb->prefix."random_event_poster_event";
$tablename5 = $wpdb->prefix."random_event_poster_banner";
$sql = "select event.*, banner.name as banner_name, banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
$results = $wpdb->get_results($sql);
$update_this_event = -1;
$banner_stores = [];
//Deletion
if(isset($_POST['delete_event'])) {
$event_id = esc_sql($_POST['event_id']);
$sql = "DELETE from $tablename WHERE id= '" . $event_id . "'";
try{
$event = $wpdb->query($sql);
}
catch (Exception $e) {
echo "<script>console.log($e);</script>";
}
} else if(isset($_POST['update_event'])){
$update_this_event = intval(esc_sql($_POST['event_id']));
$banner_store_id = esc_sql($_POST['banner_id']);
$name = esc_sql($_POST['banner_store_name']);
$description = esc_sql($_POST['banner_store_description']);
$location_note = esc_sql($_POST['banner_store_location_note']);
$address = esc_sql($_POST['banner_store_address']);
$status = esc_sql($_POST['banner_store_status']);
$sql = "UPDATE $tablename SET name = '" . $name . "'
, description = '" . $description . "'
, location_note = '" . $location_note . "'
, address = '" . $address . "'
, status = '" . $status . "' WHERE id = '" . $banner_store_id . "'";
try{
$participants = $wpdb->query($sql);
}
catch (Exception $e) {
echo "<script>console.log($e);</script>";
}
} else if(isset($_POST['select_update_event'])){
$update_this_event = intval(esc_sql($_POST['event_id']));
// $pssql = "select * from $tablename2";
// $banner_stores = $wpdb->get_results($pssql);
$pssql = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.store_id is null";
// $pssql = "select * from $tablename2";
$banner_stores = $wpdb->get_results($pssql);
$pssql2 = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.id = '".$update_this_event."'";
$current_banner_store = $wpdb->get_results($pssql2);
if(count($current_banner_store) != 0) {
array_push($banner_stores, $current_banner_store[0]);
}
$poster_sql = "select ap.*, a.name as poster_name, ap.qty as qty from $tablename6 as ap inner join $tablename4 as a on a.id = ap.poster_id where ap.event_id = $update_this_event";
$poster_event = $wpdb->get_results($poster_sql);
$poster_petone = [];
foreach($results as $result) {
if($result->id == $update_this_event) {
$poster_sql = "select a.* from $tablename5 as ap inner join $tablename4 as a on a.id = ap.poster_id where banner_store_id = ".$result->store_id;
$poster_petone = $wpdb->get_results($poster_sql);
}
}
}else if(isset($_POST['cancel_update_event'])){
$update_this_event = -1;
}else if (isset($_POST['save_update_event'])) {
$update_this_event = intval(esc_sql($_POST['event_id']));
$title = esc_sql($_POST['title']);
$qty = 0;
$description = esc_sql($_POST['description']);
$prize = esc_sql($_POST['prize']);
$event_code = esc_sql($_POST['event_code']);
$event_from = esc_sql($_POST['event_from']);
$event_to = esc_sql($_POST['event_to']);
$banner_store_id = esc_sql($_POST['banner_store_id']);
if(isset($_POST['poster_ids'])){
$poster_ids = $_POST['poster_ids'];
$poster_qtys = $_POST['poster_qty'];
}
$query = "UPDATE $tablename set title='$title',description='$description',event_code='$event_code',valid_from='$event_from',valid_to='$event_to',store_id='$banner_store_id', prize = '$prize' ";
$query .= "where id = $update_this_event";
$result_insert = $wpdb->query($query);
$delete_query = "delete from $tablename6 where event_id = $update_this_event";
$wpdb->query($delete_query);
for($i = 0; $i < count($poster_ids); $i++) {
$poster_id = esc_sql($poster_ids[$i]);
$poster_qty = esc_sql($poster_qtys[$i]);
$poster_query = "INSERT INTO $tablename6 (event_id,poster_id, qty) values ";
$poster_query .= "('$update_this_event','$poster_id','$poster_qty');";
$poster_insert = $wpdb->get_results($poster_query);
$poster_result = $wpdb->insert_id;
}
$update_this_event = -1;
$sql = "select event.*, banner.name as banner_name, banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
$results = $wpdb->get_results($sql);
}
?>
<style type="text/css" emb-not-inline="">
.table-container {
width: 100%;
max-width: 100%;
overflow-x: auto;
}
.hidden {
display: none;
}
.banner-button {
background-color: #ffffff;
border-radius: 5px;
padding: 5px;
font-size: 13px;
min-width: 75px;
}
table {
border: none;
text-align: center;
}
table tr:nth-child(even) {
background-color: #dddddd;
}
table tr:nth-child(odd) {
background-color: #ffffff;
}
table th {
background-color: #23282d;
color: #ffffff;
}
table th:first-child{
border-radius: 20px 0px 0px 0px;
}
table th:last-child{
border-radius: 0px 20px 0px 0px;
}
table {
border-radius: 20px 20px 0px 0px;
}
</style>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<h1>View All events</h1>
<br/>
<div class="table-container" style="
width: 100%;
max-width: 100%;
overflow-x: auto;
">
<table cellpadding="10" border=1 style="border-style: solid #AAA">
<tr>
<th>Title</th>
<th>Description</th>
<th>Prize</th>
<th>event Code</th>
<th>banner Store</th>
<th>poster Qty</th>
<th>Validity</th>
<th>QR code</th>
<th>Action</th>
</tr>
<?php
foreach($results as $result) {
if($update_this_event == $result->id) { ?>
<tr>
<form method="post" name="formtest1" id="formtest1">
<td valign="top"><input type="text" name="title" value="<?php echo $result->title ?>"/> </td>
<td valign="top"><input type="text" name="description" value="<?php echo $result->description ?>"/> </td>
<td valign="top"><input type="text" name="prize" value="<?php echo $result->prize ?>"/> </td>
<td valign="top"><input type="text" name="event_code" value="<?php echo $result->event_code ?>"/> </td>
<td valign="top">
<!-- <select onChange="changebanner(this)" id="banner_store_id" name="banner_store_id"> -->
<select id="banner_store_id" name="banner_store_id">
<?php
foreach($banner_stores as $pstore) {
if($result->banner_id == $pstore->id) {
?>
<option SELECTED value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
<?php
}else {
?>
<option value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
<?php
}
}
?>
</select>
</td>
<td valign="top">
<div id="poster_div">
<table border="0" cellpadding=5>
<?php
if(count($poster_event) == 0) {
for($i = 0; $i < count($poster_petone); $i++)
{
?>
<tr>
<td>
<input type="hidden" name="poster_ids[]" value="<?php echo $poster_petone[$i]->id?>"><?php echo $poster_petone[$i]->name?>
</td>
<td>
<input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_petone[$i]->qty ?>">
</td>
</tr>
<?php
}
}else {
for($i = 0; $i < count($poster_event); $i++)
{
?>
<tr>
<td><input type="hidden" name="poster_ids[]" value="<?php echo $poster_event[$i]->poster_id?>"><?php echo $poster_event[$i]->poster_name?></td>
<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_event[$i]->qty?>"></td>
</tr>
<?php
}
}?>
</table>
</div>
</td>
<td valign="top"><input id="event_from" name="event_from" type="text" value="<?php echo $result->valid_from ?>"/> - <input name="event_to" id="event_to" type="text" value="<?php echo $result->valid_to ?>"/> </td>
<td valign="top"></td>
<td valign="top">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> ">
<input type="submit" name="save_update_event" value="save" class="banner-button">
<input type="submit" name="cancel_update_event" value="cancel" class="banner-button">
</td>
</form>
</tr>
<?php
} else {
?>
<tr>
<td valign="top"><?php echo $result->title ?> </td>
<td valign="top"><?php echo $result->description ?> </td>
<td valign="top"><?php echo $result->prize ?> </td>
<td valign="top"><?php echo $result->event_code ?> </td>
<td valign="top"><?php echo $result->banner_name ?> </td>
<td valign="top"><?php get_poster_of_event($result->id ) ?> </td>
<td valign="top"><?php echo $result->valid_from ?> - <?php echo $result->valid_to ?></td>
<td valign="top"><?php generate_random("https://generic.com/event/?random=".$result->event_code, $result->title) ?> </td>
<td valign="top">
<form method="post" name="formtest" id="formtest">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
<input type="submit" name="delete_event" value="delete" class="banner-button"/>
</form>
<form method="post" name="formtest" id="formtest">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
<input type="submit" name="select_update_event" value="update" class="banner-button"/>
</form>
</td>
</tr>
<?php
}
}
?>
</table>
</div>
<script>
let jQueryNC = jQuery.noConflict();
jQueryNC( function() {
jQueryNC( "#event_to" ).datepicker({ dateFormat: 'yy-mm-dd' });
jQueryNC( "#event_from" ).datepicker({ dateFormat: 'yy-mm-dd' });
} );
jQueryNC("body").on("change", "#banner_store_id", function() {
changebanner(jQueryNC(this));
});
function changebanner(e){
let jQueryNC = jQuery.noConflict();
jQueryNC( "#poster_div" ).html("Loading...");
let formData = new FormData(); // creates an object, optionally fill from <form>
let value = jQueryNC("#banner_store_id").val();
console.log(e.value);
formData.append('poster_id', value);
formData.append('action', 'get_poster');
let xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/admin-post.php");
xhr.send(formData);
xhr.onload = () => {
let posters = JSON.parse(xhr.response);
let htmldiv = '<table border=0 cellpadding=5>';
for(let i = 0; i < posters.length; i++)
{
htmldiv += '<tr>';
htmldiv += '<td><input type="hidden" name="poster_ids[]" value="'+posters[i].id+'">'+posters[i].name+'</td>';
htmldiv += '<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="'+posters[i].qty+'"></td>';
htmldiv += '</tr>';
}
htmldiv += '</table>';
jQueryNC("#poster_div").html(htmldiv);
}
}
</script>
<?php
} ?>
Clarification: when the select input is not changed, the inputs inside container div are recognized upon submitting without any errors, but when the contents of container div are changed via changebanner; the new inputs and tables are created but if it is submitted, the inputs like poster_ids[] is not recognized by $_POST['poster_ids']
EDIT added the entire code in hopes of clarifying the problem
I tried to explain the issue in my comments but maybe it will be easier to see here.
Your initial form on page load has a bunch of inputs etc in it, including some poster_ids and poster_qty.
If you submit that form, by clicking the submit button, a standard HTML form submission via POST happens. All the inputs that exist in the form on page load will be sent in the request, and your PHP will get all of them.
But if you don't submit the form, and instead change the selected #banner_store_id option, some Javascript takes over. That JS will do a few things:
Create an empty formData object, ignoring everything currently in your form;
Add 2 new key/value pairs to that formData
POST those 2 values to your PHP. Note this is not a standard HTML POST like the one that happens when you click submit, it is an AJAX POST. It is essentially independent of the <form> on the page, and it will only POST the fields from the form if you specifically add them. The code you have does not do that, and so does not include any of your existing form fields.
If you try to use $_POST['poster_ids'] in the PHP which receives this JS POST, it will fail, because those fields were not in the request. The only things there are a poster_id and an action.
If you do want to include all the fields in your form in the data you POST via JS when changing #banner_store_id, you need to create a formData with the form itself, as shown in the docs:
let myForm = document.getElementById('formtest1');
let formData = new FormData(myForm);
If you do this, then all the inputs on your form are bundled up and included in that formData, and just like with the normal POST will all be sent to your PHP.
Here's the relevant part of your code, commented to explain it further:
function changebanner(e) {
// Create a new FormData object - **NOTE** it is empty! You have not passed
// in your existing form, so none of the form inputs already on the page are
// in FormData. If you POSTed it right away $_POST would be completely empty.
let formData = new FormData();
// Now add 2 items to it
formData.append('poster_id', value);
formData.append('action', 'get_poster');
// Now make your POST, and send formData, which has just those 2 items
let xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/admin-post.php");
xhr.send(formData);
// The POST is done, you sent poster_id and action and nothing else to your PHP
}
Try taking out the onchange(this) in the select and instead use the jQuery on.("change").
Without seeing the exact error or what you have tried it is hard to say exactly but trying to access a variable that has not be created yet often gives an undefined because you are trying to access it before it exists. By using the jQuery on function you can find things added after DOM has loaded.
Good luck.
$("body").on("change", "#data_store_id", function() {
changeSELECTED($(this));
});
function changeSELECTED(e) {
let jQueryNC = jQuery.noConflict();
jQueryNC("#container_div").html("Loading...");
let formData = new FormData(); // creates an object, optionally fill from <form>
formData.append('data_id', e.value);
formData.append('action', 'get_data');
let xhr = new XMLHttpRequest();
xhr.open("POST", "/adminfolder/admin-post.php");
xhr.send(formData);
xhr.onload = () => {
let datas = JSON.parse(xhr.response);
let htmldiv = '<table border=0 cellpadding=5>';
for (let i = 0; i < datas.length; i++) {
htmldiv += '<tr>';
htmldiv += '<td><input type="hidden" name="data_ids[]" value="' + datas[i].id + '">' + datas[i].name + '</td>';
htmldiv += '<td><input type="text" name="data_qty[]" placeholder= "Qty Allocation" value="' + datas[i].qty + '"></td>';
htmldiv += '</tr>';
}
htmldiv += '</table>';
jQueryNC("#container_div").html(htmldiv);
}
}
<select id="data_store_id" name="data_store_id">
<?php
foreach($data_stores as $dstore) {
if($result->data_id == $dstore->id) {
?>
<option SELECTED value="<?php echo $dstore->id?>">
<?php echo $dstore->name ?>
</option>
<?php
}else {
?>
<option value="<?php echo $dstore->id?>">
<?php echo $dstore->name ?>
</option>
<?php
}
}
?>
</select>

Submitting multiple form row into table using sql loop

i have collected multiple rows from a student table. and its listing them just fine.
<?php
$sql = "SELECT * FROM `students` WHERE `class`='$class' && `academicyear`='$academicyear'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo #++$n ; ?> </td>
<td><?php echo $row["studentid"]?> <input type="text" name="studentid" value="<?php echo $row["studentid"]?>" style="visibility: hidden; width: 10px;"></td>
<td><?php echo $row["fname"]?> &nbsp <?php echo $row["sname"]?> <input type="text" name="name" value="<?php echo $row["fname"]?> <?php echo $row["sname"]?>" style="visibility: hidden; width: 10px;"></td>
<td style="display: none; width: 10px;"><input type="text" name="class" value=" <?php echo $class; ?>"> </td>
<td style="display: none; width: 10px;"><input type="text" name="academicyear" value=" <?php echo $academicyear; ?>"></td>
<td style="display: none; width: 10px;"><input type="text" name="rowcount" value=" <?php echo $rowcount; ?>"> </td>
</tr>
<?php
}
} else {
echo "";
}
mysqli_close($conn);
?>
my difficulty is how to submit this multiple rows into another table called classlist
<?php
// Receiving variables
#$pfw_ip= $_SERVER['REMOTE_ADDR'];
#$example1_length = addslashes($_POST['example1_length']);
#$studentid = addslashes($_POST['studentid']);
#$name = addslashes($_POST['name']);
#$class = addslashes($_POST['class']);
#$academicyear = addslashes($_POST['academicyear']);
#$rowcount = addslashes($_POST['rowcount']);
// Validation
//saving record to MySQL database
#$pfw_host = "localhost";
#$pfw_user = "root";
#$pfw_pw = "";
#$pfw_db = "myschool";
$pfw_link = mysql_connect($pfw_host, $pfw_user, $pfw_pw);
if (!$pfw_link) {
die('Could not connect: ' . mysql_error());
}
$pfw_db_selected = mysql_select_db($pfw_db, $pfw_link);
if (!$pfw_db_selected) {
die ('Can not use $pfw_db : ' . mysql_error());
}
$i=0;
while ($i<= $rowcount) {
#$pfw_strQuery = "INSERT INTO `classlist`(`studentid`,`name`,`class`,`academicyear`) VALUES (\"$studentid\",\"$name\",\"$class\",\"$academicyear\")" ;
$rowcount = $rowcount - 1;
}
//insert new record
$pfw_result = mysql_query($pfw_strQuery);
if (!$pfw_result) {
die('Invalid query: ' . mysql_error());
}
mysql_close($pfw_link);
header('location:classlist.php');
?>
i only get the last row data submitted into the classlist table then an error appear -- invalid query, duplicate query.
please help.
You must use single quotes to wrap strings in SQL
#$pfw_strQuery = "INSERT INTO `classlist`(`studentid`,`name`,`class`,`academicyear`) VALUES ('$studentid','$name','$class','$academicyear')" ;

Autonaming "Input Type's checkbox's name" in html form

Basically I want to automatically create a new name for the INPUT TYPE=CHECKBOX
maybe like
input type=checkbox name=ORDER1
And
input type=checkbox name=ORDER2
And so on
While reading it from the database. but I don't know how to do that, need some guide here.
<form method=POST action="order.php">
<?php
include 'connection.php';
$query = "SELECT * FROM product";
$exe = mysql_query($query);
echo "<div align=center><b> YOUMIND FASHION STORE </b></div><br><br>";
while($row = mysql_fetch_assoc($exe))
{
$a = $row['name'];
$b = $row['price'];
$c = $row['weight'];
$d = $row['pics'];
$e = $row['id_product'];
echo "<table width='320' border='1' align='center'>
<br>
<img src='$d' width='300' height='300'><br><br>
<tr><td><br>Name : $a <br>
Price : $b <br><br>
<INPUT TYPE='HIDDEN' NAME='WGHITEM' VALUE=$b></INPUT>
<INPUT TYPE='HIDDEN' NAME='WGH' VALUE=$c></INPUT>
Now here is the problem
<INPUT TYPE=CHECKBOX NAME='ORDER' VALUE=$e> Check This item</INPUT><br><br>
</td></tr></table>";
}
<input type="submit" value="ORDER">
</form>
You can declare a variable with starting value = 1, then you can increase it and you can use the number in your ORDER name like this:
<form method=POST action="order.php">
<?php
include 'connection.php';
$query = "SELECT * FROM product";
$exe = mysql_query($query);
echo "<div align=center><b> YOUMIND FASHION STORE </b></div><br><br>";
$i=1;
while($row = mysql_fetch_assoc($exe))
{
$a = $row['name'];
$b = $row['price'];
$c = $row['weight'];
$d = $row['pics'];
$e = $row['id_product'];
echo '<table width="320" border="1" align="center">
<br>
<img src="'.$d.'" width="300" height="300"><br><br>
<tr><td><br>Name : '.$a.' <br>
Price : '.$b.' <br><br>
<input type="hidden" name="WGHITEM" value="'.$b.'"></input>
<input type="hidden" name="WGH" value="'.$c.'"></input>
<input type="checkbox" name="ORDER'.$i.'" value="'.$e.'"> Check This item</input><br><br>
</td></tr></table>';
$i++;
}
?>
<input type="submit" value="ORDER">
</form>
You should use class and css for styling the table, instead of width, border and align attributes!

Search data from the table using javascript

I am currently working on an application based on JavaScript and PHP. In my app, I have a table and a textbox - when I enter data in the textbox, the table should show the particular value that I typed. My current implementation does not work as I am not sure how to complete the search component - can anyone help?
<table name="tablecheck" class="DataTable" id="results" >
<thead>
<tr ><th> </th>
<th> </th>
<th><center><b>COURSE CODE</b></center></th>
<th><center>COURSE NAME</center></th></tr>
</thead>
<?php if(isset($records)) : foreach ($records as $row) : ?>
<tbody>
<tr id="rowUpdate" class="TableHeaderFooter">
<td>
<?php echo anchor('coursemaster_site/delete/'.$row->id, 'Delete',array('onClick'=>"return confirm('ARE YOU WANT TO DELETE..?')")); ?>
</td>
<td>
<input type=checkbox name="editcustomer[] " id="editcustomer[]" value="<?php echo $row->id ?>" >
</td>
<td >
<input class="inputwide span2 " type="text" onblur="upper(this)" name="course_code_<?php echo $row->id ?>" id=" course_code_<?php echo $row->id ?>" value="<?php echo $row->course_code ; ?> " >
</td>
<td>
<input class="inputmedium span2" type="text" name="course_name_<?php echo $row->id ?>" id="course_name_<?php echo $row->id ?>" value="<?php echo $row->course_name ; ?>" >
</td>
</tr>
</tbody>
<?php endforeach ; ?>
<?php endif ; ?>
</table>
<form action="#" method="get" onSubmit="return false;">
<label for="q">Search Here:</label><input type="text" size="30" name="q" id="q" value="" onKeyUp="doSearch();" />
</form>
<script>
function doSearch() {
var rowContainsSearchTerm, fullname;
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var searchTermMoreThanTwoCharsLong = v.length > 2;
for ( var i = 1; i < rows.length; i++ ) {
fullname = concatInputValues(rows[i].getElementsByTagName("input"));
if (fullname) {
rowContainsSearchTerm = fullname.indexOf(v) > -1;
if (searchTermMoreThanTwoCharsLong && rowContainsSearchTerm) {
rows[i].style.backgroundColor = "#00F";
} else {
rows[i].style.backgroundColor = "";
}
}
}
}
function concatInputValues(inputs){
var inputContents = "";
for (var j = 0; j < inputs.length; j++) {
inputContents = inputContents + inputs[j].value;
}
return inputContents;
}
</script>
Have you considered using JQuery DataTables? The plugin has a really nice table view as well as automatically enabled search textbox, and should fit in easily with your JavaScript/PHP solution.
See example table below:

Want to update multiple records using checkboxes and save button

I am searching some records using two text boxes and then updating the selected records in database. i am able to see the value row id of the selected checkbox but when i want to get the value for updation in database it gives 0, i.e showing no record in array
Here is my code
if($_POST["search"])
{
$nitnumber = $_POST["nitnumber"];
$workno = $_POST["workno"];
$query = "select * from print where nit = $nitnumber and work = $work";
$result = mysql_query($query) or die ("<font color =red>NIT Number and/or Work Number is Missing</font>");
$count = mysql_num_rows($result);
if($count == 0)
echo "<font color=red>Record not found</font>";
else
{
while($record = mysql_fetch_assoc($result))
{
?>
<tr class="odd">
<td><div align="center"><?php echo $record['a']; ?></div></td>
<td><div align="center"><?php echo $record['b']; ?></div></td>
<td><div align="left"><?php echo $record['c']; ?></div></td>
<td> <div align="left">
<?php
enter code hereecho $record["d"];
?>
</td>
<td>
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>">
<?php echo $record["id"];?>
</td>
<?php } } }?>
<tr>
<td colspan="5" align="right"> <input type="submit" value="Save" name="save"> </td>
</tr>
<?php
if ($_POST['save'])
{
$num_chkboxes=count($_POST['checkbox']);
for($i=0; $i<$num_chkboxes; $i++){
$complete = intval($checkbox[$i]);
echo $complete;
var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
//$Result1 = mysql_query($updateSQL, $FamilyOrganizer) or die(mysql_error());
}
}
?>
<?php
if ($_POST['save'])
{
$checkbox1 = $_POST['chk1'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
$updateSQL = "" // your update query here
}
?>
<input type="checkbox" name="chk1[]" value=""> // take checkboxes like this
First, the problem started when you fill the values of the checkboxes:
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>" />
you must gave them the value like
value="<?php echo $record['id'] ?>"
Second, you don't get the values of the checkboxes as you should:
for($i = 0; $i < count($_POST['checkbox']); $i++){
$complete = intval($_POST['checkbox'][$i]);
//echo $complete;
//var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
}
Another thing you should take care about is the assigning of the elements ids:
id="checkbox[]"
you must give unique ids for each element:
id="checkbox-1"
id="checkbox-2"

Categories