I am trying to use PHP to update an SQL table using HTML forms.
I want the user to be able to search for a VCR name and display it details in a while loop and then an update form will appear for the user to change its details in the database.
However every time i press the update button on the update form, the variables that hold the new details empty and become undefined.
<?php require('connect.php'); ?>
<?php require('headerPrivate.php'); ?>
<?php require('session.php');?>
<?php
//SEARCH PHP CODE
//THIS WORKS FINE AND ALL THE DETAILS APPEAR
if(isset($_POST["search"]))
{
//CREATE VARIABLES
$username=$_SESSION['username'];
echo "username: ".$username;
echo '<br>';
$vcrName=$_POST['name'];
echo "VCR Name: ".$vcrName;
echo '<br>';
echo '<br>';
//SELECT * FROM PRODUCT
$sql="SELECT *
FROM product
INNER JOIN user
ON product.owner_ID=user.user_ID
WHERE username='$username' AND name='$vcrName'";
echo "SQL SELECT 1: ".$sql;
echo '<br>';
echo '<br>';
//$vcrName=$_POST['name'];
$result = mysqli_query($con,$sql);
echo '<div class="row">';
echo '<div class="col-xs-6 col-md-4">';
while ($row_all = mysqli_fetch_assoc($result))
{
echo '<form method="post">';
echo "<u>Title: ".$row_all["name"].'</u>';
echo '<br>';
echo '<small>';
echo " Price: ".$row_all["price"];
echo '</small>';
echo '<br>';
echo "<p><u>Short Description:</u> ".$row_all["short_descripton"]."</p>";
echo '<br>';
echo "<p><u>Long Description:</u> ".$row_all["long_description"]."</p>";
echo '<br>';
echo '<hr>';
echo '</form>';
echo '<div>';
}
echo '</div>';
}
?>
<content>
<!--SEARCH FOR VCR NAME-->
<form class="form" method="post">
<label for="name" class="sr-only">VCR Name</label>
<input type="text" name="name" class="form-control" placeholder="VCR Name" required="" autofocus="" autocomplete="off">
<button name="search" type="search" class="btn btn-success btn-block">Search</button>
</form>
<?php
//This is where i run into issues. The old name in the variable $vcrName is empty and i need it for the update SQL statement.
//UPDATE PHP
if(isset($_POST["alter"]))
{
//CREATE A SESSION VARIABLE FOR THE CUSTOMER ID
$customer_ID=$_SESSION['customer_ID'];
echo "Customer ID: ".$customer_ID;
echo '<br>';
//CREATE VARIABLES
$changeTitle=$_POST["titleChange"];
$changesDescChange=$_POST["sDescChange"];
$changelDescChange=$_POST["lDescChange"];
$changepriceChange=$_POST["priceChange"];
$vcrName=$_POST['name'];
//UPDATE SQL
$sql_update="UPDATE product
SET
name='$changeTitle',
short_descripton='$changesDescChange',
long_description='$changelDescChange',
price='$changepriceChange'
WHERE
owner_ID='$customer_ID' AND name='$vcrName'";
echo "SQL Update 0: ".$sql_update;
echo '<br>';
echo '<br>';
echo "Updated Name: ".$changeTitle;
echo '<br>';
echo '<br>';
echo "SQL Update 1: ".$sql_update;
return $sql_update;
echo '<br>';
echo '<br>';
$result_update = mysqli_query($con,$sql_update);
if($result_update){
echo "Update Successful!";
}
else {
echo "Update Unsuccessful";
}
}
?>
<!--UPDATE FORM-->
<form class="form" method="post">
<label for="titleChange" class="sr-only">VCR Name</label>
<input type="text" name="titleChange" class="form-control" placeholder="VCR Name" required="" autofocus="" autocomplete="off">
<label for="sDescChange" class="sr-only">Short Description</label>
<input type="text" name="sDescChange" class="form-control" placeholder="Short Description" required="" autofocus="" autocomplete="off">
<label for="lDescChange" class="sr-only">Long Description</label>
<input type="text" name="lDescChange" class="form-control" placeholder="Long Description" required="" autofocus="" autocomplete="off">
<label for="priceChange" class="sr-only">Price</label>
<input type="text" name="priceChange" class="form-control" placeholder="Price" required="" autofocus="" autocomplete="off">
<button name="alter" type="submit">Change</button>
</form>
</content>
</body>
</html>
Your PHP code refers to a POST variable that doesn't exist:
$vcrName=$_POST['name'];
In your update form, you need to pass it as a hidden value:
<input type="hidden" name="name" value="<?=htmlspecialchars($vcrName)?>"/>
It's not clear if these are two separate PHP scripts (or if so, why they are) so you may need to put in a database call to get that value. From a user interface point of view, one is typically given the existing values when updating a record anyway. This would mean getting the data and giving each form element a value attribute.
Related
I was making a form inside a PHP script and when i tried to access a field
of form in the same script it was giving me error Undefined index
This is my code:
<?php
$query="SELECT * FROM `vendor_list`";
$query_run=mysql_query($query);
if(mysql_num_rows($query_run)>0)
{
echo '<form method="POST">';
echo 'Book name:<input type="text" name="book_name" size="40" maxlength="40"><br><br>';
echo 'Number Of Copies:<input type="text" size="5" name="num_copies" maxlength="2"><br><br>';
echo '<select name="vendor_email">';
while($query_row=mysql_fetch_assoc($query_run))
{
$laser=$query_row['vendor_name'];
$email=$query_row['email'];
echo "<option value='".$email."'>".$laser."</option>";
}
echo '</select><br>';
echo '<input type="submit" value="submit">';
echo '</form>';
}
else
{
echo 'No vendor to display';
}
echo $_POST['book_name'];
USE THIS:-
<?php
$query="SELECT * FROM `vendor_list`";
$query_run=mysql_query($query);
if(mysql_num_rows($query_run)>0)
{
echo '<form method="POST">';
echo 'Book name:<input type="text" name="book_name" size="40" maxlength="40"><br><br>';
echo 'Number Of Copies:<input type="text" size="5" name="num_copies" maxlength="2"><br><br>';
echo '<select name="vendor_email">';
while($query_row=mysql_fetch_assoc($query_run))
{
$laser=$query_row['vendor_name'];
$email=$query_row['email'];
echo "<option value='".$email."'>".$laser."</option>";
}
echo '</select><br>';
echo '<input type="submit" value="submit">';
echo '</form>';
}
else
{
echo 'No vendor to display';
}
if($_POST){
echo $_POST['book_name'];
}
?>
Try this
<?php
$query="SELECT * FROM `vendor_list`";
$query_run=mysql_query($query);
if(mysql_num_rows($query_run)>0)
{
?>
<form method="POST" action="">
Book name:<input type="text" name="book_name" size="40" maxlength="40"><br><br>
Number Of Copies:<input type="text" size="5" name="num_copies" maxlength="2"><br><br>
<select name="vendor_email">
<?php
while($query_row=mysql_fetch_assoc($query_run))
{
$laser=$query_row['vendor_name'];
$email=$query_row['email'];
echo "<option value='".$email."'>".$laser."</option>";
}
?>
</select><br>
<input type="submit" name="submit" value="submit">
</form>
<?php
}
else
{
echo 'No vendor to display';
}
if(isset($_POST["submit"]))){
echo $_POST['book_name'];
}
?>
The Clean Way
All the breaks you have in that code are a hot mess...
Tip When you are echoing too much HTML just wrap it in an if..else.. like this...
<?php
$query = "SELECT * FROM `vendor_list`";
$query_run = mysql_query($query);
?>
<?php if(mysql_num_rows($query_run)>0): ?>
<form method="POST">
<label for="book_name">Book name:</label>
<input type="text" name="book_name" id="book_name" size="40" maxlength="40">
<label for="book_name"Number Of Copies:</label>
<input type="text" size="5" name="num_copies" maxlength="2">
<select name="vendor_email">
<?php while($query_row=mysql_fetch_assoc($query_run)): ?>
<option value="<?=$query_row['email']?>"><?=$query_row['vendor_name']?></option>
<?php endwhile; ?>
</select>
<input type="submit" value="submit">
</form>
<?php else: ?>
<p>No vendor to display</p>
<?php endif; ?>
<?php if (isset($_POST['book_name'])) echo $_POST['book_name']; ?>
Using the below code this will also check if you have a form submission or not, unless this code is a cut/copy paste.. It looks like it will process sections when it should not.. eg the echo post..
Personally i myself will set the action="" to PHP_SELF as many years ago had issues with it, soon this will change once i start using HTML5 when its cross browser enough / older users update their browsers.
Example of processing or showing a post but not both.
echo $_POST['book_name'];
echo "POST Dump: " . print_r($_POST, true);
} else {
// No Form Submission, So we generate the form instead
// QUERY - data
$query = "SELECT * FROM 'vendor_list'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)>0) {
// FORM - Name/#Copies
echo '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
echo 'Book name:<input type="text" name="book_name" size="40" maxlength="40"><br><br>';
echo 'Number Of Copies:<input type="text" size="5" name="num_copies" maxlength="2"><br><br>';
// FORM - Select Vendor
echo '<select name="vendor_email">';
while($query_row=mysql_fetch_assoc($query_run))
{
$laser=$query_row['vendor_name'];
$email=$query_row['email'];
echo "<option value='".$email."'>".$laser."</option>";
}
echo '</select><br>';
// FORM - Submit / Close Form
echo '<input type="submit" value="submit">';
echo '</form>';
} else {
echo 'No vendor to display';
}
}
?>
Or using a code that shows the form and processing any $_POST
<?php
// QUERY - data
$query = "SELECT * FROM 'vendor_list'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)>0) {
// FORM - Name/#Copies
echo '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
echo 'Book name:<input type="text" name="book_name" size="40" maxlength="40"><br><br>';
echo 'Number Of Copies:<input type="text" size="5" name="num_copies" maxlength="2"><br><br>';
// FORM - Select Vendor
echo '<select name="vendor_email">';
while($query_row=mysql_fetch_assoc($query_run))
{
$laser=$query_row['vendor_name'];
$email=$query_row['email'];
echo "<option value='".$email."'>".$laser."</option>";
}
echo '</select><br>';
// FORM - Submit / Close Form
echo '<input type="submit" value="submit">';
echo '</form>';
} else {
echo 'No vendor to display';
}
if (isset($_POST['book_name'])) {
echo "<b>Displaying post data</b> <br />";
echo "Example book: " . $_POST['book_name'] . "<br />";
echo "POST Dump: <br /><pre>" . print_r($_POST, true) . "</pre>";
} else {
echo "Page has not been subitted yet, please select an item";
}
?>
this script displays data from a specific email address which the user enters.
the snippet of code below displays the data in a textfield at the top of the page however I want to display the data in a textfield in the body of text.
echo '<input name="login" type="text" value="' . $result['name'] . '>';
What do I change in the above code to enable me to do this.
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="orders"; // Table name
$email = $_POST['textfield'];
$db = new PDO('mysql:host='.$host.
';dbname='.$db_name.
';charset=UTF-8',
$username, $password);
$stmt = $db->prepare('SELECT * FROM `orders` WHERE `email`=:email LIMIT 1');
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount()>0)
{
echo '<input name="login" type="text" value="' . $result['name'] . '>';
}
else
{
echo "Email not found in the database!";
}
?>
form:
<form id="form_53" name="login" action="test.php">
<input type="submit" value="Track">
<input type="text" username="textfield" value="">
<input type="text" name="name" value="<?php echo $result['name']?>"> //I want to display results here
</form>
if both the code exists in the same file.. this will work
<input type="text" name="name" value="<?php echo $result['name']?>">
and if you want to check if there are rows returned you can use
<input type="text" name="name" value="<?php echo ($stmt->rowCount()>0) ? $result['name'] : "" ?>">
edited the code so that you know what exactly you want to do
First: Replace this code
if($stmt->rowCount()>0)
{
echo '<input name="login" type="text" value="' . $result['name'] . '>';
}
else
{
echo "Email not found in the database!";
}
just keep $result = $stmt->fetch(PDO::FETCH_ASSOC); and
if($stmt->rowCount()<=0) echo "Email not found in the database!";
Second: now in HTML section
<input type="text" name="name" value="<?php echo ($stmt->rowCount()>0) ? $result['name'] : "" ?>">
As long as you don't clobber $result you can do:
<input type="text" name="name" value="<?php echo $result['name']; ?>"> //I want to display results here
echo '<input name="login" type="text" value="' . $result['name'] . '">';
Just add a double quote to the echo'd string.
It's pretty easy to accomplish. Of course make sure that the $results array is included in the session for the desired HTML page that you are working on.
<form id="form_53" name="login" action="test.php">
<input type="submit" value="Track">
<input type="text" username="textfield" value="">
<input type="text" name="name" value="<?php echo $results['name']?>"> //I want to display results here
</form>
how to display the result after submit the form
i want a display result after submit the form for print
example 1st im filling the form submit the result after the submit i want a screen to display same result
http://www.tizag.com/phpT/examples/formexample.php
how can i do this
please help me to fix this issue.
php form code
<?php
function renderForm($grn, $name, $rollno, $class, $fees, $date, $reference, $error)
{
?>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<p><span class="style9"><strong>G.R.N No:</strong></span><strong> *</strong>
<input name="grn" type="text" id="grn" value="<?php echo $grn; ?>" size="50" />
</p>
<p><span class="style9"><strong>Name:</strong></span><strong> *</strong>
<input name="name" type="text" id="name" value="<?php echo $name; ?>" size="50" />
</p>
<p><span class="style9"><strong>Roll No :</strong></span><strong> *</strong>
<input name="rollno" type="text" id="rollno" value="<?php echo $rollno; ?>" size="50" />
</p>
<p><span class="style9"><strong>Class:</strong></span><strong> *</strong>
<input name="class" type="text" id="class" value="<?php echo $class; ?>" size="50" />
</p>
<p><span class="style9"><strong>Fees Date :</strong></span><strong> *</strong>
<input id="fullDate" name="date" type="text" value="<?php echo $date; ?>" size="50" />
</p>
<p><span class="style9"><strong>Fees :</strong></span><strong> *</strong>
<input name="fees" type="text" value="<?php echo $fees; ?>" size="50" />
</p>
<span class="style9"><strong>Reference</strong></span><strong> *</strong>
<input name="reference" type="text" value="<?php echo $reference; ?>" size="50">
<br/>
<p class="style1">* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$grn = mysql_real_escape_string(htmlspecialchars($_POST['grn']));
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$rollno = mysql_real_escape_string(htmlspecialchars($_POST['rollno']));
$class = mysql_real_escape_string(htmlspecialchars($_POST['class']));
$fees = mysql_real_escape_string(htmlspecialchars($_POST['fees']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$reference = mysql_real_escape_string(htmlspecialchars($_POST['reference']));
// check to make sure both fields are entered
if ($grn == '' || $name == '' || $rollno == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($grn, $name, $rollno, $class, $fees, $date, $reference, $error);
}
else
{
// save the data to the database
mysql_query("INSERT fees SET grn='$grn', name='$name', rollno='$rollno', class='$class', fees='$fees', date='$date', reference='$reference'")
or die(mysql_error());
echo "<center>KeyWord Submitted!</center>";
// once saved, redirect back to the view page
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','','','','','');
}
?>
Not quite shure what you are asking.
do you need help displaying the submited form data? or more spesific display for print?
to display it you would just need to make a html page that displays it.
like:
echo '<table><tr>';
echo '<td>';
echo '<Strong>Name:</strong><br/>';
echo $name;
echo '</td>';
echo '</tr></table>';
To display just the result and not the form, when you post to the same page you need to encapsulate the for code with an if statement.
if(isset($_POST['submit'])) {
//code for the php form
}else {
//code to display form
}
Use a new page for the "action" part in the form. On that new page, simply echo the $_POST of values you want to display. If you plan on making some sort of page so that people can check their entries, you could store these $_POST-data in sessions.
Simply call function on the bottom to disply posted values :
function showFormValues()
{
?>
<div>
<p><span class="style9"><strong>G.R.N No:</strong></span><strong> *</strong>
<?php echo $_POST['grn']; ?>
</p>
<p><span class="style9"><strong>Name:</strong></span><strong> *</strong>
<?php echo $_POST['name'];
</p>
and so on.
.
.
.
.
</div>
<?php
}
?>
I've the following code :
$query = "SELECT * FROM items WHERE SUBSTRING(item_no, 1, ".$length.") BETWEEN
'".$from_new."' AND '".$to_new."' ORDER BY item_no Desc";
$result = mysql_query($query);
$dd=array();
$ii=array();
$qq=array();
$aa=array();
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
?>
<form method="post" action="final_group_items.php">
<?php
echo "<table>";
for($i=0;$i<$num;$i++){
$row = mysql_fetch_array($result);
echo "<tr><td align=center>"; ?>
<input disabled maxlength="2" type="text"
name="ii[]" value="<?php echo strtoupper($row['item_no']); ?>"><?php echo
"</td><td align=center>";?>
<input disabled maxlength="2" type="text"
name="qq[]" value="<?php echo $row['qty'];?>">
<?php echo "</td><td align=center>"; ?>
<input disabled maxlength="2" type="text"
name="aa[]" value="<?php echo $row['actual_price'];?>">
<?php echo "</td><td align=center>";?>
<input required maxlength="2" type="text" name="dd[]" value="<?php echo
$row['discount_price']; ?>">
<?php
echo "</td><tr>";
}
echo "</table>";
?>
<input type="submit" value="Change Values">
</form>
Now when i click Submit it will open the final_group_items.php which has the follow testing code to make sure if all array (ii,qq,dd,aa) are not empty:
if(empty($_POST['qq']))
{
echo "No value inside";
return false;
}
foreach($_POST['qq'] as $test)
{
echo $test;
}
return true;
so by testing all array's, the only one works is $_POST['dd']...Others outputs "no value inside" which I really don't know how or why?
What should I do when I have multiple of fields having uniqe arrays and values.
Thank You
This:
<input disabled maxlength="2" type="text" name="qq[]" value="<?php echo $row['qty'];?>">
Will prevent the browser from even posting the field at form submission, because disabled gets an implicit value of "disabled".
The attribute should be removed:
<input maxlength="2" type="text" name="qq[]" value="<?php echo $row['qty'];?>">
I have recently used a PHP pagination tutorial, Pagination - what it is and how to do it, to display record information from a MySQL database. The problem is that the page only sends out the information sent in the latest form, and I am not quite sure how to fix the problem.
The code for the form output is shown below.
$musicitems = getmusicitems($pagenumber,$prevpage,$lastpage,$nextpage);
$count = ($musicitems==NULL) ? 0 : mysql_num_rows($musicitems);
for ($i=0;$i<$count;$i++)
{
$records = mysql_fetch_assoc($musicitems);
print'
<label for="deleteMusicItem'.$records['m_id'].'" id="deleteMusicItemLabel'.$records['m_id'].'">Delete Music Record:</label>
<input type="checkbox" name="deleteMusicItem" id ="deleteMusicItem'.$records['m_id'].'" value="delete" />
<br/>
<label for="artistname'.$records['m_id'].'" id="artistLabel'.$records['m_id'].'">Artist Name:</label>
<input type="text" size="30" name="artistname" class="artistname1" id ="artistname'.$records['m_id'].'" value="'.$records['artistname'].'" />
<br/>
<label for="recordname'.$records['m_id'].'" id="recordnameLabel'.$records['m_id'].'">Record Name:</label>
<input type="text" size="30" name="recordname" class="recordname1" id ="recordname'.$records['m_id'].'" value="'.$records['recordname'].'"/>
<br/>
<label for="recordtype'.$records['m_id'].'" id="recordtypeLabel'.$records['m_id'].'">Record type:</label>
<input type="text" size="20" name="recordtype" class="recordtype1" id ="recordtype'.$records['m_id'].'" value="'.$records['recordtype'].'"/>
<br/>
<label for="format'.$records['m_id'].'" id="formatLabel'.$records['m_id'].'">Format:</label>
<input type="text" size="20" name="format" class="format1" id ="format'.$records['m_id'].'" value="'.$records['format'].'"/>
<br/>
<label for="price'.$records['m_id'].'" id="priceLabel'.$records['m_id'].'">Price:</label>
<input type="text" size="10" name="price" class="price1" id ="price'.$records['m_id'].'" value="'.$records['price'].'"/>
<br/><br/>
';
$musicfiles=getmusicfiles($records['m_id']);
for($j=0; $j<2; $j++)
{
$mus=mysql_fetch_assoc($musicfiles);
if(file_exists($mus['musicpath']))
{
echo ''.$mus['musicname'].'<br/>';
}
else
{
echo '<label for="musicFile'.$records['m_id'].'" id="musicFileLabel'.$records['m_id'].'">Music:</label> <input type="file" size="40" name="musicFile1" id="musicFile'.$records['m_id'].'"/><br/>';
}
}
$pictures=getpictures($records['m_id']);
for($j=0;$j<2;$j++)
{
$pics=mysql_fetch_assoc($pictures);
if(file_exists($pics['picturepath']))
{
echo '<img src="'.$pics['picturepath'].'" width="150" height="150"><br/>';
}
else
{
echo '<label for="pictureFile'.$records['m_id'].'" id="pictureFileLabel'.$records['m_id'].'">Picture:</label><input type="file" size="40" name="pictureFile1" id="pictureFile'.$records['m_id'].'"/><br/>';
}
}
}
echo'<input type="submit" value="Submit" name="modfiymusicitem" id="modfiymusicitem" /> ';
if ($pagenumber == 1) {
echo " FIRST PREV ";
}
else {
echo " <a href='{$_SERVER['PHP_SELF']}?pagenumber=1'>FIRST</a> ";
$prevpage = $pagenumber-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenumber=$prevpage'>PREV</a> ";
}
echo "(Page $pagenumber of $lastpage)";
if ($pagenumber == $lastpage) {
echo " NEXT LAST ";
}
else {
$nextpage = $pagenumber+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenumber=$nextpage'>NEXT</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenumber=$lastpage'>LAST</a> ";
}
You have to pass the form data to the next page manually. This, most important part, is always forgotten by tutorial writers.
You have to pass to other pages, not only the page number, but the whole form data.
I hope your form uses the GET method, as it should be, so, you have your data either in the $_SERVER['QUERY_STRING'] as a string or the $_GET array. So, you can either do regexp pagenumber in the QUERY_STRING, or assemble another QUERY_STRING from the $_GET array, like this:
$_GET['pagenumber']=$nextpage;
$query_string=http_build_query($_GET);
echo " <a href='{$_SERVER['PHP_SELF']}?$query_string'>NEXT</a> ";