How to get unique button id from a while loop? (PHP) - javascript

First of all here's my code:
session_start();
require_once "config.php";
$email = $_SESSION["email"];
$result = mysqli_query($link,"SELECT * FROM cuponai WHERE gmail='$email' AND panaudoti=0");
echo "<table border='1'>
<tr>
<th>Cupono kodas</th>
<th>Apply code</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr> ";
echo "<td>" . $row['cuponas'] . "</td>";
echo "<td> <form method='post'><input type='submit' name='". $row['cuponas'] ."' value='submit'></from></td>";
echo "</tr>";
}
echo "</table>";
if(isset($_POST['???????'])) {
$sql = "UPDATE cuponai SET panaudoti=1 WHERE cuponas='????????????' ";
if ($link->query($sql) === TRUE) {
echo "YOU DID IT WOO";
} else {
echo "Error updating record: " . $link->error;
}
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
</body>
</html>
The parts in question marks is where I'm strugling...
Basically I'm making this site where you can see your purchased coupons and each of the coupons have an apply button near them so you basically have a list and need to apply them after you apply them I want it too refresh the page and applied coupons dissapear and are marked as used in the database. But I've been scratching my head this whole time and trying to make the buttons unique with javascirpt and all that but to no avail hopefully some of you could figure out a solution here?
-sorry for the spaggeti code

In the case of the code you provided, you could add hidden input elements in your forms.
Use the same name and set the value to the unique id you want. This input's value and name will be sent to the PHP portion of your file where you can access it inside the $_POST array like so; $_POST['name_of_input']
In short, you would have to make the following adjustments to your code to make it work as you expect;
Change this
echo "<td> <form method='post'><input type='submit' name='". $row['cuponas'] ."' value='submit'></from></td>";
To this
echo "<td> <form method='post'><input type='hidden' name='couponid' value='". $row['cuponas'] ."'><input type='submit' name='". $row['cuponas'] ."' value='submit'></from></td>";
And then change this
if(isset($_POST['???????'])) {
$sql = "UPDATE cuponai SET panaudoti=1 WHERE cuponas='????????????' ";
To this
if(isset($_POST['couponid'])) {
$sql = "UPDATE cuponai SET panaudoti=1 WHERE cuponas='".$_POST['couponid']."' ";
Your $_POST['couponid'] will hold the data of $row['cuponas'] and your code should work as you expect.
A couple of extra notes beyond the scope of the question;
1. You are currently echoing the HTML you create in PHP before the <!DOCTYPE html> tag.
Although a browser will correct for this, this isn't proper HTML form.
Rather than echoing everything at the top of the document, you might want to store it in a variable and echo that inside the <body> tag instead.
Instead of this;
echo "<table border='1'>
<tr>
<th>Cupono kodas</th>
<th>Apply code</th>
</tr>";
You could use;
$html_to_echo = "<table border='1'>
<tr>
<th>Cupono kodas</th>
<th>Apply code</th>
</tr>";
To add to this variable you can use something like this;
$html_to_echo .= "<tr> ";
And then in the HTML portion of your page;
<body>
<?php echo $html_to_echo; ?>
</body>
It is possible to interweave PHP and HTML like this in a PHP document.
2. Although already mentioned in the comments of your question, here's an extra SQL Injection warning for people passing through in the future.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough

Related

Populate text input field automatically based on dropdown selection mysqli

I've created a dropdown list that is populated by data from my mysql db and programmed using php. What I need to do is populate a text field based on the selection made in the dropdown. Unfortunately, my question differs from the others asked on this forum because most are simply typing all of their options into a html form. Mine are contained within a table and I do not want to save the content in the text field to my database...it will be used for user reference only.
I've read a plethora of forum posts on this site and numerous others and have tried using jquery, javascript, and ajax scripts, but for some reason the only thing I've been successful in getting to appear in the text field is the id of the corresponding item selected from the dropdown list. I think it is important to know that both fields come from the same table in the db, so I can't figure out why it is so difficult to automatically populate the field. I would like to use javascript because I want everything in this one file.
This is the code in the php form:
<?php
'<div id="trxdetailstable">';
echo '<table align="center" width="750px" cellspacing="0" border=".5px" ! important><tr>
<th>Movie Title</th><th>Category</th><th>Price</th></tr>';
echo '<td align="left" width="8%" height="25px">';
$ddlquery4 = "SELECT id, title, categoryname FROM dvd ORDER BY title ASC";
$ddlresult4 = mysqli_query($dbc, $ddlquery4) or die("Bad SQL: $ddlquery4");
echo '<select class="dropdown" name="dvdid" id="dvdid" size="1" onchange="updatecat()">';
while($ddlrow4=mysqli_fetch_array($ddlresult4, MYSQLI_ASSOC)){
$categoryname = $ddlrow4['categoryname'];
echo "<option data-categoryname='' value='".$ddlrow4['id']."'>" . $ddlrow4['title'] . "</option>";
} //End while statement
echo "</select>";
echo '</a></td>';
echo '<td align="left" width="10%">';
echo '<input required id="categoryname" name="categoryname" type="text" readonly="readonly">';
echo '</a></td>';
This is the code I currently have in the html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is the code that is currently generating no results (text field is left blank after a dropdown item is selected):
$('#dvdid').change(function(e){
var optionChange = $('#dvdid option:selected').text();
$('#categoryname').val(optionChange);
});
</script>
And this is the code that actually gave me the primary key (id) for the item selected in the dropdown list (I want it to be the categoryname):
<script>
function updatecat(id){
if (id === "") {
$("input[name=categoryname]").val("");
} else {
$("input[name=categoryname]").val(id);
}
}
</script>
I have about 3 other scripts I've tried, but they all left the text (category) field blank.
Any advice would be appreciated. Please keep in mind all of my data is generated from a database not manually entered. Thanks.
You have repeated rows and do not use ID atrribute with them , you can use class like this :
$('select.dropdown').change(function(e){
var optionChange = $(this).find('option:selected').text();
$(this).closest("tr").find(".categoryname").val(optionChange);
});
and your php code should be something like this :
<?php
'<div id="trxdetailstable">';
echo '<table align="center" width="750px" cellspacing="0" border=".5px" ! important>
<tr>
<th>Movie Title</th>
<th>Category</th>
<th>Price</th>
</tr>';
echo '<tr>
<td align="left" width="8%" height="25px">';
$ddlquery4 = "SELECT id, title, categoryname FROM dvd ORDER BY title ASC";
$ddlresult4 = mysqli_query($dbc, $ddlquery4) or die("Bad SQL: $ddlquery4");
echo '<select class="dropdown" name="dvdid" id="dvdid" size="1" onchange="updatecat()">';
while($ddlrow4=mysqli_fetch_array($ddlresult4, MYSQLI_ASSOC)){
$categoryname = $ddlrow4['categoryname'];
echo "<option data-categoryname='' value='".$ddlrow4['id']."'>" . $ddlrow4['title'] . "</option>";
} //End while statement
echo "</select>";
echo '</a></td>';
echo '<td align="left" width="10%">';
echo '<input required class="categoryname" id="categoryname" name="categoryname" type="text" readonly="readonly">';
echo '</a></td></tr>';
For others using html/php and searching for a way to auto populate a text field based on the selection made in a dropdown fed from data held in their mysql db (and only use one file) here is what FINALLY worked for me:
In html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In html/php portion:
echo '<td align="left" width="8%" height="25px">';
$ddlquery4 = "SELECT id, title, categoryname FROM dvd ORDER BY title ASC";
$ddlresult4 = mysqli_query($dbc, $ddlquery4) or die("Bad SQL: $ddlquery4");
echo '<select type="text" class="dropdown" name="dvdid" id="dvdid" size="1" onchange="updatecat()">';
while($ddlrow4=mysqli_fetch_array($ddlresult4, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow4['id']."' data-categoryname='".$ddlrow4['categoryname']."'>" . $ddlrow4['title'] . "</option>";
} //End while statement
echo "</select>";
echo '</a></td>';
echo '<td align="left" width="10%">';
echo '<input type="text" id="categoryname" name="categoryname" readonly="readonly" value="">';
echo '</a></td>';
In HTML area at end of file:
<script>
$('#dvdid').change(function() {
selectedOption = $('option:selected', this);
$('input[name=categoryname]').val( selectedOption.data('categoryname') );
});
</script>
I sincerely hope this prevents someone else from having to go the days of trial and error and endless searching and reading that I went through.

How to edit and delete records of MySQL database without refreshing?

I am new to ajax, I am trying to view, add, edit and delete data of mysql database without refreshing the tab or in other words using ajax on this table:
I have done the view part, *edited but I can not figure out how to edit or delete *. I know it is a very long task, but I have found no solution on the internet.. Thanks in advance
HTML Code:
<html>
<head>
<title>View Data Without refresh</title>
<script language="javascript" type="text/javascript" src="script/jquery-git.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
(function() {
$.ajax({
type: "POST",
url: "display.php",
dataType: "html",
success: function(response){
$("#responsecontainer").html(response);
}
});
});
});
</script>
</head>
<body>
<fieldset><br>
<legend>Manage Student Details</legend>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Class</th>
<th>Section</th>
<th>Status</th>
</tr>
</table>
<div id="responsecontainer" align="center"></div>
</fieldset>
<input type="button" id="display" value="Add New"/>
</body>
</html>
PHP Display Code:
<?php
include("connection.php");
$sql = "select * from tbl_demo";
$result=mysqli_query($db,$sql);
echo "<table class='myTable'>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td width='13.5%'>$data[0]</td>";
echo "<td width='21%'>$data[1]</td>";
echo "<td width='19.5%'>$data[2]</td>";
echo "<td width='24%'>$data[3]</td>";
echo "<td><span class='edit'>Edit</span> | <span
class='delete'>Delete</span></td>";
echo "</tr>";
}
echo "</table>";
?>
If your connection, sql query and php response is ok and
I want it to be automatically done
means you want run ajax on page loading. Then, Output of php should be at last instead in each iteration.
<?php
include("connection.php");
$sql = "select * from tbl_demo";
$result=mysqli_query($db,$sql);
$output = "<table class='myTable'>";
while($data = mysqli_fetch_row($result))
{
$output .="<tr>";
$output .="<td width='13.5%'>$data[0]</td>";
$output .="<td width='21%'>$data[1]</td>";
$output .="<td width='19.5%'>$data[2]</td>";
$output .="<td width='24%'>$data[3]</td>";
$output .="<td><span class='edit'>Edit</span> | <span
class='delete'>Delete</span></td>";
$output .="</tr>";
}
$output .="</table>";
echo $output;
?>
To make edit/delete you need to pass or redirect page with action to other page named controller. After making changes again you need to redirect index/view data page or use ajax if you don't want to refresh/redirect page.

Html Dropdown Menu Displays nothing

I'm trying to diplay my table when I click a value in Dropdown list. When I view page code source, the table values are there but it's not showing. I would like to query from mysql using the value from dropdown and populate the table with datas from mysql query.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
function jsFunction(value){
<?php
$con=mysqli_connect("localhost","root","","dengue");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mapping_details where case_type='value'";
echo '<div class="table-responsive ">
<table class="table table-condensed table-hover table-bordered">
<thead>
<tr>
<th>Barangay</th>
<th>Case Type</th>
<th>Total Dengue Cases</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['brgy'] . "</td>";
echo "<td>" . $row['case_type'] . "</td>";
echo "<td>" . $row['total_case_brgy'] . "</td>";
echo "</tr>";
}
echo '</tbody></table></div>';
mysqli_close($con);
?>
}
</script>
</head>
<body>
<select id ="ddl" name="ddl" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</body>
</html>
Originally, in my other webpages, the php code is inside the body. But this time, I can't make it work if I use dropdown menu so that's why I put it inside the function for me to be able to use onchange function. I've read some answers using AJAX or JSON but I'm not familiar with those so if possible I only want to use javascript as maybe it is the simplest way.
What you are trying to do here is run PHP code in the browser, which you cannot do. All the HTML, CSS, and JavaScript is sent down to the client ( your browser ) and then is rendered and initialized by the browser. When you are calling your onchange event to call the jsFunction() you are trying to execute PHP within that function but- you are on the client-side running in chrome or firefox or some browser and you cannot execute PHP there. PHP has to run on page load and then can change the html, css, or JavaScript before it is sent down to the client.
There are two ways of doing what you want to do. You can send an Ajax request ( call your server using javascript ) to get new data or you can submit a form that reloads the page and you can run PHP like you are comfortable with- modifying the html, css, and/or javascript before it is returned to the client (browser).
Here is the non-ajax way which just keeps reloading the page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<?php
$value = isset( $_POST['ddl'] ) ? $_POST['dll'] : 1; // we are setting 1 as the default
$con=mysqli_connect("localhost","root","","dengue");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mapping_details where case_type='{$value}'";
$html= '<div class="table-responsive ">
<table class="table table-condensed table-hover table-bordered">
<thead>
<tr>
<th>Barangay</th>
<th>Case Type</th>
<th>Total Dengue Cases</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result))
{
$html.= "<tr>";
$html.= "<td>" . $row['brgy'] . "</td>";
$html.= "<td>" . $row['case_type'] . "</td>";
$html.= "<td>" . $row['total_case_brgy'] . "</td>";
$html.= "</tr>";
}
$html.= '</tbody></table></div>';
mysqli_close($con);
?>
}
</script>
</head>
<body>
<form method="POST" action="">
<select id="ddl" name="ddl">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</form>
<script>
$("select#ddl").on("change",function(){
$('form').submit();
});
</script>
<?php echo $html; ?>
</body>
</html>

