Editing data in multiple columns from front-end - php

I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..
<?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID = $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "<div style='overflow-x:auto;'><table border = '1'><font size = '2' face='verdana'>
<th>TND ID</th><th>Site name S1</th><th>Site name S2</th><th>Call sign S1</th><th>Idea ID S1</th><th>Call sign S2</th><th>Idea ID S2</th><th>Site to integrate</th><th>True azimuth (°) S1</th><th>True azimuth (°) S2</th><th>Pathlength (km)</th><th>TR Antenna diameter (m)</th><th>TR Antenna height (m) S1</th><th>TR Antenna height (m) S2</th><th>Channel ID S1</th><th>Channel ID S2</th><th>Design frequency S1</th><th>Design frequency S2</th><th>Polarization</th><th>Radio model</th><th>TX power (dBm)</th><th>Receive signal (dBm)</th><th>Planning Remarks</th><th>Projects Remarks Uploaded by</th><th>O & M Remarks Uploaded by</th><th>Planning Remarks Uploaded by</th><th>TXN NOC Remarks Uploaded by</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
echo "<tr><td>".$row["TND_ID"]."</td><td>".$row["Site_name_S1"]."</td><td>".$row["Site_name_S2"]."</td><td>".$row["Call_sign_S1"]."</td><td>".$row["Idea_ID_S1"]."</td><td>".$row["Call_sign_S2"]."</td><td>".$row["Idea_ID_S2"]."</td><td>".$row["Site_to_integrate"]."</td><td>".$row["True_azimuth_S1"]."</td><td>".$row["True_azimuth_S2"]."</td><td>".$row["Path_length_(km)"]."</td><td>".$row["TR_Antenna_diameter_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S2"]."</td><td>".$row["#1_Channel_ID_S1"]."</td><td>".$row["#1_Channel_ID_S2"]."</td><td>".$row["#1_Design_frequency_S1"]."</td><td>".$row["#1_Design_frequency_S2"]."</td><td>".$row["Polarization"]."</td><td>".$row["Radio_model_S1"]."</td><td>".$row["TX_power_(dBm)_S1"]."</td><td>".$row["Receive_signal_(dBm)_S1"]."</td><td>".$row["Planning_Remarks"]."</td><td>".$row["Projects_remarksupdated_user_name"]."</td><td>".$row["O_M_remarksupdated_user_name"]."</td><td>".$row["Planning_remarksupdated_user_name"]."</td><td>".$row["txn_noc_remarksupdated_user_name"]."</td></tr>";
}
echo "</table></div>";
$link->close();
?>

