I'm making something for a stocktake.
I have a form that generates with 4 fields. item_code, item_name, packing, quantity
<form action="goods.php" method="post">
<table>
<!-- Headers -->
<tr>
<td><b>Item Code</b></td>
<td><b>Description</b></td>
<td><b>Packing</b></td>
<td><b>Quantity</b></td>
</tr>
<?php
for ($i = 0; $i <= 50; $i++) {
?>
<tr>
<td>
<INPUT TYPE="TEXT" NAME="item_code[<?php echo $i; ?>]" SIZE="6" VALUE="
<?php
if (!empty($_POST["item_code"][($i)])) {
echo $_POST["item_code"][($i)];
}
?>"></td>
<td><?php
if (!empty($_POST["item_code"][($i)])) {
$result = FetchData($_POST["item_code"][($i)]);
echo $result['category'];
}
?>
</td>
<td>
<?php
if (!empty($_POST["item_code"][($i)])) {
echo $result['item_name'];
}
?></td>
<td>
<?php
if (!empty($_POST["item_code"][($i)])) {
echo $result['packing'];
}
?></td>
<td><INPUT TYPE="TEXT" NAME="quantity[<?php echo $i; ?>]" SIZE="5" VALUE="
<?php
if (!empty($_POST["quantity"][($i)])) {
echo $_POST["quantity"][($i)];
} else {
echo "";
}
?>"></td>
A js function for the button
<script>
function fillForm(value) {
document.getElementById('value').innerHTML = value;
}
</script>
and a list that is generated with 3 fields. item_code, item_name, packing
<?php
$dbh = dbh_get();
$sql = 'SELECT * FROM goods as goods(item_code, sort) order by human_sort(goods.item_code)';
$v = array();
$stmt = $dbh->prepare($sql);
$stmt->execute();
while (true) {
$r = $stmt->fetch();
if (is_bool($r)) break;
print '
<tr>
<td class="buttonL" id="<php ' . $r['item_code'] . ' ?>" onclick="fillForm()">' . $r['item_code'] . '</td>
<td>' . $r['item_name'] . '</td>
<td>' . $r['packing'] . '</td>
</tr>' . "\n";
}
dbh_free($dbh);
?>
}
I want to put a button on each list row and when it's clicked it populates the first three fields in the form, leaving quantity to be filled out. Then when another is clicked it populates the next form row etc,. It's working fine manually entering from the list, but the list is nearly 5000 items so it's a hassle to keep searching then scrolling up and entering the values.
I don't see how to do this with PHP so I assume I need a javascript function, which is where I'm lost. Let me know if you need more info.
Related
I have a somefile.php and someotherfile.js with the code as below
javascript file
function deleteSelectedRow() {
return (confirm('Are you sure you want to delete this record))
};
<!DOCTYPE html>
<html lang=" en">
<head>
<title> Title </title>
</head>
<body>
<h1>Select the user to delete from the list below </h1>
<form action="" method="POST">
<?php
if(require_once('../SQL/mySQL_connect.php'))
{
$query = "SELECT id, FirstName, LastName, PhoneNumber FROM participants ORDER BY id ASC";
$userDetails = #mysqli_query($mysqli, $query);
}
else
{
echo "Couldn't connect to database";
echo mysqli_error($mysqli);
}
// mysqli_close($mysqli);
?>
<br><br><br>
<table name="userDetailsTable" id="userDetailsTable" align="left" cellspacing="7" cellpadding="8">
<tr>
<td align="center"><b>S No</b></td>
<td align="center"><b>Id</b></td>
<td align="center"><b>Rank</b></td>
<td align="center"><b>First Name</b></td>
<td align="center"><b>Last Name</b></td>
</tr>
<?php
for($i = 1; $i <= mysqli_num_rows($userDetails); $i++)
// while($row=mysqli_fetch_array($userDetails))
{
$row=mysqli_fetch_array($userDetails);
echo '<tr>
<td align ="center" >'. $i .'</td>
<td align ="center" >' . $row['id'] . '</td>
<td align ="center">' . $row['Rank'] . '</td>
<td align ="center">' . $row['FirstName'] . '</td>
<td align ="center">' . $row['LastName'] . '</td>
<td align ="center"> <input type = submit name="delete" value="delete" onclick="return deleteSelectedRow();" ></input></td>';
echo '</tr>';
}
?>
</table>
</form>
<?php
if(isset($_POST['delete']))
{
require_once('../SQL/mySQL_connect.php');
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$_POST['IDNumber']."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
echo "Deleted from Database Successfully";
}
else
{
echo "Couldn't Delete from database";
echo'<br>';
echo mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
?>
</body>
What this code does is as follows
Connects to database and retrieves the user details
Creates a table and prints out the user details in it
user clicks on delete button in front of any record and it gets deleted after confirmation
A success message is displayed that the message is deleted
What I want to do is that after displaying the success message the above printed table should get updated automatically so that user is confirmed that the id no longer exists in the table
I tried the following solutions
reload page just before the success message is displayed so that user sees the success message as well as the updated table as well (since reload will re-connect to database and refetch the table)
I tried to use "location.reload(true)" command but i can't figure out where to place this line so that it gets executed just before the success message is displayed.
Any help is much appreciated
A few things:
you'll want the delete operation to be the first thing you do on the page (if it's a form submit) because otherwise you'll print the "pre-deleted" table.
you need to pass the ID through post in the form. It's easier if you just have a unique for for every row, and have a hidden ID input for each.
The confirm is better attached to the form submit event, because otherwise you'll miss other, non-click, input methods.
Your delete operation, as it was written in the question, is susceptible to an SQL Injection attack. You'll want to escape that POST value.
Something like the below should work
function deleteSelectedRow() {
return (confirm('Are you sure you want to delete this record))
};
<?php
$message = '';
$connected = false;
if(require_once('../SQL/mySQL_connect.php'))
{
$connected = true;
}
if($connected && isset($_POST['delete']))
{
$id_to_delete = mysqli_real_escape_string($mysqli, $_POST['IDNumber']);//escape value to prevent sql injection attack
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$id_to_delete."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
$message = "Deleted from Database Successfully";
}
else
{
$message = "Couldn't Delete from database";
$message .='<br>';
$message .= mysqli_error($mysqli);
}
//mysqli_close($mysqli);
}else{
$message = "unable to connect to database";
}
?><!DOCTYPE html>
<html lang=" en">
<head>
<title> Title </title>
</head>
<body>
<h1>Select the user to delete from the list below </h1>
<?php
if($connected)
{
$query = "SELECT id, FirstName, LastName, PhoneNumber FROM participants ORDER BY id ASC";
$userDetails = #mysqli_query($mysqli, $query);
}
else
{
echo "Couldn't connect to database";
echo mysqli_error($mysqli);
}
?>
<br><br><br>
<?php if($message){ /* do we have a success/error message from the delete operation? */ ?>
<p><?php echo $message; ?></p>
<?php } ?>
<table name="userDetailsTable" id="userDetailsTable" align="left" cellspacing="7" cellpadding="8">
<tr>
<td align="center"><b>S No</b></td>
<td align="center"><b>Id</b></td>
<td align="center"><b>Rank</b></td>
<td align="center"><b>First Name</b></td>
<td align="center"><b>Last Name</b></td>
</tr>
<?php
for($i = 1; $i <= mysqli_num_rows($userDetails); $i++)
// while($row=mysqli_fetch_array($userDetails))
{
$row=mysqli_fetch_array($userDetails);
echo '<tr>
<td align ="center" >'. $i .'</td>
<td align ="center" >' . $row['id'] . '</td>
<td align ="center">' . $row['Rank'] . '</td>
<td align ="center">' . $row['FirstName'] . '</td>
<td align ="center">' . $row['LastName'] . '</td>
<td align ="center"> <form action="" method="POST" onsubmit="return deleteSelectedRow();"><input type="hidden" name="IDNumber" value="'.$row['id'].'" /><input type = submit name="delete" value="delete"></form></td>';
echo '</tr>';
}
?>
</table>
<?php if($connected){
mysqli_close($mysqli);
} ?>
</body>
You need to store the Success/Error message in a $_SESSION["flash"] instead of show by echo and after delete the user you must redirect to the same page.
On the top of the page, if isset the $_SESSION["flash"] you can show the message and remove it from the session. In code:
if(isset($_POST['delete']))
{
require_once('../SQL/mySQL_connect.php');
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$_POST['IDNumber']."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
$_SESSION["flash"] = "Deleted from Database Successfully";
}
else
{
$_SESSION["flash"] = "Couldn't Delete from database";
//echo'<br>';
//echo mysqli_error($mysqli);
}
mysqli_close($mysqli);
header('Location: '.$_SERVER['PHP_SELF']);
}
and on the top of the page of before isset($_POST['delete']):
if(isset($_SESSION["flash"])){
echo $_SESSION["flash"];
unset($_SESSION["flash"]);
}
don't forget to start_session() on the top of the page.
I'll notice that your code have a SQL Injection Vulnerability. You shouldn't do MySQL queries without validate GET and POST input data.
I am calling Api : $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123'; and fetching Status results of all Order IDS & displaying in php page when we refresh php page.
Now i want to select Order IDs through checkbox, than when i click on button "Show Status" , than only i want to Call Api & update the Selected Order IDs status in web page.
<p><button type= "button" class="call">Show Status</button></p>
<table class="tbl-qa" border="1">
<thead>
<tr>
<th class="table-header"></th>
<th class="table-header">ORDERID</th>
<th class="table-header">Status</th>
</tr>
</thead>
<tbody id="table-body">
<?php
$tabindex = 1;
if (!empty($orderrecords))
{
foreach($orderrecords as $k => $v)
{ ?>
<?php
$hide = '';
$data['username'] = 'admin';
$data['password'] = 'admin123';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';
$ch = curl_init();
// some curl code
$res = explode("\n", $output);
if (!isset($res[13]))
{
$res[13] = null;
}
$status = $res[13];
?>
<tr class="table-row" id="table-row-<?php echo $orderrecords[$k]["id"]; ?>" tabindex="<?php echo $tabindex; ?>">
<td><input onclick="assignorderids('<?php echo $orderrecords[$k]["order_id"]; ?>')" type="checkbox" name="assigneeid" id="assigneeid-<?php echo $orderrecords[$k]["order_id"]; ?>" value="<?php echo $orderrecords[$k]["order_id"]; ?>"></td>
<td><?php echo $orderrecords[$k]["order_id"]; ?></td>
<td><?php echo $status; ?></td>
</tr>
<?php
$tabindex++;
}
} ?>
</tbody>
</table>
Please help me how i can achieve this ?
Update : assignorderids function
function assignorderids(oid)
{
var checkstatus=$("#assigneeid-"+oid).is(":checked");
var morderId =document.getElementById("orderids").value;
if(checkstatus==false)
{
var arrayorder = JSON.parse("[" + morderId + "]");
document.getElementById("orderids").value='';
for (var i = 0; i < arrayorder.length; i++) {
var orderstatusValue=arrayorder[i];
if(orderstatusValue!=oid){
if (document.getElementById("orderids").value=='')
{
document.getElementById("orderids").value=orderstatusValue;
}
else
{
var newvalue=document.getElementById("orderids").value;
document.getElementById("orderids").value=newvalue+","+orderstatusValue;
}
}
}
}
else
{
if(morderId=='')
{
document.getElementById("orderids").value=oid;
}
else
{
document.getElementById("orderids").value=morderId+","+oid;
}
}
}
Url Output
Basically, I have a table with two column: 'Kode Barang' (Item ID) and 'Nama Barang' (Name of Item). The first column is a dropdown option which it's data get populated dynamically from another table. If a user select an Item ID, then the second column will automatically show the name of the item.
Let's say that I've only two row as this code below:
<HTML>
<table id="theTable" border="1">
<thead>
<tr>
<th> Kode Barang </th>
<th> Nama Barang </th>
<tr>
</thead>
<tbody>
<tr>
<td type="text" name="kode_barang" id="kode_barang"/readonly>
<?php
mysql_connect("localhost","root","");
mysql_select_db("skripsi_1");
$result = mysql_query("select * from input_data_barang");
$jsArray = "var kode_barang = new Array();\n";
echo '<select name="kode_barang" onchange="changeValue(this.value)">';
echo '<option></option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['kode_barang'] . '">' . $row['kode_barang'] . '</option>';
$jsArray .= "kode_barang['" . $row['kode_barang'] . "'] = {name:'" . addslashes($row['nama_barang']) . "',desc:'".addslashes($row['nama_barang'])."'};\n";
}
echo '</select>';
?>
</td>
<td><input type="text" name="nama_barang" id="nama_barang"/readonly>
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(id){
document.getElementById('kode_barang').value = kode_barang[id].name;
document.getElementById('nama_barang').value = kode_barang[id].desc;
};
</script>
</td>
</tr>
<tr>
<td type="text" name="kode_barang" id="kode_barang"/readonly>
<?php
mysql_connect("localhost","root","");
mysql_select_db("skripsi_1");
$result = mysql_query("select * from input_data_barang");
$jsArray = "var kode_barang = new Array();\n";
echo '<select name="kode_barang" onchange="changeValue(this.value)">';
echo '<option></option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['kode_barang'] . '">' . $row['kode_barang'] . '</option>';
$jsArray .= "kode_barang['" . $row['kode_barang'] . "'] = {name:'" . addslashes($row['nama_barang']) . "',desc:'".addslashes($row['nama_barang'])."'};\n";
}
echo '</select>';
?>
</td>
<td><input type="text" name="nama_barang" id="nama_barang"/readonly>
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(id){
document.getElementById('kode_barang').value = kode_barang[id].name;
document.getElementById('nama_barang').value = kode_barang[id].desc;
};
</script>
</td>
</tr>
</table>
</HTML>
The first row works perfectly. The problem is in the second row. If I select an option from the dropdown, then name of the item doesn't appear in the second row, but appear in the first row instead. Would anybody please show me how to fix this? Thank you.
You are appending your values using:
document.getElementById('kode_barang').value = kode_barang[id].name;
document.getElementById('nama_barang').value = kode_barang[id].desc;
The problem is, that there is an Element with the ID kode_barang/nama_barang in BOTH rows. So you have 2 Elements for the ID's. Javascript appereantly just decides only to take the first one. Just rename them in the second row to "kode_barang2" and "nama_barang2" and when setting the values change the names too:
document.getElementById('kode_barang2').value = kode_barang[id].name;
document.getElementById('nama_barang2').value = kode_barang[id].desc;
I have an SQL-database with many tables. Now I would like to create an input-form to be able to get data into the db without writing the entire sql-code every time. And this should work as follows:
All table names are listed in a drop-down menu. After having selected a table name, a new table with 4 columns is created automatically:
The first column of this table simply contains an increasing number.
The second column contains the field-names of the selected table.
In the third column there are empty input fields to enter the values for the database. Only in the third line (=product name) there is a drop-down menu with all product names from the main-table of the db.
The fourth column contains the data type (e.g. int or varchar)
All tables in the database have the same structure in the first 3 columns: the first column contains the table-id, the second column the foreign-key (=master_id) and the third column the product_name.
Up to this point, the script works well with the following 2 php-files (javasql.php and getuser.php):
javasql.php:
enter code here
<!DOCTYPE html>
<html>
<head>
<script>
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 (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="" class="optdrugs">please select</option>
<?php
include("files/zugriff.inc.php"); // database Access
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'product'";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optdrugs" value="'. $row['TABLE_NAME'] . '">' .
$row['TABLE_NAME']. '</option>';
echo '<br>';
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>Bitte Tabelle auswählen:</b>
<br>
<?php
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$q = $_POST['tablename'];
$column_passed = unserialize($_POST['column']); // content of array
$column is passed from getuser.php
foreach ($_POST["insertvalue"] as $key => $value) {
echo $value . "<br>";
$werte[] = "'$value'";
}
$sql="INSERT INTO $q ($column_passed) VALUES (" .
implode(", ", $werte) . ")"; // data entry
mysqli_query($db, $sql);
if (mysqli_affected_rows($db) > 0) {
echo "<h3 style='color:blue'>successful</h3>";
} else {
echo "<h3 style='color:red'>not
successful</h3>";
}
}
?>
</div>
</body>
</html>
enter code here
getuser.php:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<form id="formdatabase" name="formdatabase" action="javasql.php"
method="post">
<input type="hidden" name="sent" value="yes">
<?php
$q = strval($_GET['q']);
$con = mysqli_connect('localhost','root','','product');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM $q";
$result = mysqli_query($con,$sql);
$numcols = mysqli_num_fields($result); // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$data_type_array = array(
1=>'tinyint',
2=>'smallint',
3=>'int',
4=>'float',
5=>'double',
7=>'timestamp',
8=>'bigint',
9=>'mediumint',
10=>'date',
11=>'time',
12=>'datetime',
13=>'year',
16=>'bit',
252=>'text',
253=>'varchar',
254=>'char',
246=>'decimal'
);
$data_type_array = array_flip($data_type_array);
echo "<table>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th><th>" . 'Column names' . "</th>
<th>" . 'Values for db-entry' . "</th><th>" . 'Type' . "</th>";
echo "</tr>";
echo "<tr>";
$nr = 1;
for($x=0;$x<$numcols;$x++):?>
<td><?= $nr; ?></td>
<td><?= $field[$x]->name; ?></td>
<?= $column[] = $field[$x]->name; ?>
<td>
<?php
if ($field[$x]->name == 'Name') { // if-Beginn
?>
<select name="insertvalue[<?= $x; ?>]" id="insertvalue<?=
$x; ?>" size="1" onchange = "javascript:getSelectedRow()">
<?php
include("files/zugriff.inc.php");
$sql = "SELECT * FROM product_main ORDER BY Name";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optdrugs" value='. $row['Name'] . '>' .
$row['Name'] . '</option>';
echo '<br>';
}
?>
</select>
<?php
$name_option = "";
} else {
$name_option = "<input type='text' id='insertvalue" . $x . "'
name='insertvalue[" . $x . "]' size='50'>";
echo $name_option;
}
?>
</td>
<?php
$key = array_search($field[$x]->type, $data_type_array);
if($key !== false){
echo "<td>" . $key . "</td>";
}else{
echo "<td>" . $field[$x]->type . "</td>";
}
?>
<td><?= $field[$x]->type; ?></td>
<?= $nr = $nr + 1; ?>
</tr>
<?php endfor;
echo "</table>";
mysqli_close($con);
?>
<input type="hidden" name="tablename" value="<?= $q; ?>">
<input type="hidden" name="column" value="<?php echo htmlentities
(serialize($column)); ?>">
<input type="submit" value="Enter values" name="submit">
</form>
</body>
</html>
Since I need the master_id (= foreign key) in addition to the product-name for database entry, I would like to extend my script, so that the respective master_id is automatically sent to the input field in line 2, when a product-name is selected in line 3 ... without clicking a button. I tried to do this with javascript but it didn´t work. As far as I know, the solution would be to use AJAX but unfortunately, I am not very used to AJAX.
I would be more than happy, if someone could help me to solve this problem!
Why does this form not update the values that the items in my session? The session seems to keep track of the value fine, before the form tries to allow users to edit the value. Here's what I wrote out form submit:
<?php
if(isset($_POST['submit'])){
foreach($_POST['quantity'] as $key => $val) {
if($val==0) {
unset($_SESSION['Cart'][$key]);
}else{
$_SESSION['Cart'][$key]['quantity']=$val;
}
}
}
?>
And here's the form:
<?php
$sql="SELECT * FROM products where Product_ID IN (";
foreach($_SESSION['Cart'] as $id => $value){
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY Category ASC";
$query=mysql_query($sql);
$totalquantity=0;
while($row=mysql_fetch_array($query)){
$subtotal=$_SESSION['Cart'][$row['Product_ID']['quantity']]['quantity'];
$totalquantity+=$subtotal;
?>
<tr>
<td><?php echo $row['Name'] ?></td>
<td><input = type="text" name="Quantity [<?php echo $row['Product_ID'] ?>]" size="5" value="<?php echo $_SESSION['Cart'][$row['Product_ID']['quantity']]['quantity'] ?>"/> </td>
</tr>
<?php
}
?>
And of course, the submit button is just
<button type="Submit" name="Submit">Update selection</button>
It looks like it should all work out properly, but it doesn't update.
Submit should be "submit" most probably.Change it either in the input filed or in the $_POST["Submit"]