Updating SQL data without refreshing page

I'm trying to update the two locked textboxes with information that I get from my database. I enter a phone number in the "Telefon" checkbox, and I want it to get the firstname and lasttname for that phone number. Which works by the way, but it's not the way I want it. I want the information to be automatically put into the textboxes without refreshing the page. and for some odd reason my code got split in two here. I've tried to look for a solution for hours. I'm very new to coding, and I would love some help!
<?php
SESSION_START();
$output = NULL;
if(isset($_POST['btn_checkTelefon'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$fornavnoutput_Database = $rows['Fornavn'];
$etternavnoutput_Database = $rows['Etternavn'];
}
echo '<script type = "text/javascript">';
echo 'function sayHi() {';
echo 'val1 = document.getElementById("telefon_Input").value;';
echo 'if(val1 == "") {';
echo ' alert("Vennligst skriv inn ditt telefon nummer!");';
echo '}';
echo 'if(val1 !== "") { ';
echo ' document.getElementById("check_Fornavn").value = "<?php echo $fornavnoutput_Database?>";';
echo ' document.getElementById("check_Etternavn").value = "<?php echo $etternavnoutput_Database?>";';
echo '}';
echo '}';
echo '</script>';
} else {
$output = "No results";
}
}
$fornavnoutput_Database2 = "Fornavn";
$etternavnoutput_Database2 = "Etternavn";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
</script>
<script type = "text/javascript"></script>
<title></title>
</head>
<body>
<?php
include 'connectdb.php';
?>
<form name="form1" action="">
<table id="valgt_skap_tabell" class="bokssvartabell">
<tr>
<td>Valgt skap</td>
</tr>
<tr>
<td>
<input class="bokssvarskjema" type="text" name="Valgt skap" disabled value= <?php
if(isset($_POST["radios"])){
echo $_POST["radios"];
} else {
//header('location: index.php');
} ?>>
</td>
</tr>
</table>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button type="button" name ="btn_checkTelefon" id="sjekkTelefon" onclick = "sayHi()">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
</form>
<?php echo $output; ?>
</body>
You need to use AJAX for this. Example $.ajax() -> shortcuts $.post(), $("id").load("url"), ... Look it up a lot in depth explanation about these on stackoverflow.
Please never mix JavaScript with php.
Use it in separate file.
Edit: So have you fixed it yet?
The easier way to load paged dynamicaly is with load method + actions. $.post is used if you need to do something with returned data from php. I will give you example of load.
I will give a proper example how to code.
Universal function for a link that look at href value and load HTML parts (form in this case) from PHP dynamicaly to your page, you do need to implement actions or just call your ordinary page if you have only one default action there. I use jQuery library here. This script must be in separate file else it will work but you will get a sync warning in your console.
$(function() {
$('a').on("click", function(e) {
e.preventDefault();
e.stopPropagation();
var URL = $(this).attr('href');
$('body').load(URL, 'form');
})
})
php example
prefered showsomethingfunction in separate file like showfunctions.php
function myLinks() {
echo "<a href='index.php?action=showsomething'>showsomething</a>"
}
index.php + included showfunctions.php
<?php
myLinks();
if(isset($_GET["action"]){
// do your ordinary thing like open connection with database.
switch($_GET["action"]))
{
case "showsomething":
//show showsomething() function with html
break;
//further you can add more action instead of showsomething if you have several links
}
//close database.
}
?>
You need to separate your code else it will be a mess if it gets even more complicated. HTML code must be ONLY in showfunctions.php for example in function to call for actions.
Code is not tested but I think it will work. This code will also work without javascript but then it will just reload pages.
You have to use jQuery $.post() for that.
first You have to create php file which will process Your data.
For example lets create file query.php with the following content:
<?php
if(isset($_POST['telefon_Search'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
$row = $resultSet->fetch_assoc();
echo json_encode($row);
}
}
next on Your page You have to create function which will send phone number to our query.php file and which will return Name and Surname if they exist.
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
var user = $.parseJSON(data);
$('#check_Fornavn').val(user.Fornavn);
$('#check_Etternavn').val(user.Etternavn);
});
});
and complete html will looks like:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
<title></title>
</head>
<body>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button name ="btn_checkTelefon" id="sjekkTelefon">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
$('#check_Fornavn').val(data.Fornavn);
$('#check_Etternavn').val(data.Etternavn);
});
});
</script>
</body>
</html>

