how to access form data using post in loop - php

I am trying to access data from form field which is dynamically created and store it to db.I don't know how to do that.I tried many ways but didn't worked.please help me.Thank you for reading this.....
<html lang="en">
<head>
<title>toggle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'attendance';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from student', $link);
if(isset($_POST["submit"]))
{
$name=$_POST['student'];
echo $name;
}
?>
<script type="text/javascript">
function change(obj) {
var tr=obj.parentNode; // this may change depending on the html used
tr.style.backgroundColor=(obj.checked)? 'green' : 'red';
}
</script>
<style type="text/css">
.nochange, tr {background-color:green;}
</style>
</head>
<body onLoad="change(this)">
Report Attendance
<table border="1" cellspacing="2" cellpadding="5" summary="">
<form name="myform" action="" method="post">
<?php while ($row = mysql_fetch_assoc($res)){
echo "<tr class='nochange'><td><input type='checkbox' name='student' value='" . $row['stu_id'] . "' checked style='background:#f00;' onClick='change(this);'>" . $row['stu_name'] . "<br />"."</td></tr>";
}?>
<input type="submit" name="submit" value="submit"/>
</form>
</table>
</body>
</html>

Make checkbox an array
<html lang="en">
<head>
<title>toggle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'attendance';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from student', $link);
if(isset($_POST["submit"]))
{
//Here goes array
for($i=0;$i<count($_POST['student']);$i++)
{
$name=$_POST['student'][$i];
echo $name;
}
}
?>
<script type="text/javascript">
function change(obj) {
var tr=obj.parentNode; // this may change depending on the html used
tr.style.backgroundColor=(obj.checked)? 'green' : 'red';
}
</script>
<style type="text/css">
.nochange, tr {background-color:green;}
</style>
</head>
<body onLoad="change(this)">
Report Attendance
<table border="1" cellspacing="2" cellpadding="5" summary="">
<form name="myform" action="" method="post">
<?php while ($row = mysql_fetch_assoc($res)){
echo "<tr class='nochange'><td><input type='checkbox' name='student[]' value='" . $row['stu_id'] . "' checked style='background:#f00;' onClick='change(this);'>" . $row['stu_name'] . "<br />"."</td></tr>";
}?>
<input type="submit" name="submit" value="submit"/>
</form>
</table>
</body>
</html>

You need to create array of checkboxes and then loop over it in $_POST.
HTML:
<?php while ($row = mysql_fetch_assoc($res)){
echo "<tr class='nochange'><td><input type='checkbox' name='student[".$row['stu_id']>"]' value='" . $row['stu_id'] . "' checked style='background:#f00;' onClick='change(this);'>" . $row['stu_name'] . "<br />"."</td></tr>";
}?>
In PHP posted file,
if (! empty($_POST['student'])) {
foreach ($_POST['student'] as $stu_id -> $student) {
echo '<br/> Student Id: ' . $stu_id;
}
}
Also, never user mysql_* functions are they are deprecated and will be removed in PHP's further releases.

Related

PHP / MySQLi drop-down empty

Im just starting out with MySQL and PHP. Im trying to create a drop-down menu, to pick a certain competence within a company.
Later on, i want a total of 3 dropdowns, so that i can combine user/competence/avaliable date, to display sort of a calendar to show which users are avaliable a certain date, with information about their competence.
However, the code below just returns this:
Result
The same query to the database returns 12 values.
What am i doing wrong? I get no errors, just a blank drop-down.
<!DOCTYPE html>
<html>
<head>
<title> Greetings. </title>
<meta charset="UTF-8"/>
</head>
<body>
<?php
session_start();
$con = mysqli_connect("127.0.0.1", "root", "", "service");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
echo "<br />";
$query_kompetens = "SELECT kompetens FROM kompetens";
$kompetens = mysqli_query($con, $query_kompetens);
echo "<select name='Kompetens'>";
echo "<option size =30 ></option>";
while ($row = mysqli_fetch_array($kompetens)) {
echo "<option value='" . $row['Kompetens'] . "'>" . $row['Kompetens'] . "</option>";
}
echo "</select>";
;
?>
</body>
</html>
Try This code, actually you used $row['Kompetens'] instead of $row['kompetens'].
<!DOCTYPE html>
<html>
<head>
<title> Greetings. </title>
<meta charset="UTF-8"/>
</head>
<body>
<?php
session_start();
$con = mysqli_connect("127.0.0.1", "root", "", "servicedesk");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
echo "<br />";
$query_kompetens = "SELECT kompetens FROM kompetens";
$kompetens = mysqli_query($con, $query_kompetens);
echo "<select name='Kompetens'>";
echo "<option size =30 ></option>";
while ($row = mysqli_fetch_array($kompetens)) {
echo "<option value='" . $row['kompetens'] . "'>" . $row['kompetens'] . "</option>";
}
echo "</select>";
;
?>
</body>
</html>

