I am creating a small project to explain my students on how to update values in SQL database using PHP code. I have created table in MySQL with all the fields as VARCHAR. I have written the following code which throws following error :
Error in Updting valueYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Mbps WHERE dsl = '25610669'' at line 1 where 25610669 is an existing record in the database. Here is the code:
<?php
if((isset($_POST['B2'])))
{
$server = 'localhost' ;
$un = 'root' ;
$pass = 'icsk' ;
$db = 'yusuf' ;
$conn = mysqli_connect($server, $un, $pass, $db);
$update = "UPDATE homereg SET Fname = {$_POST['First']}, Lname = {$_POST['Last']}, cid = {$_POST['cid']}, pack = {$_POST['choice']} WHERE dsl = {$_POST['dsl']}" ;
$result = mysqli_query($conn, $update);
if($result == 1)
{
echo "Successfully Updated" ;
}
else
{
echo "Error in Updting value" . mysqli_error($conn) ;
}
}
?>
<html>
<head>
<title>Update User Information</title>
</head>
<body background="HomePageMap.gif">
<CENTER><B><FONT COLOR = 'RED'>SEARCH & UPDATE THE EXISTING RECORD HERE </FONT></B></CENTER><P>
<form method="POST" action="modify.php" name = "frm">
<div align="center">
<table border="1" width="314">
<tr>
<td width="130"><b>DSL Number</b></td>
<td width="168"><input type="text" name="dsl" size="20"></td>
</tr>
<tr>
<td width="130"><b>First Name</b></td>
<td width="168"><input type="text" name="First" size="20"></td>
</tr>
<tr>
<td width="130"><b>Last Name</b></td>
<td width="168"><input type="text" name="Last" size="20"></td>
</tr>
<tr>
<td width="130"><b>Civil ID</b></td>
<td width="168"><input type="text" name="cid" size="20"></td>
</tr>
<tr>
<td width="130"><b>Net Pack</b></td>
<td width="168"><select size="1" name="choice">
<option value = "2 Mbps">2 Mbps</option>
<option value = "5 Mbps">5 Mbps</option>
<option value = "10 Mbps">10 Mbps</option>
<option value = "15 Mbps">15 Mbps</option>
</select></td>
</tr>
</table>
</div>
<p align="center"><input type="submit" value="Search" name="B1">
<p align="center"><input type="submit" value="Modify" name="B2">
<input type="reset" value="Reset" name="B2"></p>
</form>
<p align="center"> </p>
</body>
</html>
If answer below me not work, try this:
$update = "UPDATE homereg SET Fname = `$_POST['First']}`, Lname = `$_POST['Last']`, cid = `$_POST['cid']`, pack = `$_POST['choice']` WHERE dsl = `$_POST['dsl']`" ;
You have to put quotes around strings like this:
$update = "UPDATE homereg SET Fname = '{$_POST['First']}', Lname = '{$_POST['Last']}', cid = '{$_POST['cid']}', pack = '{$_POST['choice']}' WHERE dsl = '{$_POST['dsl']}'" ;
Also, not sure if you left it out because it's just an example, but you'll want to escape your POST values to protect against SQL injection like so:
$first = mysqli_real_escape_string($conn, $_POST['First']);
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I've got some code where I have to input my contact data from client, and output data from MySQL database which creates new rows in table
Also there's additional function which has to be inside the code - but I've no idea how to handle this problem. I have to count the amount of element pieces x their weight in real-time to show the client the total weight the order is going to have.
The problem is I don't know how to make the client see it whenever they change the value of Pieces in <input>.
Lastly, the data from the form and table has to be sent to employee via email.
PHP Code:
<html>
<head>
<meta charset="utf-8" />
<meta name="calculator" content="width=device-width, initial-scale=1"/>
<title>Test</title>
<link rel="stylesheet" href="style.css" >
</head>
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<h1>TEST</h1>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="<?= $form['EMAIL']; ?>" class="form-contact" required><br>
<input id="Country" type="text" placeholder="<?= $form['COUNTRY']; ?>" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="<?= $form['PHONE']; ?>" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<table class="table-responsive" border="1">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".'<input class="pcs-input" min=0 maxlength="3" value=0 size="2px" style="background-color: white;" name="inputs[]">';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sumWeight'></div></td></tr>";
}
} else {
echo "0 Results";
}
mysqli_close($connection);
?>
</tbody>
</table>
<!-- Counting all needed atributes -->
<div id="totalWeight">totalWeight</div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
</html>
JavaScript Code
<script type="text/javascript">
document.addEventListener(function()
input.OnChange = calculateForm();
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
totalWeight += sumWeight;
}
});
document.write(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
Updated
Well it doesn't work again, no errors, just doesn't multiply
I think the problem might be with transporting data from table/database into the variable, any solution?
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' id='inputs' data-weight=".$row["weight"];
echo "></input>";
# echo "<tr><td>".$row["id"].'';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sum-Weight2'></div></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).parent().parent().find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('.totalGewicht').html(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
<!-- Counting all needed atributes -->
<div id="totalWeight"></div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
Overall there are quite a few issues with your code, which can be summarised as problems with
invalid HTML (e.g. duplicate IDs, incorrectly written input element, un-closed table rows, un-closed data attributes)
over-complicated HTML
typing or case errors (e.g. W instead of w)
incorrect CSS selectors in the JavaScript
lack of initial default data (e.g. if there are no numbers in any one of the input boxes, the calculation will fail because trying to add a blank value to another number results in NaN (Not a Number)
calculation did not run when page loads, so data is missing until the user changes something (which is no use, if they want to see the current weight before changing any values)
This client-side demo demonstrates the HTML you need to get your PHP to produce, and the correct JavaScript / jQuery code in order to do the calculations and display the results:
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
table
{
border-collapse:collapse;
}
td
{
border: solid 1px black;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td><input type='number' class='pcs-input' data-weight='3' value='1' /></td>
<td>Nr. 14536</td>
<td>Test 1</td>
<td>3 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='15' value='1' /></td>
<td>Nr. 23431</td>
<td>Test 2</td>
<td>15 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='4' value='1' /></td>
<td>Nr. 33125</td>
<td>Test 3</td>
<td>4 kg</td>
<td class='sum-weight2'></td>
</tr>
</tbody>
</table>
Total Weight: <span id="totalWeight"></span>
Remember you need to move the focus from the textbox to another element (using mouse or tab key) before the "change" event will fire. (It will also run if you use the up/down buttons on the input box.)
So this means, as well as editing the JavaScript as I've shown, you need to alter the PHP so it outputs the HTML table rows with the structure and data I've demonstrated above.
This should work:
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='1' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
Resolution:
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="Email" class="form-contact" required><br>
<input id="Country" type="text" placeholder="49" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="Tel" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class=".table-responsive">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='0' min='0' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
</script>
<!-- Counting all needed atributes -->
Total Weight: <span id="totalWeight"></span>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
I have the following html table with select option in one of the columns. I want to display the values of the rows that are checked but don't know how to work with the select option value. Can someone help me modify the code? If not using DOM, can we just use PHP to get all checked values and store in $ variable? Finally I will submit the checked values and insert into table using PHP. Thanks a lot.
<?php
require_once("connMysql.php");
$stu_add = mysqli_query($db_link, "SELECT * FROM stu");
$rowcount = mysqli_num_rows($stu_add);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>how to get options value in html table</title>
</head>
<body>
<table id="table" border="1">
<tr>
<th style="text-align:center; width:70px">Classname</th>
<th style="text-align:center; width:100px">Student ID</th>
<th style="text-align:center; width:100px">Name</th>
<th style="text-align:center; width:100px">Grade</th>
<th style="text-align:center; width:100px">Select</th>
</tr>
<?php
if($stu_add-> num_rows > 0 ){
while ($row = $stu_add-> fetch_assoc()){
?>
<tr>
<td id="classname" style="text-align:center;"><?php echo $row['classname'];?></td>
<td id="stuid" style="text-align:center;"><?php echo $row['stuid'];?></td>
<td id="stu_name" style="text-align:center;"><?php echo $row['stu_name'];?></td>
<td><select name="grade" id="grade">
<option value="">-Please select-</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</td>
<td align="center">
<input type="checkbox" id="checked" name="checked[]" value="<?php echo $row['stuid'];?>">
</td>
</tr>
<?php
}
}
?>
<input type="text" id="classname" size="10">
<input type="text" id="stuid" size="10">
<input type="text" id="stu_name" size="10">
<input type="text" id="grade" size="10">
<button class="" onclick="showData()">Show data</button>
</table>
<script>
function showData()
{
var table = document.getElementById('table');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
// document.getElementById("classname").value = this.cells[0].innerHTML;
// document.getElementById("stuid").value = this.cells[1].innerHTML;
// document.getElementById("stu_name").value = this.cells[2].innerHTML;
// document.getElementById("grade").value = this.cells[3].innerHTML.options[0].text;
var a = this.cells[0].innerHTML;
var b = this.cells[1].innerHTML;
var c = this.cells[2].innerHTML;
var d = this.cells[3].innerHTML.options[0].text;
var data = a + b + c + d;
alert(data);
};
}
}
</script>
As the above user says you can get the id of the checkbox and use onchange then pass the value to the function.
```
$('#checkbox').change(function(){
var query = $(this).val();
showdata(query);
});
```
I have a listbox that displays a couple of internships under following format
id - name :
1 - Computer Science
So far, I have create the function addRow in order to update my fields from form.
If I do
alert($montext)
I can display "1 - Computer Science", but I am looking only for the value "1".
I tried :
alert(<?php substr($montext,0,2)?>);
But seems that php inside "script" isn't being executed.
Because following code changes the value in the field:
document.getElementById('ti').value=$montext;
Because I'd like also to execute php code inside the script TAG.
I'm running under Apache.
If you could help me out. Thanks
Find hereby the used code.
<html>
<head>
<script>
function addRow(title,text,description,id) {
$montext=$( "#idStage option:selected" ).text();
alert($montext);
document.getElementById('ti').value=$montext;
/*document.getElementById('te').value=text;
document.getElementById('de').value=description;
document.getElementById('id').value=id;*/
}
function setText(title,text,description,id){
document.getElementById('title').value=title;
document.getElementById('text').value=text;
document.getElementById('description').value=description;
document.getElementById('id').value=id;
}
</script>
</head>
<body>
<?php
include('../admin/connect_db.php');
?>
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<label class="notBold">Choose the internship you want to update: </label>
<select name="idStage" id="idStage" onChange="addRow()">
<?php
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT id, title,text,description FROM offre ORDER by published_date ASC')) {
$stmt->bind_result($id,$title,$text,$description);
$stmt->execute();
while($stmt->fetch()){
?>
<option id="nostage" value="<?php echo$id;?>" onclick="setText('<?php echo $title ?>',' <?php echo $text ?> ',' <?php echo $description ?>',' <?php echo $id?>');"><?php echo $id." - ".$title;?></option>
<?php
}
$stmt->close();
}
?>
</select>
</td>
<td width="20">
<img src="./Image/exit.png" title="Close" id="closeDelete" class="closeOpt" onclick="closeOpt()" />
</td>
</tr>
</table>
<form method="post" action="modifystage.php">
<table>
<tr>
<td>
<input type = "hidden" id ="id" name="id"/>
</td>
</tr>
<tr>
<td class="label">
<label>Title </label>
<textarea id = "ti" name="ti" rows = "3" cols = "75">
<?php
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT id, title,text,description FROM offre ORDER by published_date ASC')) {
$stmt->bind_result($id,$title,$text,$description);
$stmt->execute();
}
echo $title;
?>
</textarea>
</td>
</tr>
<tr>
<td class="label">
<label>Desc</label>
<textarea id = "de" name="de" rows = "3" cols = "75">
<?php
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT id, title,text,description FROM offre ORDER by published_date ASC')) {
$stmt->bind_result($id,$title,$text,$description);
$stmt->execute();
}
echo $description;
?>
</textarea>
</td>
</tr>
<tr>
<td class="label">
<label>Text </label>
<textarea id = "te" name="te" rows = "3" cols = "75">
<?php
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT id, title,text,description FROM offre ORDER by published_date ASC')) {
$stmt->bind_result($id,$title,$text,$description);
$stmt->execute();
}
echo $text;
?>
</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="right"colspan="2" class="label">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>
You don't need to use PHP here. Use the javascript substring function - http://www.w3schools.com/jsref/jsref_substring.asp
For example
alert(montext.substring(0, 2));
Write your <script> on bellow your PHP and try this :
<script>
function addRow(title,text,description,id) {
var montext = $( "#idStage" ).text();
alert(montext);
document.getElementById('ti').value(montext);
/*document.getElementById('te').value=text;
document.getElementById('de').value=description;
document.getElementById('id').value=id;*/
}
function setText(title,text,description,id){
document.getElementById('title').value=title;
document.getElementById('text').value=text;
document.getElementById('description').value=description;
document.getElementById('id').value=id;
}
</script>
If you want to call variable from PHP, don't forget to use echo like this :
alert("<?php echo substr($montext,0,2); ?>");
I have 3 different selectboxes. Second and third select boxes will be populated depending on first select boxes' value via ajax + php. But the response is not as i expected. It the shows error function. When i check it from the console there is no promlem with reading data from database as json format. But i'am unable to show these data as html to the screen. Here is my try:
HTML:
<table>
<tr>
<td valign="middle" align="center">
<label id="fieldOfBusinessLabel" for="fieldOfBusinessText">Field of Business</label>
</td>
<td valign="middle" align="center">
<select id="fieldOfBusinessSelectBox" class="selectBox" name="fieldOfBusinessSelectBox">
<option value="">--select--</option>
<?php
$result=mysqli_query($db,'SELECT * FROM field_of_business');
while($row=mysqli_fetch_assoc($result)) {
echo '<option value="'.$row["FobID"].'">'.$row['FobName'].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td valign="middle" align="center">
<label id="typeOfProductionLabel" for="typeOfProductionText">Type of Production/Service</label>
</td>
<td valign="middle" align="center">
<select id="typeOfProductionSelectBox" clas="selectBox" name="typeOfProductionSelectBox">
<option value="">--select--</option>
</select>
</td>
</tr>
<tr>
<td valign="middle" align="center">
<label id="mainProductsLabel" for="mainProductsText">Main Products/Services</label>
</td>
<td valign="middle" align="center">
<select id="mainProductSelectBox" clas="selectBox" name="mainProductSelectBox">
<option value="">--select--</option>
</select>
</td>
</tr>
</table>
JS:
$(document).ready(function(){
$("#fieldOfBusinessSelectBox").change(function(){
var value = $("select#fieldOfBusinessSelectBox option:selected").val();
$.ajax({
type: 'POST',
url: 'listData.php',
dataType: "json",
data:{fobID:value},
success:function(answer){
var data1 = "<option>--select--</option>";
var data2 = "<option>--select--</option>";
$.each(answer, function(i, answer){
data1 += "<option>"+answer.TopsName+"</option>";
});
$.each(answer, function(i, answer){
data2 += "<option>"+answer.MpsName+"</option>";
});
$('#typeOfProductionSelectBox').html(data1);
$('#mainProductSelectBox').html(data2);
},
error:function(){
alert("An error has occured !");
}
});
});
});
PHP:
<?php
include './config.php';
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest'){
die('Wrong request !');
}
$fobID = mysqli_real_escape_string($db,$_POST['fobID']);
if(isset($_POST['fobID'])){
$stmt1 = $db->prepare("SELECT TopsName FROM type_of_production_service WHERE FobID = ?");
if($stmt1 == "false"){
die('Query error !'.$db->error);
}
$stmt1->bind_param('i', $fobID);
$stmt1->execute();
$result = $stmt1 -> get_result();
$topsName = $result ->fetch_all(MYSQLI_BOTH);
echo json_encode($topsName);
$stmt2 = $db->prepare("SELECT MpsName FROM main_products_services WHERE FobID = ?");
if($stmt2 == "false"){
die('Query error !'.$db->error);
}
$stmt2->bind_param('i', $fobID);
$stmt2->execute();
$result2 = $stmt2 -> get_result();
$mpsName = $result2 ->fetch_all(MYSQLI_BOTH);
echo json_encode($mpsName);
}
$db->close();
You have 2 json_encoded strings in result and it not decoded. User one json object:
PHP:
echo json_encode(array('mps' => $mpsName, 'tops' => $topsName));
JS:
answer = $.parseJSON(answer);
$.each(answer.tops, function(k,v){...});
$.each(answer.mps, function(k,v){...});
When user select the dropdownlist value,the price will show up according to the database.I'm dying thinking about the code.i hope anyone can help me here.
<form action="next.php" method="post">
<center>
<table>
droplist to display database row name from table tabelmedicine
<tr><td width="116">Medicine name</td><td width="221">
<center>:
<select name="name" id="name">
<option>--- Choose Medicine ---</option>
connect with db
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
echo '<option>'.$row['name'].'</option>';
}
}
?>
</select ></center>
</p></td></tr>
textfield to display price value from tabelmedicine row priceperunit
<tr><td><p>Price</p></td><td><p align="center">:<input type="text" name="price"
id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
</p></td></tr>
<script>
var select = document.getElementById('name');
var input = document.getElementById('price');
select.onchange = function()
{
input.value = select.value;
}
</script>
This should do it. Just make sure $row['price'] is the correct database field key
<form action="insertout.php" method="post">
<center>
<table>
<tr>
<td width="116">Medicine name</td>
<td width="221">
<center>
:
<select name="name" id="name">
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
echo '<option value="'.$row['price'].'">'.$row['name'].'</option>';
}
}
?>
</select >
</center>
</p>
</td>
</tr>
<tr>
<td>
<p>Price</p>
</td>
<td>
<p align="center">:<input type="text" name="price"
id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<script>
var select = document.getElementById('name');
var input = document.getElementById('price');
select.onchange = function(){
input.value = select.value;
}
</script>