PHP Mysql Table Pagination - javascript

Ive been try to make a page with Pagination on table. Upon button click, the table in main.php got populated by the first 16 rows retrieved from the query in page.php. For example the retrieved rows were 20. So there would be an excess of 4 for the second page. The thing is when I clicked the "Next" button to show the missing 4 records, the page is then diverted to page.php with the missing records. What I want to happen is for the 20 records in main.php be replaced by the 4 records.
MAIN.PHP
<div id="section">
<head3>Asset Assignment</head3><br><br>
<table>
<td>
<tr>Search Asset:</tr>
<tr><input type="text" id="sidt" name="sid"></tr>
<tr><input type="button" name="searchSub" value="Search" onClick="searchItem()"></tr>
</td>
</table><br>
<table>
<tr>
<td>Employee ID</td>
<td>Asset Serial Number</td>
</tr>
<tr>
<td><input type="text" name="empID"></td>
<td><input type="text" name="srlID"></td>
</tr>
<tr>
<td align="right"><input type="button" name="assign" value="Assign" onClick="assignItem()"></td>
</tr>
</table><br>
</div>
<div id="section2"></div>
JAVASCRIPT
function searchItem()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "asid=" + document.getElementById("sidt").value;
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
document.getElementById("section2").innerHTML = xhr.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
}
function assignItem(){}
PAGE.PHP
<?PHP
session_start();
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "password";
$dbDatabase = "awsims";
$db = new PDO("mysql:dbname=$dbDatabase;host=$dbHost;port=3306", $dbUser, $dbPass);
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int)$_GET['startrow'];
}
$sql = $db->prepare("SELECT * FROM assets LIMIT $startrow, 16");
$sql->execute();
$fetch = $sql->rowCount();
$num=$fetch;
if($num>0)
{
echo "<table style='width: 100%' border='1'>";
echo "<tr><td>ID</td><td>Drug</td><td>quantity</td></tr>";
for($i=0;$i<$num;$i++)
{
$row = $sql->fetch(PDO::FETCH_ASSOC);
$a = $row['SerialNumber'];
$b = $row['AssetType'];
$c = $row['AssetSubType'];
echo "<tr>";
echo "<td>$a</td>";
echo "<td>$b</td>";
echo "<td>$c</td>";
echo "</tr>";
}
echo "</table>";
}
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.($startrow+16).'>Next</a>';
$prev = $startrow - 16;
//if ($prev >= 0)
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.$prev.'>Previous</a>';
?>

Try changing your sql statement to as following query.
$sql = $db->prepare("SELECT * FROM assets LIMIT 16 OFFSET $startrow");
The next and previous link code should be like following.
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.($startrow+1).'>Next</a>';
$prev = $startrow - 1;
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.$prev.'>Previous</a>';

Here is the easiest and smartest PHP MySQL Pagination example I had ever read! Very well explained and a full code is provided which is tested and working 100%.

Related

ajax calling php loop with form not working on first loop only