how to update the data that was displayed from database using PHP?

I had inserted the data from html and it is stored in mysql database, and the data is retrieved from database to html,now I had done how to delete the data that are displayed in html,my task is how to update the displayed.And my deleted code is:
Below is my HTML code:
<html>
<head>
<title>STUDENT_DATA</title>
</head>
<body>
<form action="tab.php" method="post" >
<center>
sname: <input type="text" name="sname" required><br></br>
sno:<input type="text" name="sno"><br></br>
marks:<input type="text" name="marks"><br></br>
class:<input type="text" name="class"><br></br>
phno:<input type="text" name="phno" onkeypress='return event.charCode >
= 48 && event.charCode <= 57'><br></br>
DOB:<input type="date" placeholder="DD-MM-YYYY"
required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}"
name="DOB"/><br></br>
<button>submit</button></br>
</center>
</form>
</body>
</html>
Below is my PHP code for displaying the data:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "student",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
$sql = "SELECT * FROM hello1 ";
$result = mysql_query($sql) or die(mysql_error());
?>
<table border="2" style= " margin: 0 auto;" id="myTable">
<thead>
<tr>
<th>sname</th>
<th>sno</th>
<th>marks</th>
<th>class</th>
<th>phno</th>
<th>DOB</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['sname'] . "</td>";
echo "<td>" . $row['sno'] . "</td>";
echo "<td>" . $row['marks'] . "</td>";
echo "<td>" . $row['class'] . "</td>";
echo "<td>" . $row['phno'] . "</td>";
echo "<td>" . $row['DOB'] . "</td>";
echo "<td><a href='delete.php?did=".$row['sname']."'>Delete</a></td>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
Below is my PHP code for deleting:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "student",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
?>
<?php
if(isset($_GET['did'])) {
$delete_id = $_GET['did'];
$sql = mysql_query("DELETE FROM hello1 WHERE sname = '".$delete_id."'");
if($sql) {
echo "<br/><br/><span>deleted successfully...!!</span>";
}
else
{
echo "ERROR";
}
}
?>
Below is what I have tried in update.php
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection) { die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db) { die("Database Selection Failed" . mysql_error()); } ?>
<?php if(isset($_GET['did']))
{
$update_id = $_GET['did']; $sql = mysql_query("UPDATE FROM venu WHERE id = '".$update_id."'");
if($sql) {
echo "<br/><br/><span>updated successfully...!!</span>";
} else {
echo "ERROR";
}
} ?>

UPDATE single column in database: PHP&MYSQL

