Ok so what happens is I run this code and I get an error at line 68 which is in the second php segment where it grabs the info from the textfield which says:
Notice: Undefined index: fieldno0 in C:\wamp\www\addform.php on line 68
Any ideas what is going wrong here? I've been messing with this code and I can't figure out why I can't grab info from the text field.
<!DOCTYPE html>
<html>
<body>
<?php
$nof="fieldno";
$nos="Type";
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password,"vaccinations");
echo "<form action='addform.php' method='POST'>
<button type='submit' name='subform'>Submit Form</button><br>
<input type='text' placeholder='Number of fields' name='fieldno'/><br>
<input type='text' placeholder='Name of Form' name='form'/>
<button type='submit' name= 'submit' >Create fields</button> <br>
</form><br>";
$query= $conn->query("SELECT * FROM element_types");
$data = array();
while($rows = $query->fetch_assoc()){
$data[] = $rows;
}
if(isset($_POST['submit'])){
$fields = $_POST['fieldno'];
$FormName = $_POST['form'];
if($fields && $FormName){
$conn->query("INSERT INTO `vaccinations`.`forms` (`Name`, `author`, `number_of_elements`) VALUES ('$FormName', '5', '$fields');");}
echo "<form action='addform.php' method='POST'>";
for ($i=0; $i<$fields; $i++) {
echo "<input type='text' placeholder='Enter name of field$i' name='$nof$i'/>";
echo "$nof$i";
echo "<select name='$nos$i'>";
for($x=0;$x<sizeof($data);$x++){
echo "<option value=".$data[$x]['id'].">".$data[$x]['name']."</option>";
}
echo "</select><br></form><br>";
}
}
?>
<?php
if((isset($_POST['subform'])) ){
$fields=$conn->query("SELECT number_of_elements FROM forms WHERE id IN (SELECT MAX(id) FROM forms)");
while($rows = $fields->fetch_assoc()){
$data[] = $rows;
}
$data[0] = (int)$data[0];
$fields=$data;
echo("WHADDUP");
for($y=0;$y<1;$y++){
$fieldname = $_POST["$nof$y"];
echo $fieldname;
//$IorderInForm = ('$y-1');
//$selectOption = $_POST["$nos$y"];
//$insert=$conn->query("INSERT INTO `vaccinations`.`form_elements`
// (`form_id`, `field_number_in_form`, `element_type_id`, `field_name`)
// VALUES ('$formId', '$IorderInForm', '$selectOption', '$Ifieldname')");
}
}
?>
</body>
</html>
Related
I'm trying to create a modify users form, which has two checkboxes on for if a user is an Admin or if they are Active.
I've got it to read the database and check the check boxes accordingly but when I try to get the values from the userform to update, the database my PHP only returns one value.
<?php
session_start();
include 'scripts/dbconnection.php';
include 'scripts/logoncheck.php';
include 'scripts/uservariables.php';
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////Get operator number and name///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
$sql = "SELECT * from users";
$result = $mysqli->query($sql);
$displaytable = "<table>";
$displaytable = $displaytable."<thead><tr><th colspan='5'>Users!</th></tr>";
$displaytable = $displaytable."<tr><th>Number</th><th>Name</th><th>Admin</th><th>Active</th><th>Password</th></tr></thead><tbody>";
$user = array();
while($row = $result->fetch_assoc())
{
$displaytable = $displaytable."<tr>";
$displaytable = $displaytable."<td>".$row['opnum']."</td>";
$displaytable = $displaytable."<td><input type='text' name='username[]' value='".$row['opname']."' required></td>";
$admin = $row['admin'];
if($admin == "Yes")
{
$displaytable = $displaytable."<td><input type='checkbox' name='admin[]' value='Yes' checked='checked'/></td>";
}
else
{
$displaytable = $displaytable."<td><input type='checkbox' name='admin[]' value='No'/></td>";
}
$active = $row['active'];
if($active == "Yes")
{
$displaytable = $displaytable."<td><input type='checkbox' name='active[]' value='Yes' checked='checked'/></td>";
}
else
{
$displaytable = $displaytable."<td><input type='checkbox' name='active[]' value='No' /></td>";
}
$displaytable = $displaytable."<td><input type='checkbox' name='reset_password[]' /></td>";
$displaytable = $displaytable."</tr>";
}
$displaytable = $displaytable."</tbody></table>";
$num_rows = mysqli_num_rows($result);
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$useradmin = $_POST['admin'];
$useractive = $_POST['active'];
$resetpassword = $_POST['reset_password'];
print_r($_POST['admin'][0]);
print_r($_POST['admin'][1]);
print_r($_POST['admin'][2]);
for ( $i = 0; $i < $num_rows; $i++ )
{
echo "<br> User:".$username[$i]."<br>";
if(isset($useradmin[$i]))
{
echo $username[$i]." is Admin <br>";
}
elseif(!isset($useradmin[$i]))
{
echo $username[$i]." is not Admin <br>";
}
if(isset($useractive[$i]))
{
echo $username[$i]." is Active <br>";
}
elseif(!isset($useractive[$i]))
{
echo $username[$i]." is not Active <br>";
}
if(isset($resetpassword[$i]))
{
echo $username[$i]." reset password <br>";
}
elseif(!isset($resetpassword[$i]))
{
echo $username[$i]." not reset password <br>";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<LINK href="home.css" rel="stylesheet" type="text/css">
<title>Add Results</title>
</head>
<body>
<div class="login-card">
<?php include 'scripts/consts/menu.php';?>
<h1>Add Results!</h1>
<br>
<div class="results1">
<form action="#" method="POST">
<?php echo $displaytable;?>
<input name="submit" value="Save" type="submit" class="login login-submit">
</form>
</div>
</div>
</body>
</html>
The values that are being printed from the array useractive currently is just:
Array ( [0] => Yes )
And, what I ideally want is:
Array ( [0] => Yes, [1] => No, [2] => Yes)
In your code, if admin value is No in database and you want to change the value to Yes by checking the checkbox and update, you will get No as a value from the checkbox
Try replacing the checkbox code in the while loop with this:
$admin_checked = "";
if($admin == "Yes")
{
$admin_checked = "checked='checked'";
}
$displaytable = $displaytable."<td><input type='checkbox' name='admin[]' value='Yes' $admin_checked /></td>";
$active = $row['active'];
$active_checked = "";
if($active == "Yes")
{
$active_checked = "checked='checked'";
}
$displaytable = $displaytable."<td><input type='checkbox' name='active[]' value='Yes' $active_checked /></td>";
This way checkboxes will be checked if value is Yes and you only need to specify the checkbox input code once
And get the value from the checkboxes with this:
if(!($useradmin = $_POST['admin'])) //$_POST['admin'] is either "Yes" if checked or null if not checked
{
$useradmin = "No";
}
if(!($useractive = $_POST['active']))
{
$useractive = "No";
}
Strangely enough, you will only get the value of the checkboxes if they have been checked. It looks stupid, but that's how it works.
Here is my challange:
I want to update a MySQL table with inputs from a $_POST array.
How is this done? (Spend hours upon hours looking for a solution to this).
In my “table.php” I get the data from MySQL and place it in input forms.
In my “updatesfields.php” I can’t figure out how to update the fields in MySQL.
(I might be way off, but that's no news)
Table.php:
<form method="POST" action="updatefields.php" enctype="multipart/form-data" >
<table border="1"><tr>
<td>ID</td>
<td>Text</td>
</tr>
<?php
$host = "xxx";
$username1 = "xxx";
$password1 = "xxx";
$db_name = "xxx";
$tbl_name = "xxx";
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
$sql = "SELECT * FROM $tbl_name ORDER BY bilag ASC";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
// fetch
while($data = $q->fetch()){
echo "<tr><td>";
// --------------------- ID -----------------------------
$id = $data[0];
if ($id != 0)
{ echo "<center><input type='text' style='font-weight:bold;' value='$id' name='id[]' size='10'>";}
else { echo "<center><input type='text' style='font-weight:bold;' value='' name='id[]' size='10'>"; }
echo "</td>";
// --------------------- ID -----------------------------
echo "<td>";
// --------------------- Text -----------------------------
$text = $data[3];
if ($text != null)
{ echo "<center><input type='text' style='font-weight:bold;' value='$text' name='text[]' size='10'>";}
else { echo "<center><input type='text' style='font-weight:bold;' value='' name='text[]' size='10'>"; }
// --------------------- Text -----------------------------
echo "</td></tr>";
}
?>
</table>
<br>
<input type="submit" value="Update">
</form>
updatefields.php:
<?php
$host = "xxx";
$username1 = "xxx";
$password1 = "xxx";
$db_name = "xxx";
$tbl_name = "xxx";
foreach ($_POST as $number => $text)
{
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
$sql = "UPDATE $tbl_name SET text=? WHERE id=?]";
$q = $conn->prepare($sql);
$q->execute(array($indsæt,$id));
}
?>
First, in the HTML, we need to change this:
<input type="submit" value="Update">
to this. Names are important attributes because they become keys in the $_POST array.
<input type="submit" name="submit" value="Update">
Then, in updatefields.php:
if (isset($_POST['submit'])){
//how many ids came through in the $_POST array?
$id_count = count($_POST['id']);
//connect only once, before the loop
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
//this runs once for each id we have
for ($i=0; $i<$id_count; $i++){
$sql = "UPDATE $tbl_name SET text=? WHERE id=?";
$q = $conn->prepare($sql);
$q->bindParam(1, $_POST['text'][$i]);
$q->bindParam(2, $_POST['id'][$i]);
$q->execute();
if ($q) {//execute() returns TRUE on success
//insert success
} else {
//insert failed
}
}//for loop
} else {//submission did not come from form
echo "There was a problem processing this request. Please click here to try again.";
}
You can read more about binding parameters in the PHP documentation.
I create one form when i enter number of Rows & Columns then that number of rows & Column table would be generated i want save values entered into that table into database.Please anyone can help me..
My PHP CODE:
<?php
global $Hostname;
global $Username;
global $Password;
global $Database_name;
function getConnection()
{
$Hostname = "localhost";
$Username ="root";
$Password ="";
$Database_name="labdata";
$oMysqli = new mysqli($Hostname,$Username,$Password,$Database_name);
return($oMysqli);
}
if(isset($_POST['submit']))
{
echo "<table border='1' align='center'>";
for($iii = 0;$iii <$_POST['column'];$iii++)
{
echo "<tr>".$jjj."</tr>";
for($jjj = 0; $jjj <$_POST['rows'];$jjj++) //loop for display no. of rows.
{
echo "<td>" ."<input type=\"text\" name='$iii'>"."</td>";
}
}
echo "</table>";
echo"<form name=\"aa\" method=\"post\">";
echo "<input type=\"submit\" name=\"save\" value=\"save\">";
echo "</form>";
}
$TestName = $_POST['testname'];
$Result = $_POST['result'];
$Unit = $_POST['unit'];
$NormalRange = $_POST['NormalRange'];
if(isset($_POST['save']))
{
$InsertQuery = "INSERT INTO rct(testname,result,unit,NormalRange) VALUES('$TestName','$Result','$Unit','$NormalRange')";
$oMysqli= getConnection();
$oMysqli->query($InsertQuery);
print_r($InsertQuery);exit();
while($Row = $InsertQuery->fetch_array())
{
$TestName = $Row['testname'];
$Result = $Row['result'];
$Unit = $Row['unit'];
$NormalRange = $Row['NormalRange'];
}
}
?>
<html>
<head>
<title>Rct</title>
</head>
<body>
<form name='abc' method="post">
<label for='Table'>Define Table</label>
<label for='rows'>Row</label>
<input type="text" name="column"></input>
<label for='column'>Column</label>
<input type="text" name="rows"></input>
<input type="submit" name="submit" value="submit" onclick="aaa()">
</form>
</body>
</html>
There are many problems with your code:
The table containing <input/>s should be inside <form name='aa'>.
The inputs that are in the table should be named something like $iii[].
The [] tells PHP to create an array of all the rows in $_POST, so you can access $_POST[0][0] for row 0, col 0, $_POST[1][2] for row 2, col 1, etc.
You seem to have rows and columns backwards.
All your <input/> tags are missing the /.
There's no form with inputs named testname, result, unit, NormalRange, so why are you accessing these $_POST values?
fetch_array() can only be used after a SELECT query. INSERT doesn't return any values.
Probably other things I missed.
First of all you must correct the input tag
Replace
<input type="text" name="column"></input>
To
<input type="text" name="column" />
Second the upper loop must be row loop instead of colum as column sit inside the row
if(isset($_POST['submit']))
{
echo"<form name=\"aa\" method=\"post\">";
echo "<table border='1' align='center'>";
for($iii = 0;$iii <$_POST['rows'];$iii++)
{
echo "<tr>";//start Row here
for($jjj = 0; $jjj <$_POST['column'];$jjj++) //loop for display no. of rows.
{
echo "<td>" ."<input type=\"text\" name='".$iii.$jjj."'>"."</td>";//all TDs must be inside the row
}
echo "</tr>";//end row here
}
echo "</table>";
echo "<input type=\"submit\" name=\"save\" value=\"save\">";
echo "</form>";
}
And of course table must be inside the form.
Let me know if this helps
i have index.php and index2.php
here is index.php:
when i submit this value, index2.php will show. Here is index2.php:
I am not understanding, why this error msg is showing.
Anyways, submitting these selected values(index2.php) it will say a disease name from the database. clicking on submit, this text is showing(below):
I am pesting my code here:
index.php
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("symptomchecker",$con) or die(mysql_error());
$q = "select dtid,diseasetype from disease_type";
$result = mysql_query($q,$con) or die(mysql_error());
$numRB = mysql_num_rows($result);
echo "<html><head><title>Disease Type</title></head><body><h1>Disease List</h1></br><form action='index2.php' method='post'>";
$i=0;
while($row = mysql_fetch_array($result)){
echo $row['diseasetype'];
echo "<input type='radio' name='diseasetype' id='pet1' value='$row[dtid]' />" ;
echo "<br />";
$i++;
}
echo " <input type='submit' value='submit' name='submit'></form></body></html>";
?>
index2.php:
$diseasetypeid = "$_POST[diseasetype]";
$j=0;$i=0;
$query = "select did from disty_dis_rel where dtid = ".$diseasetypeid."";
$result1 = mysql_query($query,$con) or die(mysql_error());
echo "<html><head><title>symptom</title></head><body><h1>symptom List</h1></br><form action='' method='post'>";
while($row = mysql_fetch_array($result1))
{
$z=$row['did'];
$query2 = "select sid,symptomname from symptom where sid = ".$z."";
$result2 = mysql_query($query2,$con) or die(mysql_error());
while($row2 = mysql_fetch_array($result2))
{
echo $row2['symptomname'];
echo "<input type='checkbox' name='pets[$i]' id='pet1' value='$row[sid]' />" ;
echo "<br />";
$i++;
}
$j++;
}
echo " <input type='submit' value='submit' name='submit'></form></body></html>";
if(isset($_REQUEST[submit]))
{
**foreach ($_REQUEST[pets] as $key=>$values)**
{
$yy.=$values."-";
}
$yy=rtrim($yy,"-");
$xx = "select did,sids from dis_sym_rel where sids=".$yy."";
$result3 = mysql_query($xx,$con) or die(mysql_error());
while($row = mysql_fetch_array($result3)){
$p=$row[did];
$xxx = "select did,diseasename from disease where did=".$p."";
$result4 = mysql_query($xxx,$con) or die(mysql_error());
while($row4 = mysql_fetch_array($result4))
{
echo $row4[diseasename];
}
}
}
?>
the line between ###doublestar### is the error line(49).
Just within index2.php :
$diseasetypeid = "$_POST[diseasetype]";
should be
$diseasetypeid = $_POST["diseasetype"];
and
if(isset($_REQUEST[submit]))
should really be this :
if($_SERVER['REQUEST_METHOD'] == 'POST')
this checks the REQUEST_METHOD rather than a form value. And
foreach ($_REQUEST[pets] as $key=>$values)
should be
foreach ($_REQUEST['pets'] as $key=>$values)
and I suggest you read about sql injection
This code:
foreach ($_REQUEST[pets] as $key=>$values)
Should be changed to:
foreach ($_REQUEST['pets'] as $key=>$values)
You should quote (put apostrophe or double-quotes, before and after your array key if it's string).
Then, you must have a form something to the following (i can't find it in your index.php file).
<input type="text" name="pets[]" />
<input type="text" name="pets[]" />
<input type="text" name="pets[]" />
<input type="text" name="pets[]" />
<input type="text" name="pets[]" />
The array key 'pets' is the name of your input. [] indicates array. In foreach ($something as ...), $something must be an array (or object).
I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>