I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.
Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.
I don't know how to use jquery yet, so please answer with plain javascript.
Here's events.php:
<script>
//show past events
function showPastEvents(str) {
document.getElementById('pastevents').style.display = "block";
document.getElementById('hideoldbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("pastevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pastevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pastevents.php?q="+str, true);
xhttp.send();
}
function hidePastEvents() {
document.getElementById('pastevents').style.display = "none";
document.getElementById('hideoldbutton').style.display = "none";
}
//show upcoming events
function showUpcomingEvents(str) {
document.getElementById('upcomingevents').style.display = "block";
document.getElementById('hidenewbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("upcomingevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("upcomingevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "upcomingevents.php?q="+str, true);
xhttp.send();
}
function hideUpcomingEvents() {
document.getElementById('upcomingevents').style.display = "none";
document.getElementById('hidenewbutton').style.display = "none";
}
</script>
<!-- page content -->
<div class="content">
<h6>Past events</h6>
<form name="postpastevents" action=""/>
<div id="pastevents"></div>
<input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>
<br>
<br>
<!-- ####### -->
<h6>Upcoming events</h6>
<form name="postupcomingevents" action=""/>
<div id="upcomingevents"></div>
<input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>
Here is pastevents.php (it's the same code for upcomingevents.php):
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
$query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
$result = pg_query($query);
while ( $row = pg_fetch_assoc($result) ) {
$i = 0;
echo "<tr>"; //table row
foreach ($row as $key => $value) {
if ($i == 0) {
$eventname = $value;
}
if ($i == 1) {
$eventdate = $value;
}
$eventinfo = $value;
echo "<td>"; //1 column each loop
echo "$eventinfo";
if ($i == 1) {
echo date(" (l, F jS)", strtotime($eventdate));
}
echo "<br><br>";
echo "</td>";
$i++;
}
echo "<td>";//1 column while same event
?>
<div>
<form name="pasteventsurvey" action="pastevent-handle.php" method="post">
What did you think of the event?
<select name="pasteventopinion">
<option value="">(Choose one)</option>
<option value="good">Loved it!</option>
<option value="okay">Liked it</option>
<option value="bad">Needs improvement</option>
<option value="time">Time conflict</option>
<option value="NA">NA</option>
</select>
<input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
<input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
</form>
</div>
<?php
echo "</td>";
echo "</tr>"; //-table row
}
pg_close($conn);
?>
Here's pastevents-handle.php:
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));
echo "email is $idkey, eventname is $name, pastopinion is $opinion";
pg_close($conn);
?>
(I edited a bit for space, ignore anything that isn't vital)
It is illegal to have a form inside another form.
Remove the outer form and everything should work fine, except you have another problem with the code.

Receiving multiple values back from Ajax using JSON, without JQuery, not working

I'm just trying Ajax for the first time, with PHP, and I'd like to avoid using JQuery for now.
I got it to send back 1 list of states wrapped in a drop down element. woo hoo!
Now when I added JSON to return 2 values to be parsed back out (wrapped in an array - one a string, and one am array), it's not working. I suspect that the data is getting passed around property, but a headers-warning-message is being appended at the front of the return req so the entire string can't properly be parsed. Seems to be just a header issue of some sort. I'm not familiar with header stuff so I'm not sure where to go next. I have now pasted that content below.
Main Page:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error)
{
die("Connection failed");
}
$sql = 'SELECT country_name, country_id
FROM countrylist
ORDER BY 1';
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
//Create entry form on page
echo
"<form action = 'searchresults.php' method='post'>
<h1>FIND A PET SITTER</h1>
<br/>
Enter either a ZipCode
<table>
<tr>
<td style='text-align:right'>
Zip Code:
</td>
<td>
<input name='search_zip'></input>
</td>
</tr>
<br/><br/>
Or Country, City, and State
<tr>
<td style='text-align:right'>";
echo "Country: <td>
<select onChange='getState(this.value)' name='search_country' value=''>";
while ($row = $result->fetch_assoc())
{
if ($row[country_name] == 'United States of America')
{
echo "<option value ='".$row['country_id']."' selected>".$row['country_name']." </option>
";
}
else
{
echo "<option value='".$row['country_id']."'> ".$row['country_name']."</option>
";
}
}
echo
"
</select>
</td>
</tr>
<tr>
<td style='text-align:right'>
City:
</td>
<td>
<input name='search_city'>
</input>
</td>
</tr>
<tr>
<td style='text-align:right'>
<div id='statelab'></div>lab
</td><td>
<div id='statediv'></div>div
</td>
</tr>
</table>
<input type='submit'>
</input>
</form>";
?>
<script>
function getState(countryId) {
var strURL="getStates.php?countryIn="+countryId;
var req = new XMLHttpRequest();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) { //if success
alert(req.responseText);
var obj = JSON.parse(req.responseText);
document.getElementById('statediv').innerHTML=obj.stateselectbox;
document.getElementById('statelab').innerHTML=obj.statelabel;
}
else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
getState(230);/*united states*/
</script>
Ajax calls this page:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countryId = intval($_GET["countryIn"]);
if ($countryId < 1 || $countryId > 1000) exit();
$sql = 'SELECT divisions_are_called
FROM countrieslist
WHERE country_id = 0'.$countryId ;
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$divisionsAreCalled = $row[divisions_are_called];
//echo $divisionsAreCalled.': </td><td>';
$sql = 'SELECT state_name
FROM stateslist
WHERE state_name <> ""
AND country_id = 0'.$countryId . '
ORDER BY 1' ;
$result = mysqli_query($con, $sql);
$stateSelectBox = '<select name="statename">';
while ($row = mysqli_fetch_assoc($result))
{
$stateSelectBox=$stateSelectBox. '<option value="'.$row["state_name"].'">'.$row["state_name"].'</option>';
}
$stateSelectBox=$stateSelectBox. '</select>';
$data=array('divisionsarecalled'=>$divisionsAreCalled,
'stateselectbox'=>$stateSelectBox);
//header('Content-Type: application/javascript');
header('Content-Type: application/json');
echo JSON_encode($data);
?>
Here is the response:
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/professional/www/dan/myFiles/getStates.php:2) in <b>/home/professional/www/dan/myFiles/getStates.php</b> on line <b>43</b><br />
{"statelabel":"State","stateselectbox":"<select name=\"devices\"><option value=\"Alabama\">Alabama<\/option><option value=\"Alaska\">Alaska<\/option><option value=\"American Samoa\">American Samoa<\/option><option value=\"Arizona\">Arizona<\/option><option value=\"Arkansas\">Arkansas<\/option><option value=\"Armed Forces Americas\">Armed Forces Americas<\/option><option value=\"Armed Forces Europe\">Armed Forces Europe<\/option><option value=\"Armed Forces Pacific\">Armed Forces Pacific<\/option><option value=\"California\">California<\/option><option value=\"Colorado\">Colorado<\/option><option value=\"Connecticut\">Connecticut<\/option><option value=\"Delaware\">Delaware<\/option><option value=\"Florida\">Florida<\/option><option value=\"Georgia\">Georgia<\/option><option value=\"Guam\">Guam<\/option><option value=\"Hawaii\">Hawaii<\/option><option value=\"Idaho\">Idaho<\/option><option value=\"Illinois\">Illinois<\/option><option value=\"Indiana\">Indiana<\/option><option value=\"Iowa\">Iowa<\/option><option value=\"Kansas\">Kansas<\/option><option value=\"Kentucky\">Kentucky<\/option><option value=\"Louisiana\">Louisiana<\/option><option value=\"Maine\">Maine<\/option><option value=\"Maryland\">Maryland<\/option><option value=\"Massachusetts\">Massachusetts<\/option><option value=\"Michigan\">Michigan<\/option><option value=\"Minnesota\">Minnesota<\/option><option value=\"Mississippi\">Mississippi<\/option><option value=\"Missouri\">Missouri<\/option><option value=\"Montana\">Montana<\/option><option value=\"Nebraska\">Nebraska<\/option><option value=\"Nevada\">Nevada<\/option><option value=\"New Hampshire\">New Hampshire<\/option><option value=\"New Jersey\">New Jersey<\/option><option value=\"New Mexico\">New Mexico<\/option><option value=\"New York\">New York<\/option><option value=\"North Carolina\">North Carolina<\/option><option value=\"North Dakota\">North Dakota<\/option><option value=\"Northern Mariana Islands\">Northern Mariana Islands<\/option><option value=\"Ohio\">Ohio<\/option><option value=\"Oklahoma\">Oklahoma<\/option><option value=\"Oregon\">Oregon<\/option><option value=\"Pennsylvania\">Pennsylvania<\/option><option value=\"Puerto Rico\">Puerto Rico<\/option><option value=\"Rhode Island\">Rhode Island<\/option><option value=\"South Carolina\">South Carolina<\/option><option value=\"South Dakota\">South Dakota<\/option><option value=\"Tennessee\">Tennessee<\/option><option value=\"Texas\">Texas<\/option><option value=\"U.S. Virgin Islands\">U.S. Virgin Islands<\/option><option value=\"Utah\">Utah<\/option><option value=\"Vermont\">Vermont<\/option><option value=\"Virginia\">Virginia<\/option><option value=\"Washington\">Washington<\/option><option value=\"Washington DC\">Washington DC<\/option><option value=\"West Virginia\">West Virginia<\/option><option value=\"Wisconsin\">Wisconsin<\/option><option value=\"Wyoming\">Wyoming<\/option><\/select>"}
EDIT: I added changed these 3 lines in the page ajax calls and it works now:
<?php
ob_start(); //<--ADDED THIS
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xx ...
...$data=array('statelabel'=>$divisionsAreCalled,
'stateselectbox'=>$stateSelectBox);
header('Content-Type: application/javascript');
//echo json_encode($data); //<--CHANGED THIS TO THE 2 LINES BELOW
ob_end_clean(); // this clears any potential unwanted output
exit(json_encode($data));
?>

