fetch row data and update textarea to insert in mysql - php

I have two column name varchar and area text
name area
abc 12a
dfg test
Now I want to update each of them from my page where I input some text to the textarea fetched from tow rows.
<?
if(isset($_POST['submit'])) {
$i = 0;
foreach($_POST['txt'] as $textarea) {
#$val[$i] = $val[$i].$textarea;
$i++;
}
foreach($val as $value){
$q= mysql_query("UPDATE table_name SET name = '$value' WHERE `area` = '??'");
echo "Success"; }
$sql="select * from table_name";
$res=mysql_query($sql);
?>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<table border="1">
<thead>
<tr>
<th>NAME</th>
<th>AREA</th>
</tr>
<?php while($row=mysql_fetch_assoc($res))
{
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><textarea rows="4" cols="40" name="txt[]"><?php echo $row['area']; ?> </textarea><br/>
</td>
</tr>
<tr>
</tr>
<?php } ?>
<tr>
<td><input type="submit" name="submit" id="submit" value="Update" /></td>
</tr>
</table>
</form>
I am getting the name but could not update/insert it in area for that name. How do I accomplish this?

the most easy fix is to take a hidden input field and pass the $row['name']
<input type="hidden" name="name[]" value="<?php echo $row['name'];?>"/>
then
if(isset($_POST['submit'])) {
$area=$_POST['txt'];
$name=$_POST['name'];
$count=count($area);
for($i=0; $i<$count; $i++)
{
if(mysql_query("UPDATE table_name SET area = '".$area[$i]."' WHERE `name` = '".$name[$i]."'"))
{
NB:-if u have a id column then take hidden input field with $row['id'] and do the same

You can embed actual keys in PHP's array-naming hack:
<textarea name="txt[foo]">...</textarea>
<textarea name="txt[bar]">...</textarea>
Which allows you to directly associate a particular form field with the value it represents in the database. In your case:
while($row = fetch_from_db()) {
output: <texarea name="txt[$row[id]]">$row[area]</textarea>
}
And then, after submitting:
foreach($_POST['txt'] as $key => $value) {
update database : UPDATE ... SET area=value WHERE id=$key
}
Note that your code is vulnerable to sql injection attacks.

Related

Display an HTML table with data from a PhP form

I need to display an HTML table with the data that i get from a PhP form. I did a thing like this but It doesn't work properly. It shows the data row on top of the title of the columns. Here's the code:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Nome: <input type="text" name="nome">
Ragione sociale: <input type="text" name="rag">
Indirizzo: <input type="text" name="ind">
Partita IVA: <input type="text" name="iva">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['nome']);
$rag = htmlspecialchars($_REQUEST['rag']);
$ind = htmlspecialchars($_REQUEST['ind']);
$iva = htmlspecialchars($_REQUEST['iva']);
}
?>
<table>
<tbody>
<tr>
<?php
$a = array($name,$rag,$ind,$iva);
for ($i=0; $i<count($a); $i++){
print_r($a[$i]);
echo " ";
}
?>
</tr>
<tr>
<td>|Nome|</td>
<td>Ragione Sociale|</td>
<td>Indirizzo|</td>
<td>Partita IVA|</td>
</tr>
</tbody>
</table>
</body>
</html>
You print your data in the first row, without outputting any <td> for your data. Then in the second row you print your titles/headers. Change your table like so, see if that's what you want:
<table>
<thead>
<tr>
<th>|Nome|</th>
<th>Ragione Sociale|</th>
<th>Indirizzo|</th>
<th>Partita IVA|</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$a = array($name,$rag,$ind,$iva);
for ($i=0; $i<count($a); $i++){
echo "<td>";
echo $a[$i];
echo "</td>";
}
?>
</tr>
</tbody>
</table>
More on tables: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
Edit: I'd also suggest to place your table inside the if ($_SERVER["REQUEST_METHOD"] == "POST") { so it only gets printed after you submitted the form

Editing php / mysql table but does not update table

I am trying to edit a mysql table, however when i submit the form, the table does not get updated, and the previous value remains the same. I am not getting any errors at all either...
i have tried running the update query directly in the database, and it works...can someone have a look at my code and see if they can help?
below is my code:
edit.php
<?php include('server.php') ?>
<?php
if(isset($_POST['update']))
{
$responseid = $_POST['responseid'];
$response=$_POST['response'];
{
//updating the table
$result = $conn->prepare ("UPDATE response SET response= '$response' WHERE responseid=$responseid");
header("Location: results.php");
}
}
?>
<?php
//getting id from url
$responseid = $_GET['id'];
//selecting data associated with this particular id
$result = $conn->prepare("SELECT * FROM response WHERE responseid=$responseid");
while ($response = $result->fetch())
{
$response = $res['response'];
$student_id = $res['student_id'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>response</td>
<td><input type='text' name='date' value="<?php echo $response;?>"</td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
results.php
<div id="table1" class="table1">
<?php
if(isset($_POST["submit"]))
{
$searchTerm=$_POST['search'];
$stmt = $conn->prepare(" SELECT question.description AS question, answer.description AS answer, discipline.name AS name, response.responseid AS responseid, response.response AS response, response.student_id AS student_id, response.Date_Time AS Date
FROM response
INNER JOIN answer ON response.question_id = answer.answerid
INNER JOIN question ON response.question_id = question.qid
INNER JOIN discipline ON response.discipline_id = discipline.disciplineid WHERE Date_Time LIKE :searchTerm");
$stmt->bindValue(':searchTerm','%'.$searchTerm.'%');
$stmt->execute();
$result=0;
/*
The above code is a query which selects attributes according to the search term
*/
echo "<table> <tr><th>Discipline</th><th>Question</th><th>Student ID</th><th>Response</th><th>Date & Time</th><th>Answer</th><th>Final Marks</th></tr>";
while ($response = $stmt->fetch()) /* This is a While loop which iterates each row */
{
echo " <tr><td>".$response["name"]."</td><td>".$response["question"]."</td><td>".$response["student_id"]."</td><td>".$response["response"]."</td><td>".$response["Date"]."</td><td><input type='text' name='date' value=". $response["answer"]."></td><td>Edit</td></tr> ";
$result++;
}
} /* This bit of code closes the connection with the database */
?>
</div>
please click this link to see my database
Updating using prepared statements (similar to the way your doing it in the select in the second listing)...
//updating the table
$result = $conn->prepare ("UPDATE response
SET response= :response
WHERE responseid=:responseid");
$result->bindValue(':response',$response);
$result->bindValue(':responseid', $responseid);
$result->execute();
Also check the contents of $_POST as I think you have the field names wrong (think they were 'date' and 'id')...
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>response</td>
<td><input type='text' name='response' value="<?php echo $response;?>"</td>
</tr>
<tr>
<td><input type="hidden" name="responseid" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>

how do fetching and then inserting from multi check boxes in php

I am going to fetching table values in a html table along checkbox in each row and then inserting values in another database table from multi check boxes in php.
Only the values of checked boxes should be submitted to that table.
db name "laboratory":
test: fetching values.
package: inserting table.
view
Status
Active
Inactive
<?php
$conn=mysqli_connect("localhost","root","","laboratory") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
Please try to follow this code and implement in your program . Hope that this will cooperate you much
if(isset($_POST['name'])){
$name = $_POST['name'];
$status = $_POST['status'];
if(empty($name) || empty($status)){
echo "Field Must Not be empty";
} else{
$conn=new mysqli("localhost","root","","test");
if($conn){
$query = "SELECT * FROM userdata limit 5";
$stmt = $conn->query($query);
$val = '<form action="" method=""> ';
$val .= '<table> ';
if ($stmt) { ?>
<form action="" method="post">
<table>
<?php while ($result=$stmt->fetch_assoc()) { ?>
<tr>
<td><?php echo $result['post']; ?></td>
<td><input value="<?php echo $result['post']; ?>" type="checkbox" name="check[]" /></td>
</tr>
<?php } ?>
<tr>
<td>Actual Price </td>
<td>Discount</td>
<td>Final Price</td>
</tr>
<tr>
<td><input type="text" name="actual"/></td>
<td><input type="text" name="discount"/></td>
<td><input type="text" name="final"/></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" id="" cols="30" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Cancel" /></td>
</tr>
</table>
</form>
<?php }} }}?>
<?php
if(isset($_POST)){
echo "<pre>";
print_r($_POST);
echo "<pre>";
}
?>`enter code here`
First of all you have to decide that what are you using either mysqli or mysql, if you are using mysqli then you have to improve your code
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
and when you want to insert the checked data will be inserted in package table. If package table in another database then you have to give us the full detail i mean tell us the database name of package table.

Blank screen when updating data in php table

I have been working on a project and i am at the final stages of the project. My problem is whenever i try to update data in my database table into returns a blank screen with no error messages. Please find the php script and html form (the form responsible for updating the database table) below, i have divided it into about four sections:
Thanks in advance
Update Form:
<a name="inventoryEditForm" id="inventoryEditForm"></a>
<h3>↓Add New Question Form↓</h3>
<form action="inventory_edit.php" enctype="multipart/from-data" name="myForm" id="myForm" method="post">
<table width="80%" border="0" cellspacing="3" cellpadding="7">
<tr>
<td width="20%"> </td>
<td width="80%"> </td>
</tr>
<tr>
<td>Question</td>
<td><textarea rows="" name="question" cols=""><?php echo $question; ?></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Venue</td>
<td><input type="text" name="venue" maxlength="50" value="<?php echo $venue; ?>"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="questiondate" value="<?php echo $date; ?>"></td>
</tr>
</table>
<br>
<input name="thisID" type="hidden" value="<?php echo $targetID; ?>"/>
<input type="submit" name="submit" value="Update Question">
<input type="reset" name="clear" value="Clear Form">
</form>
PHP Script:
<?php
//Error reporting due to long script
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
error_reporting(E_PARSE);
//Update question table
If (isset($_POST['question'])) {
$id = mysqli_real_escape_string($link, $_POST['thisID']);
$question = mysqli_real_escape_string($link, $_POST['question']);
$venue = mysqli_real_escape_string($link, $_POST['venue']);
$date = mysqli_real_escape_string($link, $_POST['questiondate']);
//Update question in the table
$sql = mysqli_query($link, "UPDATE DebateQuestion SET question='$question',venue='$venue',date='$date' WHERE qQuestionNo='$id'LIMIT 1") or die(mysql_error());
header("location: inventory.php");
exit();
}
?>
<?php
error_reporting(E_PARSE);
//Gather this questions full information and insert automatically into the edit form
if (isset($_GET['qid'])) {
$targetID = $_GET['qid'];
$sql = mysqli_query($link, "SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1") or die(mysql_error());
$questionCount = mysqli_num_rows($sql); // count the output amount
if ($questionCount > 0) {
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
$id = $row["qQuestionNo"];
$question = $row["qQuestion"];
$venue = $row["qDebateVenue"];
$date = strftime("%b %d, %Y", strtotime($row["qDate"]));
}
} else {
echo "Oops, no questions like that exists. Check <a href='inventory.php'>inventory</a>again";
exit();
}
}
?>
In your update query you have the data column without using ` back ticks , date is also a mysql's function try to wrap up your column names with back ticks if you are not sure whether they conflict with mysql's reserved keywords
$sql = mysqli_query($link,"UPDATE DebateQuestion SET
`question`='$question',`venue`='$venue',`date`='$date'
WHERE qQuestionNo='$id'LIMIT 1")
"SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1"
Here is qQuestionNo column a string type?if not remove quotes around $targetID.
Note : I have not tested the code - just read it on screen.
I've never seen an IF statement capitalized before :
If (isset($_POST['question'])) {
I'd guess this makes a difference however.
There's lots of other weird things going on in your files, but none that should give you white screen. Try lowercase 'I' in your if statement first.
ALSO - re: the UPDATE statement, you are missing a space between the $id and the LIMIT :
**qQuestionNo='$id'LIMIT 1**

All products being displayed instead of only one

i edited my code as below but the issue is that each time i click on the edit link, all of the products are being displayed instead of only the one beside which i clicked the edit link.
note: Sorry for posting another question relating to my other one. I could not add any more comments.
<?php
include_once("db_connect.php");
if(isset($_POST['update']))
{
$prod_id = $_POST['prod_id'];
$prod_name=$_POST['prod_name'];
$prod_brand=$_POST['prod_brand'];
$prod_price=$_POST['prod_price'];
// checking empty field
if(empty($prod_price))
{
//if name field is empty
if(empty($prod_price))
{
echo "<font color='red'>Price field is empty.</font><br/>";
}
}
else
{
//updating the table
//$result=mysql_query("UPDATE tblretprod SET prod_price='$prod_price' WHERE prod_id=$prod_id");
$result=mysql_query("UPDATE tblretprod SET prod_price='".$prod_price."' WHERE prod_id='".$prod_id."';");
//redirectig to the display page. In our case, it is index.php
header("Location: update.php");
}
}
?>
<?php
$prod_id = $_GET['prod_id'];
$result=mysql_query("SELECT a.prod_name, a.prod_brand, b.prod_price FROM tblproduct a, tblretprod b where a.prod_id = b.prod_id") or die(mysql_error());
?>
<html>
<title>Edit Product</title>
<body>
Home
<br/><br/>
<form name="edit" method="post" action="updprod.php">
<table border="0">
<?php
while($res=mysql_fetch_array($result))
{
$prod_name = $res['prod_name'];
$prod_brand = $res['prod_brand'];
$prod_price = $res['prod_price'];
?>
<tr>
<td>Product Name</td>
<td>
<input type="text" disabled="disabled" name="prod_name" value = "<?php echo $prod_name;?>"> </td>
</tr>
<tr>
<td>Brand</td>
<td>
<input type="text" disabled="disabled" name="prod_brand" value = "<?php echo $prod_brand;?>"> </td>
</tr>
<tr>
<td>Product Price</td>
<td>
<input type="text" name="prod_price" value = "<?php echo $prod_price;?>">
<input type="hidden" name="prod_id" value = "<?php echo $_GET['prod_id'];?>">
</td>
</tr>
<?php } ?>
<tr>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Add in your select query in WHERE clause:
AND a.prod_id = ".$prod_id."
query:
"SELECT
a.prod_name,
a.prod_brand,
b.prod_price
FROM
tblproduct a, tblretprod b
where
a.prod_id = b.prod_id
AND a.prod_id = ".intval($prod_id).""
To make the query safer against SQL Injection i've added intval function like Kickstart well pointed out.

Categories