Display data fetched from remote PHP (mysql) in html table [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have a PHP page displaying data from a mysql database, based on a dropdown list selection, also from a mysql database. This obviously makes use of a JavaScript.
The PHP and mysql integration is working perfectly however I need to change the way the data is displayed.
Currently the returned mysql data is displaying in one table cell, I want each returned mysql field to be displayed in its own table cell.
I have added a photo of the output, I want it to display in each table cell, not in one.
I have attached the code from both my PHP file and the PHP file querying the database.
Any assistance would be greatly appreciated!
index.php
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$con = mysql_connect('localhost', 'unilever_root', 'Unilever2011');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("unilever_unilever", $con);
$skusql="SELECT packcode from skudata";
$resultsku=mysql_query($skusql);
$optionssku="";
while ($row=mysql_fetch_array($resultsku))
{
$sku=$row["packcode"];
$optionssku.="<OPTION VALUE=\"$sku\">".$sku;
}
?>
<table border=1>
<tr>
<td>SKU</td>
<td>Description</td>
<td>SU</td>
<td>Points</td>
<td>Category</td>
<td>Grouping</td>
</tr>
<tr>
<td>
<select name="users" onchange="showUser(this.value)">
<OPTION VALUE=0>
<?=$optionssku?>
</SELECT>
</td>
<td>
<div id="txtHint"><b>SKU Details will be seen here</b></div>
</td>
</tr>
</table>
</body>
</html>
getdata page
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'dbuser', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("unilever_unilever", $con);
$sql="SELECT * FROM skudata WHERE packcode = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<td>" . $row['Description'] . "</td>";
echo "<td>" . $row['SellingUnits'] . "</td>";
echo "<td>" . $row['EOTTPoints'] . "</td>";
echo "<td>" . $row['Category'] . "</td>";
echo "<td>" . $row['Grouping'] . "</td>";
}
mysql_close($con);
?>
The problem here is that you've used two ideas that don't quite work together. This line: document.getElementById("txtHint").innerHTML=xmlhttp.responseText; is setting the content of the tag with id "txtHint" to what your php script returns. This means that when your php returns, for example:
<td>blah</td><td>blah</td><td>blah</td>
then your page ends up with:
<div id="txtHint">
<td>blah</td>
<td>blah</td>
<td>blah</td>
</div>
Do you see what's happening here? You aren't adding more cells to the existing row, you're creating another table within the cell you already have (and a bad one at that, with no <table> or <tr> tags...).
To get around this, change the element with id "txtHint" to the <tr> tag for the row you are editing, and update the php to return the first cell of that row as well, eg:
HTML:
<table border=1>
<tr>
<td>SKU</td>
<td>Description</td>
<td>SU</td>
<td>Points</td>
<td>Category</td>
<td>Grouping</td>
</tr>
<tr id="txtHint">
<td>
<select name="users" onchange="showUser(this.value)">
<OPTION VALUE=0>
<?=$optionssku?>
</SELECT>
</td>
<td colspan="5">SKU Details will be seen here</td>
</tr>
PHP:
while($row = mysql_fetch_array($result))
{
echo "<td><select name='users' onchange='showUser(this.value)'><OPTION VALUE=0>";
echo $optionssku; //Not sure where this variable comes from, so I'll leave getting it from wherever necessary to you
echo "</SELECT></td>";
echo "<td>" . $row['Description'] . "</td>";
echo "<td>" . $row['SellingUnits'] . "</td>";
echo "<td>" . $row['EOTTPoints'] . "</td>";
echo "<td>" . $row['Category'] . "</td>";
echo "<td>" . $row['Grouping'] . "</td>";
}
(code not tested, but it'll be something like this).
There are certainly other methods to get around this problem, almost certainly better ones, but this is the first idea that came to me.

Categories