i have a table that displays data searched.
what i want to happen is when after i click the row, that data from that row clicked will be displayed in a form.
displaying the table:
search.php
echo '<table id="patientTable" class="w3-table-all w3-hoverable">'
echo '<tr class="w3-yellow"><th>Admission No</th><th>Hospital No</th><th>Patient Name</th></tr>';
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) ) {
echo '<tr onclick=patientClick(this)>';
foreach($row as $key=>$value) {
echo '<td>',$value,'</td>';
//echo $i;
}
echo '</tr>';
}
echo '</table><br />';
the script to attempt to connect to form
function patientClick(x){
var rowInd = x.rowIndex;
var adNo = document.getElementById("patientTable").rows[rowInd].cells[0].innerHTML
var hosNo = document.getElementById("patientTable").rows[rowInd].cells[1].innerHTML;
var patname = document.getElementById("patientTable").rows[rowInd].cells[2].innerHTML;
alert(adNo +"-"+ hosNo +"-"+ patname);//check to display row content
var jsObj = {patname:patname, adNo:adNo, hosNo:hosNo}
$.post('addPN.php', {data:jsObj}, function(data){
$('#displayPatient').html(data);
});
}
the form to display so to save more data
addPN.php
<?php
$arr = json_decode(json_encode($_POST["data"]),true);
$adNo = $arr[0]['adNo'];
$hosNo = $arr[1]['hosNo'];
$patname = $arr[2]['patname'];
echo $adNo;//check to display
echo $hosNo;//check to display
echo $patname;//check to display
?>
<html>
<body>
<form action = "savePN.php" id = "savePNotes" method = "POST">
<input type = "submit" id = "updateButton" value = "Save">
<input type = "text" readonly = "true" id = "adNo" name = "adNo" value = "<?php echo $adNo;?>">
<input type = "text" readonly = "true" id = "hosNo" name = "hosNo" value = "<?php echo $hosNo;?>">
<input type = "text" readonly = "true" id = "patname" name = "patname" value = "<?php echo $patname;?>">
<input type = "text" id = "cn" name = "cn" placeholder = "Contact Number">
<input type = "text" id = "cadd" name = "cadd" placeholder = "Address">
<input type = "text" id = "ctype" name = "ctype" placeholder = "Type">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_select.asp
this is a bad practice using php as a client, but ajax is one way communication that you cant redirect instantly in serverside
function patientClick(x){
var rowInd = x.rowIndex;
var adNo = document.getElementById("patientTable").rows[rowInd].cells[0].innerHTML
var hosNo = document.getElementById("patientTable").rows[rowInd].cells[1].innerHTML;
var patname = document.getElementById("patientTable").rows[rowInd].cells[2].innerHTML;
alert(adNo +"-"+ hosNo +"-"+ patname);//check to display row content
//here you must construct some JSON object for your data
var jsObj = { pathname: pathname,
adNo: adNo,
hosNo: hosNo }
$.post('searchPatient.php', JSON.stringify({ data : jsObj}) , function(data){
$("#displayPatient").html(data);
});
}
in your server side you should decode your json
use this
$data = json_decode($_POST["data"])
echo $data["adNo"];
and i think you structure is no good and i think its not possible to do what you wanted to do because the form are from php and different file maybe its possible if you use just normal html form so can easily manipulate the form using DOM
Related
I am trying to select multiple columns with concat an put the returned data into one textbox.
I think there is something wrong with my definition for the variables. But I could not figured out what is wrong. Here are the variables:
$id = isset($_POST['id'])?$_POST['id']:'';
$name = isset($_POST['firstname'])?$_POST['firstname']:'';
$name .= isset($_POST['insertion'])?$_POST['insertion']:'';
$name .= isset($_POST['lastname'])?$_POST['lastname']:'';
When I define just one variable for $name the script works. But that is not what I want.
Does someone know what is wrong?
Here is the other part of my script.
First I have a textbox. The data needs to be send to this textbox:
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
The button calls sends '5' as the ID and runs the script getName():
<button type="button" rel="5" onclick="getName();"
<script type="text/javascript">
$('body').on('click', '.selectClass', function () {
var id = $(this).attr('rel');
$("#id").val(id);
modal.style.display = "none";
});
</script>
After clicking on the button the id is deployed here:
<input type="text" class="form-control" id="id" name="id">
The onClick event runs the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getName(value) { // Do an Ajax request to retrieve the product price
console.log("getName before ajax", jQuery('#id').val());
jQuery.ajax({
url: './get/getname5.php',
method: 'POST',
data: {'id' : jQuery('#id').val()},
success: function(response){
console.log("getName after ajax", jQuery('#id').val());
jQuery('#name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The jquery script calls the PHP, which is not working with the multiple variables for $name
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
$conn = new mysqli($servername, $username, $password, $dbname) ;
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$id = isset($_POST['id'])?$_POST['id']:'';
$name = isset($_POST['firstname'])?$_POST['firstname']:'';
$name .= isset($_POST['insertion'])?$_POST['insertion']:'';
$name .= isset($_POST['lastname'])?$_POST['lastname']:'';
$query = 'SELECT concat(firstname, ' ', insertion, ' ', lastname) as name FROM users WHERE id="' . mysqli_real_escape_string($conn, $id) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}
}
?>
I am trying to show data from the database in my textbox. But when I start the script I am getting no results. I tested the script in different ways and i figured out that the variable: $product1 is empty. Does anybody know how I can fix this?
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
}
?>
Change
var selectedItem = jQuery('.product1 option:selected').val();
To
var selectedItem = jQuery('#product1 option:selected').val();
You are selecting a class with name product1, but you set only an ID with this name. Id's are specified with # and classes with .
Update on your script, because you used getPrice(this.value);
<script>
function getPrice(selectedItem) {
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
TIP:
Did you know that you can use jQuery.ajax and jQuery('selector') also like this: $.ajax and $('selector') :-)
You have not a form tag in your HTML. The default form Method is GET.
In Your get.php you try to get a POST Variable with filter_input
The function filter_input returns null if the Variable is not set.
Two possible solutions:
1. Add a form to your html with method="post"
2. Change your php code to search for a GET variable
Im trying to do this: When someone selects any option from the drop down called subject, the sections drop down should show all sections of that subject. The subject drop down works well, fetches all names of subjects but the sections one won't work. Im unable to find the issue. It should fetch the sections from the database WHERE/WHEN name(database column) is equal to the subject chosen. Thanks in advance. My code is below:
my js code
<script type="text/javascript">
function getSection(strURL)
{
alert(strURL);
var req = getXMLHTTP(); // fuction to get xmlhttp object
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) { //data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('sectiondiv').innerHTML=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n");
}
}
}
req.open("GET", strURL, true); //open url using get method
req.send(null);
}
}
</script>
php code:
<div>
Subject:
<?php
$conn = new mysqli('localhost', '', '', '')
or die ('Cannot connect to db');
$result = $conn->query("select name from class");
echo "<select name='subject' onchange='getSection('findsection.php?subject=>'this.value'";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$name = $row['name'];
echo '<option value="subject">'.$name.'</option>';
}
echo "</select>";
?>
</div>
<br>
<div id="sectiondiv">
Section:
<select name="select">
</select>
</div>
my findsection.php
<? $subject=intval($_GET[‘subject’]);;
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$mysqli = new Mysqli($servername, $username, $password, $dbname) or mysqli_error($mysqli);
$section = $mysqli->query("SELECT section FROM class WHERE name = '$subject'")->fetch_object()->section;
$result=mysql_query($section);?>
<select name="section">
<? while ($row = $result->fetch_assoc()) { ?>
<option value><?=$row['section']?></option>
<? } ?>
</select>
You have incomplete/invalid html
echo "<select name='subject' onchange='getSection('findsection.php?subject=>'this.value'";
Change it to this
echo '<select name="subject" onchange="getSection(\'findsection.php?subject=\' + this.value)">';
when i click the today button, it goes to updatetoday.php page where i select a query and display it in call back of an ajax and display the table in .php file to div with id #test. but it display's error as Uncaught TypeError: Illegal invocation
$(document).ready(function(){
$('#today').click(function()
{
alert("hi");
$.ajax({
url:'updatetoday.php',
data:{update:today}, // pass data
success:function(result)
{$( "#test" ).html(result);}
});
});
});
updatetoday.php
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['update']==today) //taking
{
echo "<table align='center' border='1' cellspacing='2'><tr><th>Book_id</th><th>Name</th><th>Phone Number</th><th>Email Address</th><th>Start Date</th><th>Source</th><th>Destination</th><th>Morning Time</th><th>Evening Time</th><th>Duration</th><th>Days Off</th><th>Date Off</th><th>Current Status</th><th>Call Counter</th><th>Option</th><th>Calender</th><th>Save</th></tr><br><br><br>
<?php
$query_book = 'Select * from `booking` where validity = 1 limit 5';
$result_book = mysql_query($query_book);
while($row = mysql_fetch_assoc($result_book))
{
$user_id = $row['user_id'];
// query for customer table
$query_cus = 'Select * from `customer` where user_id = $user_id limit 5';
$result_cus = mysql_query($query_cus);
$row_cus = mysql_fetch_assoc($result_cus);
$name = $row_cus['user_id'];
$email = $row_cus['email_id'];
$mobile_number = $row_cus['mobile_number'];
$current_status = $row['valid'];
$startdate = $row['start_date_timestamp'];
if($current_status == '1')
{
$status = '<p style='color:green;font-weight:600;font-size:19px'>Reg</p>';
}
else if($current_status == '2')
{
$status = '<p style='color:green;font-weight:600;font-size:19px'>New</p>';
}
else if ($current_status == '3.1' )
{
$status = '<p style='color:red;font-weight:600;font-size:19px'>R</p>';
}
?>
<tr align='center'><td class='bookid'><?=$row['book_id']?></td><td ><?=$row_cus['name']?></td><td ><?=$row_cus['mobile_number']?></td><td ><?=$row_cus['email_id']?></td><td><?=$row['start_date_timestamp']?></td><td ><?=$row['source']?></td><td ><?=$row['destination']?></td><td ><?=$row['mor_timestamp']?></td>
<td><?=$row['eve_timestamp']?></td><td><?=$row['duration']?></td><td ><?=$row['days_off']?></td><td ><?=$row['date_off']?></td>
<td><?=$row['current_status']?></td ><td ><?=$row['call_counter']?></td>
<td><select class='sel' name='select_option'><option value='NULL'>Select An Option</option><option value='taking'>Taking</option><option value='later-def'>Later Defined</option><option value='later-undef'>Later Undefined</option><option value='outofrange'>Out Of Range</option><option value='rejected'>Rejected</option><option value='norespond'>No Respond</option></select></td><td><input type='text' class='cal' size='6' disabled='disabled' value='<?=$startdate?>'/></td><td><button id='<?php echo $row['book_id'];?>' class='save'>Save</button></td></tr>
<?php
}//booking table while ends
echo '</table>';
?>
</div>";
}
?>
To fix your problem you must change the line :
data:{update:today}, // pass data
to :
data:{update:'today'}, // pass data
in your code today is a string not a varible
Change the line :
success:function(data)
to :
success:function(result)
You are assigning the result from the php to a variable called data and in
{$( "#test" ).html(result);}
trying to display inside the #test div a variable called result.
I have a mysql database with some data. Now i want to show you mysql data to all. with edit option.
<?php
$username = "VKSolutions";
$password = "VKSolutions#1";
$hostname = "VKSolutions.hostedresource.com";
$database = "VKSolutions";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
$query= 'SELECT * FROM customer_details';
$result = mysql_query($query)
or die ('Error in query');
echo '<table width=80% border=1 align="center">';
echo '<tr><td><b>ID</b></td><td width="20px"><b>Name</b></td><td width="25px"> <b>Telephone</b></td><td width="30px"><b>E-mail</b></td><td width="20px"><b>Country Applying for</b></td><td width="20px"><b>Visa Categeory</b></td><td width="20px"><b>Other Categeory</b></td><td width="20px"><b>Passport No</b></td><td width="50px"> <b>Remarks</b></td></tr>';
while ($row=mysql_fetch_row($result))
{
echo '<tr>';
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '</tr>';
}
echo '</table>';
mysql_free_result($result);
mysql_close($dbhandle);
?>
I need some modifications in this code like
1) MySql data displays in a single page. but not i want. I need to display data with several pages like (page1,page2,page3,.....page54... etc)
2) and also give edit option when a user want to change.
Thanks.
You need to add LIMIT to your select statement.
If you read here:
http://dev.mysql.com/doc/refman/5.0/en/select.html
So you would change your statement to:
SELECT * FROM customer_details LIMIT 0,20
This would get the first 20 records, then to get the next lot of results:
SELECT * FROM customer_details LIMIT 20,20
The numbers after the limit are, the first one is where it still start and the second one is how many to return.
I hope this points you in the right direction.
hey if you want to show data with pages use pagination also if you want to edit the value than you have to show data in a text box like this and send via form
<?php
$username = "VKSolutions";
$password = "VKSolutions#1";
$hostname = "VKSolutions.hostedresource.com";
$database = "VKSolutions";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
$query= 'SELECT * FROM customer_details';
$result = mysql_query($query)
or die ('Error in query');
?>
<table width=80% border=1 align="center" id=pag>
<tr><td><b>ID</b></td><td width="20px"><b>Name</b></td><td width="25px"><b>Telephone</b></td><td width="30px"> <b>E-mail</b></td><td width="20px"><b>Country Applying for</b></td><td width="20px"><b>Visa Categeory</b></td><td width="20px"><b>Other Categeory</b></td><td width="20px"><b>Passport No</b></td><td width="50px"><b>Remarks</b></td></tr>
<?php
while ($row=mysql_fetch_row($result))
{
?>
<tr>
<td><input type="text" name="newid" value="<?php echo $row[0];?>" /></td>
<td><input type="text" name="newname" value="<?php echo $row[1];?>" /></td>
<td><input type="text" name="aaaa" value="<?php echo $row[2];?>" /></td>
......
</tr>
<?php
}
?>
</table>
//pagination code
<div class="pagination" align="center" >
<div id="pageNavPosition"></div>
</div>
<script type="text/javascript"><!--
var pager = new Pager('pag',10); // pag is id of table and 10 is no of records you want to show in a page. you can change if you want
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
//--></script>
</div>
<?php
mysql_free_result($result);
mysql_close($dbhandle);
?>
in the head section add this.
<script type="text/javascript" src="paging.js"></script> /* adding javascript pagination source page */
code for paging.js goes here. just copy and paste the code in a file name paging.js
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}
}