you can use this structure ,this can be used for editing 2 tables and multiple columns table a has columns (aid,a1,a2) table b has columns (bid,b1,b2) i know code looks little rough but just wrote it in 5 min to give you an idea
<?php
//this only executes when button is clicked
if (isset($_POST["submit"] && $_POST["submit"]!=""){
$counta=$_POST["aid"];
//loops through the posts inside here do your query with the set command
//like "update a set a1='$a1',a2='$a2" where aid ='$_POST["aid'][$i]"
for($i=0;$i<$count;$i++){
$a1[$i]=$_POST["a1"][$i];
$a2[$i]=$_POST["a2"][$i];
//your query here
}
$countb=$_POST["bid"];
//loops through the posts inside here do your query with the set command
//like "update b set b1='$b1',b2='$b2" where aid ='$_POST["bid'][$i]"
for($i=0;$i<$count;$i++){
$a1[$i]=$_POST["a1"][$i];
$a2[$i]=$_POST["a2"][$i];
}
//now the part before the button gets clicked
//do your query to select data from database
?>
<html>
<body>
//creating loop inside html
<?php
$a=0;
while($rowa = mysql_fetch_assoc($resulta){
?>
//getting the input data
<input type="checkbox" name="aid[]" value="<?php echo $row["aid"]; ?>>
<label>a1</label>
<input type="text" name="a1[]" value="<?php echo $row["a1"]; ?>>
<label>a2</label>
<input type="text" name="a2[]" value="<?php echo $row["a2"]; ?>>
//ending the loop
<?php
$a++;
}
//b works the same as a
$b=0;
while($rowb = mysql_fetch_assoc($resultb){
?>
<input type="checkbox" name="bid[]" value="<?php echo $row["bid"]; ?>>
<label>b1</label>
<input type="text" name="b1[]" value="<?php echo $row["b1"]; ?>>
<label>b2</label>
<input type="text" name="b2[]" value="<?php echo $row["b2"]; ?>>
<?php
$b++;
}
?>
<input type="submit" name="submit" value="submit">
</body>
</html>

You need use form instead of table while editing and pass the fetched values on input of form and write update query on form submit.
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
}
if(isset($_POST['submit']))
{
$query = "update details set Site_name_S1='$_POST['submit']',Site_name_S2='$_POST['Site_name_S2']',Call_sign_S1='$_POST['Call_sign_S1']',Idea_ID_S1='$_POST['Idea_ID_S1'] where TND_ID=$_POST['TND_ID']";
$res = mysql_query($query);
}
<form method="post">
<input type="text" name="id" value="<?php echo $row['TND_ID'] ;?>" >
<input type="text" name="Site_name_S1" value="<?php echo $row['Site_name_S1'] ;?>" >
<input type="text" name="Site_name_S2" value="<?php echo $row['Site_name_S2'] ;?>" >
<input type="text" name="Call_sign_S1" value="<?php echo $row['Call_sign_S1'] ;?>" >
<input type="text" name="Idea_ID_S1" value="<?php echo $row['Idea_ID_S1'] ;?>" >
<input type="submit" name="submit">
</form>
Just check the quotes while writing update query.

You can use Ajax
Just a fragment of code:
.............
<td><input type="text" row_id=".$some_row_num_from_table."
col-name=".$some_col_name_from_table." disabled class="some-val" value=".$some_from_base."></td>
.............
than little Ajax
$('.some-val').dblclick(function() {
$(this).attr('disabled', false);
});
$('.some-val').blur(function() {
$(this).attr('disabled', true);
var send_data = { 'row_id':$(this).attr('row_id'),
'col-name':$(this).attr('col-name'),
'myval':$(this).val()
};
$.ajax({
url:'your_url.php',
data:send_data,
method: 'post',
success: function(data){...}
});
});
your_url.php
if(isset($_POST['row_id'])){
$sql = "UPDATE mytablename SET `".$_POST['col-name']."` = ".$_POST['myval']." WHERE `row_id` = ".$_POST['row_id'];
$link->query($sql); // it s bad query without protect of sql injection JUST DEMO
}

Related

PHP (check or uncheck) a checkbox from Database

So I'm using a checkbox to insert data into MySql database.
When check it stores "finish"
When unchecked if stores "pending"
Now for an edit feature, I have to fetch and display the data from the database. I need the checkbox to be checked or unchecked if it is stored as finish or pending. Appreciate your help, thank you.
The code to fetch the data is shown below:
<?php
$query = ("SELECT * FROM ebook WHERE Eid='" . $Eid . "'");
$result = mysqli_query($con, $query);
$rows = mysqli_fetch_assoc($result);
?>
Displaying data and checkbox:
<html>
<input type="text" name="title" value="<?php echo $rows["Title"]; ?>">
<input class="tgl tgl-flip" id="chk" type="checkbox" name="chk" />
</html>
Put a condition echo inside the input.
<input class="tgl tgl-flip" id="chk" type="checkbox" name="chk" <?php if ($rows['status'] == 'finish') { echo "checked"; } ?>/>

How can i get multiple value from POST variable using same name

When user inputs text in 'ctext' field and press accept, I want to fill the value=" " field with user input, i achieved this but it fills all the value fields of same name in the page, how can i achieve it for different value of different ctext input? Anyone please give me solution with example, Many thanks
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
$i=0;
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here" value="<?php $ctext = false; if(isset($_POST['ctext'])){ $ctext = $_POST['ctext']; } echo $ctext[$i]; ?>"></input>
<input type="hidden" name="id" value="<?php $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
$i++;
endwhile;
endif;
endif;
?>
I hope I understand what you want. You want to access the ctext for each individual $pen when printing the corresponding form.
You just need to name your <input> with a unique name and then access that value when printing. A possible solution is this:
<input type="text" name="ctext[<?php echo $pen['id']; ?>]" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } echo $ctext; ?>"></input>
What does it do?
name="ctext[<?php echo $pen['id']; ?>]" ensures a unique name for each $pen. For a $pen with id 1 this will result in name="ctext[1]".
if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } uses $pen['id'] to look up the corresponding value in $_POST['ctext'].
By the way, when outputting user input you should always escape it, e.g. with htmlspecialchars. This will look like this: echo htmlspecialchars($ctext); That way malicious input like "><script>alert('Hello!')</script> won't execute the javascript.
Update: as requested a solution using session to store data:
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
session_start();
if (isset($_POST['ctext'])) {
$_SESSION['ctext'][$_POST['id']] = $_POST['ctext'];
}
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_SESSION['ctext'][$pen['id']])){ $ctext = $_SESSION['ctext'][$pen['id']]; } echo htmlspecialchars($ctext); ?>"></input>
<input type="hidden" name="id" value="<?php echo $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
endwhile;
endif;
endif;
Note: I removed the now unnecessary counter $i. The session handling is mainly done before the while loop (start a session and store POST data). During output the values from the session are used. The name of the input is not an array anymore.
Change name of an input to an array.like this . When you submit the form you will get these values as an array. Give it a try
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here"></input>
I guess your code is misleading you, your form is in while loop so once any of the ctext input is filled your variable $_POST['ctext'] is set on server side and according to your code it sets all the value of ctext once accept is pressed.
You can have different names as a solution or an array indexing in input field name=“ctext[]” to avoid this.

