I have a dropdown called product1 and a textbox called price1. The dropdown is filled with products from the database. I want to show the price of te selected product in the textbox called 'price1'.
I am using the following table structure:
forms (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sort` int(1) NOT NULL,
`name` varchar(100) NOT NULL,
`prices` decimal(7,2) NOT NULL,
`tax` int(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
With the following code I am trying to fill the textbox with the selected value.
//filename: test.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='getstate(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();
?>
<?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 WHERE id='". $product1 ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div id='price-list'>";
echo "<input type='text' class='form-control' name='price1' id='price1' value='" . $row["price"]. "'>";
echo "</div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<script>
function getprice(val) {
$.ajax({
type: "POST",
url: "test.php",
data:'id='+val,
success: function(data){
$("#price-list").html(data);
}
});
}
</script>
<?php
$product1=$_POST['price1'];
?>
When I select a product in dropdown, nothing is happening.
Can anyone help me to fix this code?
Thanks!
Update 1: Still not working
//filename: 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='getstate(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>
<!-- Your text input -->
<input id="product_name" type="text">
</html>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.select2 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>
And
//filename: 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);
}
$productId = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
$query = 'SELECT price FROM forms WHERE id=' . $productId;
$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
$result = mysql_fecth_assoc($res);
print($result['price']);
die();
}
?>
Try this:
On your select you are putting the callback for onchange, use it to call a javascript function and in this funcion get the value and populate your text field.
...
<select class='form-control select2' id='product1' name='product1'
onchange='changeValue();' style='width: 100%;'>
<!-- Your text input -->
<input id="product_name" type="text">
...
function changeValue() {
// getting the selected text in combo
var selectedItem = jQuery('.select2 option:selected').text;
// and putting in text field
jQuery('#product_name').val(selectedItem);
}
While you have all in the same script test.php you probably introduced the basic problem that you do not distinguish between…
the case when you are setting up the page (first call) with the product list and
the case when you are posting the product id to get the price (AJAX call, whenever the user chooses a different product).
The two cases can be distinguished by the presence of the variable $_POST['id'] (isset($_POST['id']). The variable $_POST['price1'] however is never transmitted and used.
I've puzzled it together (without having it tested). Try it out:
<?php
//filename: test.php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!isset($_POST['id'])) { // First call: setup the page -----------------------------
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
echo '<html>
<head>
<script>
function getprice(val) {
$.ajax({
type: "POST",
url: "test.php",
data:\'id=\'+val,
success: function(data){
$("#price-list").html(data);
}
});
}
</script>
</head>
<body>
';
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
echo "<select class='form-control select2' id='product1' name='product1' onChange='getprice(this.value);' style='width: 100%;'>";
if ( ($result!==false) && ($result->num_rows > 0) ) {
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>";
}
}
if ($result) mysqli_free_result($result);
echo '</select>';
echo '<div id="price-list">';
echo '</div>';
echo '</body>
</html>
';
} else { // Ajax call, $_POST['id'] is set -------------------------
$product1 = $_POST['id'];
$sql = "SELECT * FROM forms WHERE id='". $product1 ."'";
$result = $conn->query($sql);
if ( ($result!==false) && ($result->num_rows > 0) ) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<input type='text' class='form-control' name='price1' id='price1' value='" . $row["price"]. "'>";
break;
}
} else {
echo "0 results";
}
if ($result) mysqli_free_result($result);
}
$conn->close(); // Drop connection
?>
After read your comments I understand that what you need is to get the product price when the combo is changed, but you still don't have these prices. So you can to do an Ajax request to get the price.
...
<select class='form-control select2' id='product1' name='product1'
onchange='getPrice();' style='width: 100%;'>
<!-- Your text input -->
<input id="product_name" type="text">
...
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.select2 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'your-php-file-to-do-query-in-database.php',
method: 'POST',
data: 'product_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);
},
});
}
In you PHP file you must to make a query in database to get product price.
$productId = filter_input(INPUT_POST, 'product_id', FILTER_SANITIZE_NUMBER_INT);
$query = 'SELECT price FROM products WHERE id=' . $productId;
//execute the query in database and return the result
// In this example I will suppose you used the mysql_* functions
// to get the price
$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
$result = mysql_fecth_assoc($res);
print($result['price']);
// and finally ends the script
die();
}
I hope this help you.
Related
If there's duplicated topic - please, forgive me, but i haven't found a solution yet. First of all, I've got one php file (update.php). This file contains:
<form action='update.php' method='post'>
<table border='1'>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "exchange";
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($conn,"utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, name, symbol, buy, sell FROM exchangevalues";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><input type='text' name='ID' value='".$row["ID"]."'>";
echo "<td>".$row["name"]."</td>";
echo "<td>Buy: <input type='text' name='buy' value='".$row['buy']."'></td>";
echo "<td>Sell: <input type='text' name='sell' value='".$row['sell']."'></td>";
echo "</tr>";
}
}
$conn->close();
?>
<table>
There's 14 rows and 5 columns in my db. How do i update every row in columns 'buy' and 'sell' on 'click' (isset submit button) with new values? I've tried with ID[], buy[], but I've got problems with loop and i cannot handle it. I'm running MySQL on localhost, also i know that only last row will be updated without running loop, but still...
I am assuming you have corresponding php code to process the input, here is a sample of what you'll need to do for the HTML when creating the form:
if ($result->num_rows > 0) {
$i=0;
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><input type='text' name='ID[" . $i . "]' value='".$row["ID"]."'>";
echo "<td>".$row["name"]."</td>";
echo "</tr>";
}
}
On the php side to process the input, you can do something like this:
$id_array = $_REQUEST["ID"];
foreach($id_array as $id){
//do insert with $id
}
The below code works perfectly and gives me the "id" "firstname" and "lastname". What I want is to use a loop to echo all the field values in the result row without having to quote each column name like
$row["id"]
below is the working code
<?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();
?>
any thoughts please
This should work..
while($row = $result->fetch_array()) {
$i=0;
while($i<count($row)){
echo $row[$i];
$i++;
}
}
just use a foreach loop inside while like this
foreach($row as $key=>$value){
echo "<br> $key: ". $value. "<br>";
}
If I understand what you want to do is automate the output of the name of each column with its value (independent of the number of columns you get).
So do it like this :
if ($result->num_rows > 0) {
foreach($result->fetch_assoc() as $row) { // browse each records
foreach($row as $col => $value) { // browse each columns on a record
echo "<br>$col: $value<br>";
}
}
}
else {
echo "no result";
}
So I have an SQL database and table, and a php file calls the 10 results from it like this.
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$password = "";
$database = "c9";
$dbport = 3306;
$con = mysqli_connect($servername, $username, $password, $database, $dbport);
if (!$con) {
die("Error! Check your internet connection and try again!");
}
mysqli_select_db($con, "users");
$query = "SELECT * FROM users LIMIT 10";
$result = mysqli_query($con, $query);
echo "<table>
<tr>
<th>ID</th>
<th>Village</th>
<th>Power</th>
<th>Influence</th>
<th>Economy</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['village'] . "</td>";
echo "<td>" . $row['power'] . "</td>";
echo "<td>" . $row['influence'] . "</td>";
echo "<td>" . $row['economy'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
This is an JQuery ajax script I made but it doesn't seem to work
$(document).ready(function(){
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//document.getElementById("divTable").innerHTML=xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "/server.php", true);
xmlhttp.send(null);
});
return false;
What would be the best way to display this table from the php file on a separate index.html file. AJAX, JQuery AJAX, and XML are all options but I don't know how I would do this.
I ideally would want to display the result from the PHP file with document.getElementById('leaderboard').innerHTML because it would take all the html code, including the table.
Any help is greatly appreciated.
Use it!
In Ajax code:
var dataString = 'ajax=true';
$.ajax({
type: "GET",
url: "/server.php",
data: dataString,
dataType:'json',
success: function(data){
alert(data);
}
});
In PHP code:
$query = "SELECT * FROM users LIMIT 10";
$result = mysqli_query($con, $query);
echo json_encode($result); exit();
as the title states I am trying to write a code that will update a boolean data in column (I called 'status') for a specific row. I used while loop in table to display the rows of new registered and where the status is NULL, I've put two buttons (accept, reject) each in td so they'll be displayed to each name, What I want is when the accept button clicked, it sets the status of its row in the table to 1, and when reject is clicked, same thing but sets 0 instead of 1.
I've did a lot of research over this but hit a road block after road block, so I really hope your help in this, many thanks!
Here is my code:
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc".$i."'>Accept</button></td>";
echo "<td><button name='sRej".$i."'>Reject</button></td>";
echo "</tr>";
$i++;
}
if (isset($_POST['sAcc'.$i])) {
$row['status'] = 1;
}
}
getStudent();
?>
</table>
First of all, you miss <form> element. Your form inputs are useless without it, or without ajax.
Secondly, your $_POST check will only check last item. Since after you exit loop $i is set to last value in the loop. So your example will only work on last item.
<button> will now send $_POST with one of indexes sAcc or sRej. And it's value will be ID of your entry.
<table id="sHold" style="border:none;">
<form method="post" action="">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>{$sId}</td>";
echo "<td>{$sName}</td>";
echo "<td><button type='submit' name='sAcc' value='{$sId}'>Accept</button></td>";
echo "<td><button type='submit' name='sRej' value='{$sId}'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
if (isset($_POST['sAcc']) && intval($_POST['sAcc'])) {
$user_id = (int) $_POST['sAcc'];
// Do the database update code to set Accept
}
if (isset($_POST['sRej']) && intval($_POST['sRej'])) {
$user_id = (int) $_POST['sRej'];
// Do the database update code to set Reject
}
getStudent();
?>
</form>
</table>
Tip: I assume you're beginner. I remade your code. But you dont need to put this code into function. Use functions to handle data retrieval for example. Dont use it to display html.
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table where status='NULL'";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['name'];
echo "<tr id='".$sId."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc' id='acc-".$sId."' onclick='approveuser(this.id)'>Accept</button></td>";
echo "<td><button name='sRej' id='rec-".$sId."' onclick='approveuser(this.id)'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
getStudent();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function approveuser(id){
trid=id.split('-')[1];
//alert(trid);
$.ajax({
url: "update.php",
type:"post",
data:{ val : id },
success: function(result){
//alert(result);
$('table#sHold tr#'+trid).remove();
alert('Updated');
}
});
}
</script>
//The code give below this update.php pge(ajax page)
<?php
$data=$_POST['val'];
$status =explode('-',$data);
$user_id=$status[1];
if($status[0]=='acc'){
$value=1;
}
elseif($status[0]=='rec'){
$value=0;
}
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
mysqli_query($conn,"update student_table set status='$value' where student_id=$user_id");
?>
I've created drop down list with value name from the database. When I select the value from the drop down list, other data will appear in other textfield based on the database. The submit process was doing fine except when I check on the list. The drop down list value didn't appear in the list but other data did.
This is my adding form:
<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)){
$option_value = $row['priceperunit'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select ></center>
This is a script to display other database value in other textfield when the drop down list is selected:
<script>
var select = document.getElementById('name');
var priceperunit = document.getElementById('priceperunit');
var stock = document.getElementById('stock');
select.onchange = function()
{
var priceperunit_stock = select.value.split(',');
priceperunit.value = priceperunit_stock[0];
stock.value = priceperunit_stock[1];
}
</script>
This is my inserted data into database process:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "arie";
$connect = mysql_connect($host, $user, $pass) or die ('Failed to connect! ');
mysql_select_db($db);
$name=$_POST['name'];
if ($name === "")
{
echo "Please fill all the data";
}
else
{
$query="INSERT INTO `tabelout`(`name`)
VALUES ('$name');";
$result = mysql_query($query) OR die (mysql_error());
echo "You have successfully added new medicine to the database.";
}
?>
This is my list page, where the name didn't show up:
<?php
$con=mysqli_connect("localhost","root","","arie");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tabelout");
echo "<table border='1'>
<th>name</th>";
while($row = mysqli_fetch_array($result))
{
echo "<td><center>" . $row['name'] . "</center></td>";
}
echo "</table>";
mysqli_close($con);
?>
Make sure your database table has records, If it has records, then change the table structure, Add tr tags where required.
echo "<table border='1'>
<tr><th>name</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td><center>" . $row['name'] . "</center></td></tr>";
}
echo "</table>";