So, I am trying to figure out how do this this and it boggling me. THIS WILL NOT BE USED ONLINE LIVE SO SQL INJECTION I DONT' CARE ABOUT. What am I doing wrong/right?
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_GET['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = $id";
$comment1 = mysql_query($sql);
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
echo $sql;
The main problem is with the statement itself, the connection is fine. I am trying to read $comment, and then update that into a MYSQL table and then have it read back in a different file.
EDIT: Mark up for the form I'm taking $comment from.
<!DOCTYPE html>
<html lang="en">
<LINK href="stylesheet.css" rel="stylesheet" type="text/css">
<script src ="js/validateform.js"></script>
<head>
<meta charset="UTF-8">
<title>UniHelp Home</title>
</head>
<body>
<div id="headeruni">
<h1>Welcome <?php echo $_GET["name"]; ?> to UniHelp!</h1>
</div>
<div id ="infouni">
<h3>Welcome to UniHelp. The social Network getting you connected to other people all over the University for any help you require!</h3>
</div>
<div id ="nameandemail">
<form action="formsend.php" method="post">
First name: <br> <input type="text" name="name"><br>
Email: <br> <input type="text" name="email"><br>
Comment: <br> <input type="text" name="message"><br>
<input type="submit" name="submit">
</form>`enter code here`
</div>
<div id="grabphpdiv">
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$result = mysql_query("SELECT * FROM Dbsaved", $db);
if (!$result) {
die ("Database query failed: " . mysql_error());
}
$comment = $_POST['$comment'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo 'Comment: <br>
<input type=text name=comment><br>
<a href=addcomment.php?id=' . $row[0]. '&comment='. $row['$comment'].'>Comment</a>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
</div>
</body>
<div id="footer">Copyright &copy James Taylor 2016</div>
</html>
I just ran this code:
$comment = "Hello World!";
$id = 1;
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = {$id}";
echo $sql;
and saw:
UPDATE Dbsaved SET comment = 'Hello World!' WHERE id = 1
which is a correct SQL statement, so if it is not working, you might want to play with SQL directly to get something working. Hope that helps!
SOLUTION:
$comment = $_GET['$comment'];
$id = $_GET['$id'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo $row[4] . "";
echo "<br>";
echo 'Comment: <br>
<form action="addcomment.php?id=' . $row[0]. '" method="post">
<input type=text name=comment><br>
<input type=submit name="submit">
</form>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
and:
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_POST['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '$comment' WHERE id = $id ";
$comment1 = mysql_query($sql);
echo $sql;
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
else {
header("location: UniHelpindex.php");
}
It was to do with mainly needing to get the id which was used in $row[0]' in the form created in the while loop. And actually using the correct syntax for the update Dbsaved... bit.

Why will it not update to the database?

This is my code :
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="blah"; // Mysql password
$db_name="test"; // Database name
$tbl_name="SubCategories"; // Table name
$con=mysqli_connect("$host", "$username", "$password", "$db_name");
if (mysqli_connect_errno()) // Check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="untitled.php" method="post"><!-- untitled.php -->
<?php
//print_r($_POST); //print all checked elements
//echo "<br>".$email, $_POST["update"][$i];
//mysql_real_escape_string ($route )
if(isset($_POST['submit'])) {
foreach ($_POST["holder"] as $i=>$email) {
$y=$email;
$h=$_POST["update"][$i];
$res2=mysqli_query("UPDATE ".$tbl_name." SET subCat2 = '" . $y . "' WHERE id =". $h,$con);
if ($res2){
}
else{
echo "<h1>NOT WORKING!</h1>";
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
}
$result = mysqli_query($con,"SELECT * FROM $tbl_name");
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo '<input type="text" name="holder[]" id="checkbox-1" class="custom" value=" ' . $row['subCat2'] . '"/>';
echo '<input type="hidden" name="update[]" id="checkbox-1" class="custom" value=" ' . $row['subCatNum'] . '"/>';
echo "<br>";
}
?>
</br>
<input type="submit" name="submit">
</form>
</body>
</html>
I can't update the table in my database. I am able to extract the variables properly and echo them, however it does not work.
I have gotten the following error in the past 'no database selected'.
I think that you forgot to select the database. Try to put this after your connection:
if (!mysqli_select_db($con, $db_name)) {
die("Uh oh, couldn't select database $db_name");
}
If this happens, double check the name, permissions, etc.
Try it again, but without the quotes surrounding the DB connection variables. I mean, they are variables & not strings, right?
Original with quotes:
$con=mysqli_connect("$host","$username","$password","$db_name");
Cleaned without quotes:
$con=mysqli_connect($host,$username,$password,$db_name);
You should change your code adding the snippet below. This way you can debug your code better:
if (!$result = $mysqli->query("YOUR-SQL", MYSQLI_USE_RESULT)) {
printf("Error: %s\n", $mysqli->error);
}
...do something here..
$result->close();
Someone in my class helped me figure it out, thanks though! Here is the code, just wonderful :)
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="blah"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
$con=mysqli_connect($host,$username,$password,$db_name);
if (mysqli_connect_errno()) // Check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="untitled.php" method="post"><!-- untitled.php -->
<?php
if(isset($_POST['submit'])) {
foreach ($_POST["holder"] as $i=>$email) {
$y=$email;
$h=$_POST["update"][$i];
$sql2="UPDATE ".$tbl_name." SET name = '" . $y . "' WHERE id =". $h;
//$res2=mysqli_query("UPDATE ".$tbl_name." SET name = '" . $y . "' WHERE id =". $h,$con);
$res2=mysqli_query($con,$sql2);
if ($res2){
}
else{
echo "<h1>NOPE!</h1>";
print "Failed to connect to MySQL: " . mysqli_error();
}
}
}
$result = mysqli_query($con,"SELECT * FROM ".$tbl_name);
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo '<input type="text" name="holder[]" id="checkbox-1" class="custom" value=" ' . $row['name'] . '"/>';
echo '<input type="hidden" name="update[]" id="checkbox-1" class="custom" value=" ' . $row['id'] . '"/>';
//echo '<input type="text" class="a" name="holder2[]" id="checkbox-1" class="custom" value="' . $row['price'] . '" />';
echo "<br>";
}
?>
</br>
<input type="submit" name="submit">
</form>
</body>
</html>

Parsing php with jquery and ajax

I`m trying to parse date in PHP. I copy part of several examples but it is not working.
What I am trying to do is :
I have a PHP file that receives a variable 'parttype' and runs a query.
<?php
$parttype = $_POST['parttype'];
echo "$parttype";
$conn = mysqli_connect("127.0.0.1", "root", "") or die ("No connection");
mysqli_select_db($conn , "shop") or die ("db will not open");
$query = "SELECT * from parts where parttype='$parttype'";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo '<table border="1" align ="center"><tr><th>Id</th><th>Name</th><th>Price</th><th>InStock</th><th>Description</th><th>SUpplier</th><th>Quantity</th><th>Remove</th></tr>';
while($row = mysqli_fetch_array($result))
{
echo "<tr><form action='ppcomppartout.php' method='post'><td><input type='hidden' name='partid' value='$row[0]'>" . $row[0] . "</td><td>" . $row[1] . "</td><td>" . $row[2] . "</td><td>" . $row[3] . "</td><td>" . $row[5] . "</td><td>" . $row[6] . "</td>
<td><input type='text' name='qtty' placeholder='0'></td><td>Buy <input type='submit'></td>
</form></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
Then in the index.php I have a function get() that posts the variable to data.php
and another function that is not working - function parse(data). I eventually insert a button to get some results, but I wanted the results to come up as soon as I change the values on the select box.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
function get() {
$.post("data.php", {parttype: form.parttype.value },
function(output) {
$("#output").html(output).show();
});
}
function parse(data){
$('#output').append('<select>');
$("select").on("change", function(evt)
{
line_record( $("select option:selected").index(),data)
});
}
</script>
</head>
<body>
<form name="form">
<select name="parttype" style="width: 117px">
<?php
$con = mysqli_connect("127.0.0.1", "root", "") or die ("No connection");
mysqli_select_db($con , "shop") or die ("db will not open");
$query = "SELECT distinct parttype from parts";
$result = mysqli_query($con, $query) or die("Invalid query");
while($rows = mysqli_fetch_array($result)) {
echo "<option value=\"" . $rows[0] . "\">" . $rows[0] . " </option>";
}
echo "</select>";
mysqli_close($con);
?>
</select>
<!--<input type="submit" value="OK!!"/>-->
</form>
<!--<input type="text" name="parttype">-->
<!--<input type="button" value="Get" onClick="get();" >-->
<input type="submit" value="Get" onClick="get();" >
</form>
<div id="output"></div>
</body>
</html>
Can some one help with this?? What I am doing wrong ??
You don't specify what the problem is exactly, but you should take it step by step.
The first problem you will encounter is probably when you call your get() function on page load. The data you are sending to your php script is:
{parttype: form.parttype.value }
where form.parttype.value seems to be undefined. If you want to send the values of your form, you can change that to:
$("form").serialize()
You should also check your html source as there seem to be multiple closing form tags.
Note: You are dumping your $_POST variable in your sql query without any validation or escaping. You should really switch to prepared statements as your code is vulnerable to sql injection.

Categories