I am working on PHP CRUD operations and I have created a basic edit form in PHP. I have not used any field validations and all I want is simply editing information.
I am following this tutorial
Once a user is clicked on Edit link he is directed to the following form on which the user is supposed to edit his data.
Here is the code
<?php
include_once './functions.php';
include_once './database.php';
function renderForm($firstName,$lastName,$age){
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<form action="edit.php" method="post">
First Name<input type="text" name="firstname" value="<?php $firstName ;?>"><br/>
Last Name<input type="text" name="lastname" value="<?php $lastName ;?>"><br/>
Age<input type="text" name="age" value="<?php $age ;?>"><br/>
<input type="submit" name="submit" value="Edit">
Cancel
</form>
<?php
}
?>
<?php
if (isset($_POST['submit'])) {
$firstName = cleanData($_POST['firstname']);
$lastName = cleanData($_POST['lastname']);
$age = (int) $_POST['age'];
$id = $_GET['id'];
$query = "UPDATE basic ";
$query.="SET first_name='$firstName',last_name='$lastName',age=$age ";
$query.="WHERE id=$id";
confirmQuery($query);
closeDatabase();
}else{
$id=cleanData($_GET['id']);
$query="SELECT * FROM basic WHERE id= {$id} ";
$result=confirmQuery($query);
$rows= mysqli_fetch_assoc($result);
$firstName=$rows['first_name'];
$lastName=$rows['last_name'];
$age=$rows['age'];
renderForm($firstName, $lastName, $age);
}
?>
</body>
</html>
//Additional information
//functions included in other files
function cleanData($input){
global $connection;
return mysqli_real_escape_string($connection,$input);
}
function confirmQuery($query){
global $connection;
$result=mysqli_query($connection, $query);
if(!$result){
return "Query failed : ".mysqli_error($connection);
}
else{
return $result;
}
}
function closeDatabase(){
global $connection;
mysqli_close($connection);
}
//I have not included the file which I am using to
//connect to the DB. I am sure there is no error with that file since it works
//properly with other php files
The problem that I have with my edit form is it does not show previously entered data and just shows only a blank form (similar to create form). (It does not happen when I run the demo in the above mentioned tutorial)
Netbenas IDE says variables which are inside HTML input tags seems to be unused in its scope. I have googled this question and found that warning can be simply ignored.
But Where have I gone wrong?
I am grateful to anyone who can kindly go through my code and show me the error.
Thank You :)
I have change your PHP code to below code use in your edit.php.if u get any issue put comment.
<?php
include_once './functions.php';
include_once './database.php';
if (isset($_POST['submit'])) {
$firstName = cleanData($_POST['firstname']);
$lastName = cleanData($_POST['lastname']);
$age = (int) $_POST['age'];
$id = $_GET['id'];
$query = "UPDATE basic ";
$query.="SET first_name='$firstName',last_name='$lastName',age=$age ";
$query.="WHERE id=$id";
$r=mysql_query($query);
if($r)
{
echo "Record updated";
}
}
$id=$_GET['id'];
$query="SELECT * FROM basic WHERE id='$id' ";
$result=confirmQuery($query);
$rows= mysqli_fetch_assoc($result);
$firstName=$rows['first_name'];
$lastName=$rows['last_name'];
$age=$rows['age'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<form action="edit.php" method="post">
First Name<input type="text" name="firstname" value="<?php echo $firstName ;?>"><br/>
Last Name<input type="text" name="lastname" value="<?php echo $lastName ;?>"><br/>
Age<input type="text" name="age" value="<?php echo $age ;?>"><br/>
<input type="submit" name="submit" value="Edit">
Cancel
</form>
</body>
</html>
Related
I tried to create a form which will send an email and add data to MySQL data base. For email part because I work on localhost I used formsubmit. All good but there is a conflict. When I press on send only the email is send without any data added to my database. If I delete the action attribute from form data will be added but in this case I can't send any emails. Here is my file:
<?php
require 'config.php';
if(!empty($_SESSION["id"]))
{
$id= $_SESSION["id"];
$result = mysqli_query($conn,"SELECT * FROM tb_user WHERE id= $id");
$row = mysqli_fetch_assoc($result);
}
else
{
header("Location: login.php");
}
if(isset($_POST["submit"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$cui = $_POST['cui'];
$tip = $_POST['tip'];
$adresa = $_POST['adresa'];
$query = "INSERT INTO beneficiari VALUES('','$email','$name','$cui','$tip','$adresa')";
mysqli_query($conn,$query);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Beneficiari </title>
<link rel="stylesheet" href="indexCSS.css">
<link rel="stylesheet" type="text/css" href="beneficiariCSS.css">
</head>
<body>
<div class="topnav">
Welcome <?php echo $row["name"]; ?>
Logout
<a class="active" href="index.php">Home</a>
Anunturi
Viz
Registration
</div>
<div class="container">
<form action="https://formsubmit.co/0e6b51872b4393271dbfa08bb0655fc8" method="POST">
<h3>Inregistrare</h3>
<input type="text" name="name" id="name" placeholder="Denumire institutie" required>
<input type="email" name="email" id="email" placeholder="Enter an valid email" required>
<input type="text" name="cui" id="cui" placeholder="CUI" required>
<input type="text" name="tip" id="tip" placeholder="Tipul institutie" required>
<input type="text" name="adresa" id="adresa" placeholder="Adresa" required>
<button type="submit" name="submit">Send</button>
</form>
</div>
</body>
</html>
You can remove the action from form, and add it after the SQL query, within the if statement as header, like so:
if(isset($_POST["submit"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$cui = $_POST['cui'];
$tip = $_POST['tip'];
$adresa = $_POST['adresa'];
$query = "INSERT INTO beneficiari VALUES('','$email','$name','$cui','$tip','$adresa')";
mysqli_query($conn,$query);
header('location: https://formsubmit.co/0e6b51872b4393271dbfa08bb0655fc8');
}
I believe this will work.
But whatever you do make sure you check the input!! The way you are handling your input right now is very dangerous, and allows users to inject you with SQLs (read up on SQL injections and protection)
Actually i'm trying to create a table by name that user suggests and insert data into that table, also by user's suggestion.
I've two php files: CreateTable.php and EnterData.php
Here is my code of CreateTable.php:
<?php
$conn = new mysqli("localhost","root","","mywebsite");
if (isset($_POST['tbButton'])) {
$qry = "Create Table ".$_POST['tableName']."(firstname varchar(25),lastname varchar(25));";
$res = mysqli_query($conn,$qry);
if ($res) {
echo "Table Created!";
}
else{
die("query failed!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create Table</title>
</head>
<body>
<form action="EnterData.php" method="post">
<p><input type="text" name="tableName" placeholder="Enter Table Name..."></p>
<p><input type="submit" name="tbButton"></p>
</form>
</body>
</html>
Here is my code of EnterData.php:
<?php
$tbname = $_POST['tableName'];
$conn = new mysqli("localhost","root","","mywebsite");
if (isset($_POST['dataButton'])) {
$qry = "Insert into ".$tbname."(firstname,lastname) values('".$_POST['firstname']."','".$_POST['lastname']."');";
$res = mysqli_query($conn,$qry);
if ($res) {
echo "Data Inserted!";
}
else{
die("query failed!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create Table</title>
</head>
<body>
<form action="" method="post">
<p><input type="text" name="firstname" placeholder="Enter First Name..."></p>
<p><input type="text" name="lastname" placeholder="Enter Last Name..."></p>
<p><input type="submit" name="dataButton"></p>
</form>
</body>
</html>
Problem is that when I write action="EnterData.php" Table doesn't create in database but form values passes to 'EnterData' file.
and when I write action="CreateTable.php" table is created in database but values doesn't pass to 'EnterData' file.
I want to pass values to EnterData file and database too.
this my first attempt on stackoverflow, hope i explained my question very nicely
You can pass your tablename through get method
CreateTable.php
<?php
$conn = new mysqli("localhost","root","","mywebsite");
$tableName = $_POST['tableName'];
if (isset($_POST['tbButton'])) {
$qry = "Create Table ".$tableName ."(firstname varchar(25),lastname varchar(25));";
$res = mysqli_query($conn,$qry);
if ($res) {
header("Location: EnterData.php?tableName=".$tableName);
}
else{
die("query failed!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create Table</title>
</head>
<body>
<form action="CreateTable.php" method="post">
<p><input type="text" name="tableName" placeholder="Enter Table Name..."></p>
<p><input type="submit" name="tbButton"></p>
</form>
</body>
</html>
EnterData.php
<?php
$tbname = $_GET['tableName'];
$conn = new mysqli("localhost","root","","mywebsite");
if (isset($_POST['dataButton'])) {
$qry = "Insert into ".$tbname."(firstname,lastname) values('".$_POST['firstname']."','".$_POST['lastname']."');";
$res = mysqli_query($conn,$qry);
if ($res) {
echo "Data Inserted!";
}
else{
die("query failed!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create Table</title>
</head>
<body>
<form action="EnterData.php?tableName=<?php echo $tbname;?>" method="post">
<p><input type="text" name="firstname" placeholder="Enter First Name..."></p>
<p><input type="text" name="lastname" placeholder="Enter Last Name..."></p>
<p><input type="submit" name="dataButton"></p>
</form>
</body>
</html>
Why would you let the user create tables in your database in the first place (with root privileges!)?
As for your question... Both php files submit to EnterData.php (that is if EnterData.php's blank action attribute is properly interpreted by the browser), so your CreateTable.php has no idea of what $_POST['tableName'] is.
I don't know what it is you are trying to do, but php files don't magically get to know each other's variables - you actually have to include a file in another one to let them share a set of variables, pass the variables through $_REQUEST or use AJAX to take care of things.
I would personally recommend using uppercase for GET and POST whenever possible.
Going to try to keep it short. I have a while loop in grid.php file to fill up a table as such...
<?php while($product = $products->fetch_assoc()) { ?>
<tr>
<td><?php echo $product['cd_id']?></td>
<td><?php echo $product['cd_title']?></td>
<td><?php echo $product['cd_musician_fname']?></td>
<td><?php echo $product['cd_musician_lname']?></td>
<td><?php echo $product['cd_price']?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php } ?>
If I click the first anchor tag takes me to a edit.php file and here is the head code for that file.
<?php include '_includes/db.php';
$cd_id = trim($_GET['id']);
$message = '';
include '_includes/connection.php';
if($db->connect_error){
$message = $db->connect_error;
}else{
$sql = "SELECT * FROM CD WHERE cd_id = $cd_id";
$result = $db->query($sql);
$row = $result->fetch_assoc();
if($db->error){
$message = $db->error;
}
}
?>
Now I will show the html of edit.php
<!-- Product Musician last name-->
<fieldset class="form-group">
<label for="cd_musician_lname">Musician's lirst name</label>
<input type="text" class="form-control" id="cd_musician_lname" name="cd_musician_lname" value="<?php echo $row['cd_musician_lname'];?>">
</fieldset>
<!-- End of Musician last name-->
<!-- Product price-->
<fieldset class="form-group">
<label for="cd_price">Product price</label>
<input type="text" class="form-control" id="cd_price" name="cd_price" value="<?php echo $row['cd_price'];?>">
</fieldset>
<!-- End of Product price-->
<!-- Form submit button-->
Update Record
<a class="btn btn-primary" href="index.php" role="button">Go Back Home</a>
I have the edit.php page working just fine but if I make changes in the fields and click the submit anchor tag I get all the fields of the row empty but the PK. Here is the code for the final edit_confirm.php file
<?php
include '_includes/db.php';
$cd_id = trim($_GET['id']);
$cd_title = $_POST['cd_title'];
$cd_musician_fname = $_POST['cd_musician_fname'];
$cd_musician_lname = $_POST['cd_musician_lname'];
$cd_price = $_POST['cd_price'];
$message = '';
include '_includes/connection.php';
if($db->connect_error){
die("Connection failed: ".$db->connect_error);
} else {
$sql = "UPDATE CD SET cd_title='".$cd_title."', cd_musician_fname='".
$cd_musician_fname."', cd_musician_lname='".
$cd_musician_lname."', cd_price='".$cd_price."' WHERE cd_id = $cd_id ";
$db->query($sql);
var_dump($sql);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php include '_includes/main-head.php';?>
</head>
<body>
<?php include '_includes/main-navbar.php';?>
<div class="container">
<hr>
<?php
if($db->query($sql) === TRUE){ ?>
<h1>Record updated successfully.</h1>
<?php echo $cd_title; ?>
<?php echo $record->affected_rows ?>
<p> record was updated in the database.</p></br>
<?php } else { ?>
<p>Error updating the record: </p> <?php $db->error; ?>
<?php }; ?>
<hr>
<a class="btn btn-primary" href="index.php" role="button">Go Back Home</a>
</div>
<?php include '_includes/main-script.php';?>
</body>
</html>
If you notice in the edit_confirm.php I did a var_dump to see what are the values in the variables and it shows empty.
I need help with this.
Thank you in advance.
Man the better way to do this is make it simple to test if the record is updating or not
formsample.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
include("connection.php");
$id = $_GET['id'];
$query= "select * from clients where id = '$id'";
$sql = mysqli_query($connect, $query);
$result = mysqli_fetch_assoc($sql);
?>
<form action="process.php" method="post">
<input type="text" name="name" id="name" value="<?php echo $result['name'] ?>" />
<input type="text" name="email" id="email" value="<?php echo $result['email'] ?>" />
<input type="hidden" name="id" id="id" value="<?php echo $id?>" />
<input type="submit" />
</form>
</body>
</html>
process.php
<?php
include("connection.php");
$id = $_POST['id'];
$name = $_POST['name'];
$email= $_POST['email'];
$query = "UPDATE clients set name= '$name', email ='$email' where id = '$id'";
$sql = mysqli_query($connect, $query);
?>
Update Record
This is not the proper way to submit a form - it won't work at all.
You need to have a form opening and closing tag, the target address is in the action attribute of the form element, and the method is on there too and should be post for this form (method="POST"). In your code you have a link where you should have a submit input so it won't submit the data, it will just redirect you to that URL. You should have something like this:
<input type="submit" value="Update Record" />
http://www.w3schools.com/html/html_forms.asp
I really don't understand what I am doing here. I have this page profesor.php in which I want to insert some data into the database. After I submit the data from the form I want to be redirected to another page insert.php and display a message.
So I have profesor.php:
<?php
session_start();
if (isset($_SESSION['id'])) {
$fullname = $_SESSION['name'];
echo "<h1> Welcome " . $fullname . "</h1>";
} else {
$result = "You are not logged in yet";
}
if (isset($_POST['studname'])) {
include_once("dbConnect.php");
$studname = strip_tags($_POST['studname']);
$course = strip_tags($_POST['course']);
$grade = strip_tags($_POST['grade']);
$getStudidStm = "SELECT userid FROM users WHERE name = '$studname'";
$getStudidQuery = mysqli_query($dbCon, $getStudidStm);
$row = mysqli_fetch_row($getStudidQuery);
$studid = $row[0];
$_SESSION['studid'] = $studid;
$_SESSION['course'] = $course;
$_SESSION['grade'] = $grade;
header("Location: insert.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $fullname ;?></title>
</head>
<body>
<div id="wrapper">
<h2>Insert new grade</h2>
<form id="insertForm" action="insert.php" method="post" enctype="multipart/form-data">
Student: <input type="text" name="studname" /> <br />
Course : <input type="text" name="course" /> <br />
Grade : <input type="text" name="grade" /> <br />
<input type="submit" value="Insert" name="Submit" />
</form></div>
</form>
</body>
</html>
and insert.php
<?php
session_start();
if (isset($_SESSION['studid'])) {
include_once("dbConnect.php");
$studid = $_SESSION['studid'];
$course = $_SESSION['course'];
$grade = $_SESSION['grade'];
echo $studid;
echo $course;
echo $grade;
}
My problem is that insert.php doesn't display anything. I really don't understand what I'm doing wrong. Need some help.
your problem is in your form:
<form id="insertForm" action="insert.php" [...]
you send data to insert.php but all the 'magic' with
$_SESSION['studid'] = $studid;
$_SESSION['course'] = $course;
$_SESSION['grade'] = $grade;
you keep in profesor.php
Just change action="insert.php" to action="profesor.php" and it should work fine.
I'm trying to create a set of webpages that work together to allow users to view, delete, and edit rows of a MS Access database using PHP.
Membership.php shows a list of the names of members in the Access database. Their names are also hyperlinks that, when clicked, take users to another page EditRecord.php where all of information on the member whose name was clicked on Membership.php is displayed in text boxes with the option to completely delete the record, or just update certain fields.
Membership.php and EditRecord.php are displayed below. The error code is for line 91 of my source for EditRecord.php, but I cut some things out of this post for privacy. Instead, the line has been marked like so:
//--------This is the error line----------
code
[Membership.php]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Accounts.css">
<style type="text/javascript" src="Validate.js"></style>
<style type="text/javascript" scr="Redirect.js"></style>
<style type="text/javascript" src="Utilities.js"></style>
<title>Member Information Input</title>
</head>
<body>
<div id="content">
<?php
//Establish data connection using external file
require("connection.php");
//Issue SQL SELECT Statement
$sql = "SELECT * FROM Membership";
//Stores any results that match the search term.
$rs = odbc_exec($conn, $sql);
//Set counter for search results to zero
$results = 0;
//Iterates through search results and prints information on records that match
while($row = odbc_fetch_array($rs))
{
$results += 1;
echo '<p>' . $row['FirstName'] . " " . $row['LastName'] . "</p>";
}
?>
</div>
</body>
</html>
[EditRecord.php]
<?php
//Retrieve ID value - if the page is loading for the first time, use $_GET[]. If the
//delete or edit button has been clicked, use $_POST[]
if (isset($_GET['ID'])) {
$userID = $_GET['ID'];
}
else {
$userID=$_POST['ID'];
}
//Establish data connection
require("connection.php");
//If the Delete Button is clicked
if (isset($_POST['DelBtn'])) {
//Issue SQL Statement to Delete Selected Record
$sqlDelete = "DELETE FROM Membership WHERE ID = $userID";
//Execute the SQL Delete Query
$rsDelete = odbc_exec($conn,$sqlDelete);
if(odbc_num_rows($rsDelete) == 1) {
echo "Record successfully deleted!";
}
}
//If the Edit Button is clicked
else if (isset($_POST['EditBtn'])) {
//Collect form field values in scalar variables
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$State = $_POST['State'];
$Email = $_POST['Email'];
$Gender = $_POST['Gender'];
$Comments = $_POST['Comments'];
//Issue SQL Statement to Update Selected Record
$sqlUpdate = "UPDATE Membership SET FirstName = '$FirstName', LastName = '$LastName', Address = '$Address', City = '$City', State = '$State'" .
"Email='$Email', Gender = '$Gender', Comments = '$Comments' WHERE ID = $userID";
//Execute the SQL UPDATE Query
$rsEdit = odbc_exec($conn,$sqlUpdate);
if(odbc_num_rows($rsEdit) == 1) {
echo "Record successfully updated!";
}
}
//Issue SQL SELECT Statement to Select Record to Edit or Delete
$sql = "SELECT * FROM Membership WHERE ID = $userID";
//Execute the SQL Query
$rs = odbc_exec($conn, $sql);
odbc_close($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Accounts.css">
<style type="text/javascript" src="Validate.js"></style>
<style type="text/javascript" src="Utilities.js"></style>
<title>Member Information Input</title>
</head>
<body>
<div id="content">
<form method="post" action="EditMember.php" name="EditForm">
<?php
// Loop through and display the recordset returned by SELECT statement. Display the record values in HTML Text Boxes
**//--------This is the error line----------
while ($row = odbc_fetch_array($rs)) {
?>**
First Name: <input type="text" name="FirstName" value="<?php echo $row['FirstName']?>"><br>
Last Name: <input type="text" name="LastName" value="<?php echo $row['LastName']?>"><br>
Address: <input type="text" name="Address" value="<?php echo $row['Address']?>"><br>
City: <input type="text" name="Telephone" value="<?php echo $row['City']?>"><br>
State: <input type="text" name="Telephone" value="<?php echo $row['State']?>"><br>
Email: <input type="text" name="Email" value="<?php echo $row['Email']?>"><br>
Gender: <input type="text" name="Telephone" value="<?php echo $row['Gender']?>"><br>
Comments: <input type="text" name="Comments" value="<?php echo $row['Comments']?>"><br><br>
<input type="hidden" name="ID" value="<?php echo $row['ID']?>" >
<?php
}
?>
<input type="submit" name="EditBtn" value="Edit Record"> <input type="submit" name="DelBtn" value="Delete Record">
</form>
</div>
<div id="footer">
<?php require("Footer.php"); ?>
</div>
</body>
</html>
I also find this strange, because there are five records in my database, not four. Is that because it starts counting at zero?
Any insight or advice would be greatly appreciated.
Your problem is that you are calling odbc_close() and closing the connection before your loop calls odbc_fetch_array(). You need to leave the connection open until after you've fetched all of the rows.
Also, the "4" in the error message does not refer to a number of rows or anything like that; it's just the numeric representation of result identifier for the resource created by the odbc_exec() call.