How can I prevent the ID from showing in the datalist element?

I am trying to utilize the datalist element. Everything is working with 1 little hitch. The selectable list is showing 2 columns, both the street_id and street columns. I need the street_id that will be submitted but dont want the street_id to show in the datalist.
<?php
require 'connect_mysqli.php';
$sql = "SELECT * FROM streets";
$result = mysqli_query($con, $sql) or die ("Error " . mysqli_error($con));
?>
<form action="test.php" name="test" method = "post">
<datalist id="street" name="streets">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['street_id']; ?>"><?php echo $row['street']; ?></option>
<?php
}
?>
</datalist>
<input type="text" name="street_val" id="test" autocomplete="off" list="street">
<input type="submit" value="Submit">
</form>
<?php
mysqli_close($con);
//test the output value
echo $_POST['street_val'];//
?>
You have coded a select list - which has separate values for display and returned values. In the datalist, you only need value="" for options and then it will only return that value. Also better to keep the server code and display code separate: i.e. populate or build the array in the PHP with your query, then in the HTML only display it.

PHP dynamic form will not INSERT into mySql

I'm working on a PHP dynamic form based on the tutorial found here:
http://blog.calendarscripts.info/dynamically-adding-input-form-fields-with-jquery/
Here is the table layout:
ID | depratecat | MinBalance | InterestRate | APY | suborder
inputted rows
ID is auto-increment.
The form fields for depratecat are visible in my code only for testing; normally the user would not be able to change this value. The value of depratecat would come from a POST value from a previous page and should be the same for all rows inputted or edited in this instance. For testing I'm declaring the value as 14.
My test page is here:
http://www.bentleg.com/fcsbadmin/dynamictest4.php
The problems:
The "Add row" script function does not work and the code won't insert new data thru form; nothing happens. No errors are shown in the Chrome console
Editing or deleting pre-existing rows seems to work.
Below is my complete test code minus the connection, Some print_r added to show the array.:
<?php
error_reporting(E_ALL);
// Connect to the DB
$link = myconnection stuff
$new_depratecat='14'; //for testing
// store in the DB
if(!empty($_POST['ok'])) {
//first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM tblRates_balance WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM tblRates_balance WHERE depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
// now edit them
while($rates = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE tblRates_balance SET
MinBalance='".$_POST['MinBalance'.$rates['id']]."',
InterestRate='".$_POST['InterestRate'.$rates['id']]."',
APY='".$_POST['APY'.$rates['id']]."',
suborder='".$_POST['suborder'.$rates['id']]."'
WHERE id='$rates[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a rate is actually changed)
// adding new
if($_POST['add_MinBalance']!= "") {
//echo ("OKAY");
$sql = "INSERT INTO tblRates_balance (depratecat, MinBalance, InterestRate, APY, suborder) VALUES ('$new_depratecat','".$_POST['add_MinBalance']."', '".$_POST['add_InterestRate']."', '".$_POST['add_APY']."','".$_POST['add_suborder']."' );";
$link->query($sql);
}
}
// select existing rates here
$sql="SELECT * FROM tblRates_balance where depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
?>
<html>
<head>
<title>Example of dynamically adding row and inserting into mySql with jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Example of dynamically adding row and inserting into mySql with jQuery </h1>
<form method="POST" id="newrate">
<div id="itemRows">
Minimum Balance: <input type="text" name="add_MinBalance" size="30" />
Interest Rate: <input type="text" name="add_InterestRate" />
APY: <input type="text" name="add_APY" />
Order: <input type="text" name="add_suborder" size="2"/>
<< Add data and click on "Save Changes" to insert into db. <br>
You can add a new row and make changes to existing rows all at one time and click on "Save Changes."
New entry row will appear above after saving.
<?php
// Next section does updating. let's assume you have the rate data from the DB in variable called $rates
while($rates = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$rates['id']?>">
<?php //echo $rates['id']; ?>
Minimum Balance: <input type="text" name="MinBalance<?=$rates['id']?>" value="<?=$rates['MinBalance']?>" />
Interest Rate: <input type="text" name="InterestRate<?=$rates['id']?>" value="<?=$rates['InterestRate']?>" />
APY: <input type="text" name="APY<?=$rates['id']?>" value="<?=$rates['APY']?>" />
Order: <input type="text" name="suborder<?=$rates['id']?>" value="<?=$rates['suborder']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$rates['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script language="Javascript" type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Minimum Balance:<input type="text" name="add_MinBalance[]" value="'+frm['add_MinBalance[]'].value+'">Interest Rate:<input type="text" name="add_InterestRate[]" value="'+ frm['add_InterestRate[]'].value +'">APY:<input type="text" name="add_APY[]" value="'+frm['add_APY[]'].value+'">Order:<input type="text" name="add_suborder[]"value="'+ frm['add_suborder[]'].value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+')(this);"></p>';
jQuery('#itemRows').append(row);
frm['add_MinBalance[]'].value = '';
frm['add_InterestRate[]'].value = '';
frm['add_APY[]'].value = '';
frm['add_suborder[]'].value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
//}
</script>
</body>
</html>
The inputs in the initial form have names add_depratecat, add_MinBalance, add_InterestRate, add_APY, and add_suborder. When you add new rows, they have the same names, but with [] appended. So the original row creates single inputs, the added rows create array inputs, but they have the same names, and they conflict.
You should use the array form for the original inputs as well:
<form method="POST" id="newrate">
<div id="itemRows">
Dep_rate_cat:<input type="text" name="add_depratecat[]" size="30"/>
Minimum Balance: <input type="text" name="add_MinBalance[]" size="30" />
Interest Rate: <input type="text" name="add_InterestRate[]" />
APY: <input type="text" name="add_APY[]" />
Order: <input type="text" name="add_suborder[]" size="2"/>
so that they're consistent with the added rows.
Initially you are not adding [] in the form fields,
change <input type="text" name="add_depratecat" size="30"> to <input type="text" name="add_depratecat[]" size="30">, do the same for other fields as well.
And in foreach where you are inserting data to database use array $depratecat[] instead of string $depratecat
if(isset($_POST['add_depratecat'])) {
$depratecat = $_POST['add_depratecat']; ........
For debugging purpose write echo '<pre>'; print_r($_POST); OR var_dump($_POST); Instead of
echo '<pre>',print_r($_POST,true),'</pre>';.

populating text fields from the sql using dropdown list Jquery

Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.

Categories