I have to post a value via "form post" and insert it into table, here is my code in both files:
<html>
<body>
<table>
<form enctype="multipart/form-data" action="<?php $_SERVER["DOCUMENT_ROOT"] ?> /contents/ad_posting_process_4.php" method="post">
<?php $cat_no = "101010"; ?>
<input type=hidden id="category" value=" <?php echo $cat_no; ?> ">
<tr> <td>Sub Category: </td><td> <input type=text id="sub_category" > </td>
<tr><td></td> <td><input type="submit" name="action" value="Post"></td></tr></tr>
</form>
</body></html>
here is ad_posting_4.php
<?php session_start();
include($_SERVER["DOCUMENT_ROOT"]."/includes/conn.php");
$category = mysql_real_escape_string($_POST['category']);
$sub_category = mysql_real_escape_string($_POST['sub_category']);
echo "category=". $category;
echo "sub_category=". $sub_category; ?>
No value sent through post.
where am I wrong?
Regards:
You need to use the name attribute:
<input type="text" name="category" />
<input type="text" name="sub_category" />
the input type needs to be enclosed in quotes ' and also have a name attribute, and not id.
<input type='hidden' name="category" value=" <?php echo $cat_no; ?> " />
<tr> <td>Sub Category: </td>
<td><input type='text' name="sub_category" > </td>
I recently did something very similar with my own website and received help from this community. On the HTML side I created a standard form and gave each input a "name." For example let's say you are trying to capture city and state:
<html>
<body>
<form>
<tr>
<td>State: </td><td> <input type="text" style="border:1px solid #000000" name="state" /></td>
<td>City</td><td><input type="text" style="border:1px solid #000000" name="city" /></td>
</tr>
</form>
</body>
</html>
Then set up a mySQL database with a column named "state" and one named "city". Next, use PHP to insert the data from the form into your database. I am new to PHP, but from what I understand using PDOs is more secure than using the old mysql commands.
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "name";
$dbuser = "user";
$dbpass = "pass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '[Insert Name of your table here]'";
$q = $conn->prepare($sql);
$q->execute();
$columns = $q->fetchAll(PDO::FETCH_COLUMN, 0);
$cols = array();
foreach ($_POST as $key=>$value)
{
// if a field is passed in that doesn't exist in the table, remove it. The name of the input that is removed will be echoed so you can debug. Remove echo if you go to production.
if (!in_array($key, $columns)) {
unset($_POST[$key]);
echo $key;
}
}
$cols = array_keys($_POST);
$sql = "INSERT INTO Facilities(". implode(", ", $cols) .") VALUES (:". implode(", :", $cols) .")";
$q = $conn->prepare($sql);
array_walk($_POST, "addColons");
$q->execute($_POST);
function addColons($value, &$key)
{
$key = ":{$key}";
}
This has been working out very well for me. Note that it can only match HTML form inputs with columns of the exact same name. In my case I wanted to create over 100 inputs so this was easier. If you are dealing with 5-10 it might be easier to just insert the specific variables manually.
Related
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>
I am try to inset multiple rows to new table fetched from other table, but problem is that only last single row is being inserted and no other now is getting insert, so please tell the issue where i am lacking
<?php
error_reporting(1);
session_start();
$s=$_SESSION['username'];
//connect database
$con=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("education",$con);
$date= date("Y/m/d");
//select all values from empInfo table
$data="SELECT * FROM student";
$val=mysql_query($data);
?>
<html>
<body>
<table>
</table>
<form action="submit.php" method="post" >
<table>
<tr>
<th>Teacher name</th>
<th>Date</th>
<th>Roll No</th>
<th>Student name</th>
<th>Father name</th>
<th>Addhaar No</th>
<th>Status(P)</th>
<th>Status(A)</th>
<th>Status(L)</th>
</tr>
<?php while($r=mysql_fetch_array($val))
{?>
<tr style="border:2px solid black;">
<td><input type="text" name="teacher" value="
<?php echo $s; ?>"></td>
<td><input type="text" name="date" value="
<?php echo $date; ?>"></td>
<td ><input name="roll_no" value="
<?php echo $r['roll_no']; ?>">
</td>
<td><input name="student_name" value="
<?php echo $r['student_name'] ?>">
</td>
<td><input name="father_name" value="
<?php echo $r['father_name'] ?>">
</td>
<td>
<input name="addhaar_no" value="
<?php echo $r['addhaar_no'] ?>">
</td>
<td>
<input type="checkbox" value="present" name="status"> Present
</td>
<td>
<input type="checkbox" name="status" value="absent">Absent
</td>
<td>
<input type="checkbox" name="status" value="leave">Leave
</td>
</tr>
</table>
<?
}
?>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
submit.php -
<?php
error_reporting(1);
$con=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("education",$con);
//get data from html form
$roll_no=$_POST['roll_no'];
$student_name=$_POST['student_name'];
$father_name=$_POST['father_name'];
$addhaar_no=$_POST['addhaar_no'];
$status=$_POST['status'];
//Insert values in empInfo table with column name
$query="INSERT INTO attandance
VALUES ('', '$roll_no','$student_name','$father_name','$addhaar_no','$status'),
VALUES ('', '$roll_no','$student_name','$father_name','$addhaar_no','$status')";
echo $query;
die();
mysql_query($query);
?>
page
You need to have unique name for each fields. What you can do is have a counter in loop and add it the names of the fields to make it unique.
Sample:
$ctr = 0;
while($r=mysql_fetch_array($val)){
echo "<input type="text" name='teacher_".$ctr."'>";
$ctr++;
}
Or make the names array, and loop through the values in saving the data.
while($r=mysql_fetch_array($val)){
echo "<input type="text" name='teacher[]'>";
}
I think you should study PHP a bit more... As i can see in your code, you haven't understood fundamentals of PHP.
1: Normally, you won't mix up HTML and PHP like you did in your first code. Its just confusing and really annoying to read the code later.
2: When you post your form, for example the variable $_POST['student_name']; will just contain the value of the last row (your problem). So, why? Because you can't assign more than one value to a variable. Or at least, not the way you tried it. Array would be a good keywoard for this problem.
3: Please check your SQL syntax... Thats why i'm saying you haven't understand fundamentals... http://www.w3schools.com/sql/sql_insert.asp
Why you're repeating your values? You think the second time the variables will contain the values of the next row? Thats just false. A Variable contains everytime the same value, as long as you don't assign a new value to it.
4: mysql is depracted. Use mysqli or PDO instead.
My tip: You need to have unique input names. Just take a look at PHP, how for/while loops work, study a bit more and try it again. It's not difficult to solve, but i think you'll learn a lot more if we don't give you the direct solution.
Now mysql is depracted. So, you can use mysqli or PDO instead.
I can use now PDO. Please follow bellow code carefully:
<?php
$user = 'root';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=education', $user, $pass);
try {
$select = $dbh->query('SELECT * from student');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
<html>
<body>
<form action="submit.php" method="post" >
<table>
<tr>
<th>Teacher name</th>
<th>Date</th>
<th>Roll No</th>
<th>Student name</th>
<th>Father name</th>
<th>Addhaar No</th>
<th>Status(P)</th>
<th>Status(A)</th>
<th>Status(L)</th>
</tr>
<?php
foreach($select as $val) {
?>
<tr style="border:2px solid black;">
<td><input type="text" name="teacher" value="<?php echo $s; ?>"></td>
<td><input type="text" name="date" value="<?php echo $date; ?>"></td>
<td><input name="roll_no" value="<?php echo $r['roll_no']; ?>"></td>
<td><input name="student_name" value="<?php echo $r['student_name'] ?>"></td>
<td><input name="father_name" value="<?php echo $r['father_name'] ?>"></td>
<td><input name="addhaar_no" value="<?php echo $r['addhaar_no'] ?>"></td>
<td><input type="checkbox" value="present" name="status"> Present</td>
<td><input type="checkbox" name="status" value="absent">Absent</td>
<td><input type="checkbox" name="status" value="leave">Leave</td>
</tr>
<?php
}
?>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
For submit.php code bellow
<?php
$user = 'root';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=education', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO attandance (roll_no, student_name, father_name, addhaar_no, status) VALUES (?, ?, ?, ?, ?)");
$stmt->bindParam(1, $roll_no);
$stmt->bindParam(2, $student_name);
$stmt->bindParam(2, $father_name);
$stmt->bindParam(2, $addhaar_no);
$stmt->bindParam(2, $status);
//if you insert 2 time then
for($x=0; $x<2; $x++) {
$roll_no = $_POST['roll_no'];
$student_name = $_POST['student_name'];
$father_name = $_POST['father_name'];
$addhaar_no = $_POST['addhaar_no'];
$status = $_POST['status'];
$stmt->execute();
}
?>
I have tried out some code for dynamic insertion of data using array but the issue am facing is in a single row same data is been inserted and even if check box are left un-checked data value is inserted ignoring the checked value inside a "while-loop"..I am new to this array concept please help me out.
.php
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<div class="col-md-12">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
echo '
<tr>
<td align="left">' . $row['via'] . '<input type="hidden" name="type[]" value="' . $row['via'] . '"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>';
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
DB.php
<?php
session_start();
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(isset($_POST["submit"]) && isset($_POST["type"])){
//receiving post parameters
$types = $_POST["type"];
if(sizeof($types) > 0 ){
foreach($types as $type){
// create a new user profile
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$type."','".$type."','".$type."','".$type."', NOW())";
if(mysqli_query($con,$sql)){
header('Location: macro_ppl.php');
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}
}
}
?>
First of all checkbox values will not be present in the post if they are not set.
Second of all you add many results cause you call insert sql in the loop.
You can use:
var_dump($_POST['type']);
so you will see how the structure actually look like.
There are many ways to make this work one could be:
//setting the variables first
$ppl = 0;
$macro = 0;
$micro = 0;
$nano = 0;
//then run the loop to set them
foreach($types as $type){
if(in_array($type,['ppl','macro','micro','nano'])) //just to be sure nobody pass something else so we will not override other variables
$$type = 1;
}
//then write the query
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$ppl."','".$macro."','".$micro."','".$nano."', NOW())";
You are doing it wrong, just submit a form with data array
Form
<form id="form" name ="form" method = "POST" action="someForm.php">
<tr>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
</form>
someForm.php
if (isset($_POST['type'])) {
foreach ($_POST['type'] as $myType) {
echo $myType
}
}
Your Form
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
?>
<tr>
<td align="left"><?php echo $row['via'] ?><input type="hidden" name="type[]" value="<?php echo $row['via'] ?>"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
<?php
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
In PHP file
if (isset($_POST['submit'])) {
if(isset($_POST['type'])) {
foreach ($_POST['type'] as $value) {
echo $value;
/*add this in the query, this will return the value of checkbox which are checked*/
}
}
}
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.
I wasn't sure what else to call the title...I have a PHP page that accesses a certain MySQL database, pulls the values from the table, and places them in an HTML form (POST method - PHP_SELF). The user can then view the values, alter them as they wish, and submit them. The page then takes those values and updates the MySQL database. Everything works perfectly except that when the user submits and the page goes to show the new updated variables, it still shows the old values. The user is forced refresh the page before the new variables show up. I thought that PHP was perhaps not deleting the variables, so I unset all stored variables after the script was over and it's still not working. I ever tried putting a sleep timer before the script started, and that didn't work either. I'd appreciate any suggestions. Here is my script just for reference:
<html>
<body>
<?php
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
?>
</body>
</html>
You are displaying the data from the database before you update it.
It is normally good practice to do all your database connectivity at the top of the page, then display the results.
In your code (even if a user has submitted an update), you query the data, pull it from database and display it, then run the update with what the user submitted.
Changing your code to this should do the trick (Do read the note below though):
<html>
<body>
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
</body>
</html>
Bad note - your code is wide open to injection attacks. You are using form data with no verification. That's a big red flag. Secondly, you are using deprecated mysql_* functions. Your code should be using mysqli_* functions or better yet move to PDO. It is much safer and you will be able to do a lot more with it.
Edit 2: The page IS being updated after the user submits the form, but the page you display to the user is querying the database before you update it - and using that to display the page to the user.