Javascript error when using AJAX

I am trying to do a connection with the database using AJAX. I am totally new to AJAX...just saw a couple of tutorials and took a code snippet and tried to adapt it to my code.. but when ever I press the button I get the following error Error: Unable to get property 'documentElement' of undefined or null reference
php file
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$title = $_GET['title'];
$conn=("localhost","root","","askthedoctor");
$sql="select patient_text, doctor_text where title='".$title."')";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo $row[0];
echo $row[1];
echo '</response>';
?>
javasscript
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Cant create that object !")
else
return xmlHttp;
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
title= encodeURIComponent(document.getElementById("title").value);
xmlHttp.open("GET", "displaypatientmessage.php?title="+title,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
////////////////////////////////error////////////////////
xmlDocumentElement = xmlResponse.documentElement;
/////////////////////////////error/////////////////////////
message1 = xmlDocumentElement.firstChild.data;
document.getElementById("question").innerHTML = message1;
message2 = xmlDocumentElement.firstChild.data;
document.getElementById("answer").innerHTML = message2;
setTimeout('process()', 1000);
}else{
alert('Someting went wrong !');
}
}
}
the form containing the button which calls the javascript
<table id="table" class="table">
<tr>
<th>Messages</th>
<th>Problem Description</th>
<th>Doctor's Answer</th>
<th></th>
</tr>
<tr>
<th><select id="title">
<?php
$sql="select title from messages where paitient_id=(select id from login where username='".$username."');";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result))
{
?>
<?php echo "<option value=\"mesazhi1\">".$row[0]."</option>";}?>
</select>
</th>
<td><textarea rows="17.95" col="100" id ="question" > </textarea></td>
<td><textarea rows="17.95" col="100" id ="answer" readonly> </textarea></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td><input type="button" name="openmessage" value="Display Selected Message" onClick="process()"></td>
</tr>
</table>
</form>
1] One more thing, see the
<?php echo "<option value=\"mesazhi1\">".$row[0]."</option>";}?>
as value of each <option> is same. You will get same value of title at
title= encodeURIComponent(document.getElementById("title").value);
so no matter what option you select, you will always get same value i.e. \mesazhi\.
2] Also, take a look,
$sql="select patient_text, doctor_text where title='".$title."')";
you have not mention the table name.
3] Also why is ) at the end of query?
4] And finally
$conn=("localhost","root","","askthedoctor");
should be
$conn=mysqli_connect("localhost","root","","askthedoctor");

Store different value in the database from the forms created dynamically using PHP?

Have a look at the screenshot below.
As per the screenshot, I have the data fetched into the different blocks based on the database. For example, based on the username and password, these values are fetched from the database and displayed in different blocks. I have the PHP to store the value into the database, but the problem that I am facing is that when i try to upload it from other block, it still saves the value from the first block.
Codes as as below:
<?php
include('includes/config.php');
$upload = 'uploads/';
session_start();
$_SESSION['$userid'];
$sql = "SELECT * FROM tbl_store INNER JOIN tbl_job ON tbl_store.store_code = tbl_job.store_code WHERE username = '$userid'";
$result = mysqli_query($conn,$sql);
$rowcount=mysqli_num_rows($result);
// echo "$rowcount";
$stores = array();
$stores_add = array();
$stores_chain = array();
$job = array();
$client = array();
$brand = array();
$week= array();
$x = 1;
$imgCnt =1;
while($row = mysqli_fetch_array($result)){
echo "工作".'<br/>';
echo $row['jobs'].'<br/>'.'<br/>';
$job[] = $row['jobs'];
echo "客戶".'<br/>';
echo $row['Client'].'<br/>'.'<br/>';
$client[] = $row['Client'];
echo "牌子".'<br/>';
echo $row['Brand'].'<br/>'.'<br/>';
$brand[] = $row['jobs'];
echo "週數".'<br/>';
echo $row['week'].'<br/>'.'<br/>';
$week[] = $row['week'];
$target = $upload.'/'.$row['Client'].'/'.$row['Brand'].'/'.$row['jobs'].'/'.$row['store_code'].'/';
$testpath = $row['Client'].'/'.$row['Brand'].'/'.$row['jobs'].'/'.$row['store_code'].'/';
$_SESSION['target1'.$x] = $target;
if(!file_exists($target))
{
mkdir($target,0777,true);
}
?>
<form id='uploadForm-<?php echo $imgCnt; ?>' action = '' enctype='multipart/form-data' method = 'POST' class="form<?php echo $imgCnt; ?>">
<input type="file" class="image<?php echo $imgCnt; ?>" name="img" onChange="readURL(this);" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type='button' id = '<?php echo $imgCnt; ?>' class='uploadPicture<?php echo $imgCnt; ?> btn btn-primary' value = '上載'>
<!-- <input type="button" value="上載" class="uploadPicture" id="upload_btn<?php echo $imgCnt; ?>"/> -->
</form>
<form enctype="application/x-www-form-urlencoded">
<table width="200" border="1">
<tr>
<td>Product</td>
<td>Promotional Price</td>
<td>Regular Price</td>
<td>Stacking</td>
</tr>
<tr>
<td><input type="text" id="product"></td>
<td><input type="text" id="pp1"></td>
<td><input type="text" id="rp1"></td>
<td><input type="text" id="stacking"></td>
</tr>
</table>
<div id ="div1">
<input type="button" value="Submit" onClick="PostData();"/><br/>
</div>
</form>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function PostData() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var product = document.getElementById("product").value;
var pp1 = document.getElementById("pp1").value;
var rp1 = document.getElementById("rp1").value;
var stacking = document.getElementById("stacking").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'report.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("product=" + product + "&pp1=" + pp1 + "&rp1=" + rp1 + "&stacking=" + stacking);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
</script>
<?php
echo "-------------------------------------------------------".'<br/>';
$x = $x+1;
$imgCnt++;
}
?>
I have removed the code for image upload from it as it works completely fine. The problem is the data from the other block is not stored to the database. only the value for the first block is stored second time even. How to solve this problem.
PHP to store data:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testing";
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tbl_report (product,pp1, rp1,stacking)
VALUES ('$product', '$pp1', '$rp1','$stacking')";
if ($conn->query($sql) === TRUE) {
echo "Successful";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
To expand on what #Logan Wayne pointed out...
An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code.
So, in your JavaScript, when you grab references to your table data elements, you'll always get the FIRST instance of a Document object with whatever id you provide.
// 2. Define what to do when XHR feed you the response from the server - Start
var product = document.getElementById("product").value; <-- will always return the same element
var pp1 = document.getElementById("pp1").value; <-- will always return the same element
var rp1 = document.getElementById("rp1").value; <-- will always return the same element
var stacking = document.getElementById("stacking").value; <-- will always return the same element
You'll either have to assign unique ids to your td objects, or, again as #Logan Wayne mentioned, utilize the class property of HTML DOM objects.
Classes can be used to group like elements. After assigning class names to the different columns in your table (Product, Promotional Price, Regular Price, Stacking) you can use getElementsByClassName() to get an array of the td elements.
...
var products = document.getElementsByClassName("product"); <-- array of product td elements
...

How to get database other fields on change even of dropdown

Below are my code parts javascript, main.php and getparty.php
1) getparty.php code is as follow called from javascript to take details
from party table on change of dropdown value of party from main.php
<?php
$q = intval($_GET['q']);
include "dbc.php";
$sql= mysql_query("Select a.pcode,a.pname,a.discperc,a.delvterm from PARTY a where a.pcode='$q'") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
$pcode=$row['pcode'];
$ppname=$row['pname'];
$pdiscperc=$row['discperc'];
?>
main.php ... it is my main form to display main form for user to enter
<tr>
<td><font face="verdana" size="2" color="#000000">Party</font></td>
<td>
<?php
<td align="left" >
<?php
$sql="UPDATE PARTY set repo_flag=0 ";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
if ($ppname!="")
{
$sql="UPDATE PARTY set repo_flag=1 where pname='$ppname' ";
}
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
$dropdown = "<select id='pname' name='pname' style='width:275px' onchange='showparty(this.value)' value='<?php echo $ppname; ?>' >";
$query1 = "select pcode,pname from PARTY order by repo_flag DESC ";
$get=mysql_query($query1);
while($row = mysql_fetch_array($get))
{
$dropdown .= "\r\n<option value='{$row['pcode']}'>{$row['pname']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
?>
</td>
</tr>
<tr>
<td><input type="text" maxlength="3" size="3" name="txtdiscperc" value="<?php echo $pdiscperc; ?>"/></td>
</tr>
Javascript .. This is called to take value of party when dropdown
combo changes
<script>
function showparty(str) {
if (str == "") {
document.getElementById("txtpartyname").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtpartyname").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getparty.php?q="+str,true);
xmlhttp.send();
}
}
</script>
I am not getting value of Discount % in main.php, and some other fields also I want to get from party table which I can write code when above discount % gets properly. How can I

Categories

Resources