MySQL-Update-Function Inserts New Row - php

I am working on a page updating database-entries. Should work, but it doesn't. Instead of updating data it creates a new entry.
Explanation: usually the code should let me update the existing entry. That's why I use WHERE c.id='$ceid'. But even though I am updating the entry with ID 15 I then have a new entry with the ID 16.
UPDATE customer AS c SET c.company='$company',
c.contractnumber='$contractnumber',
c.delivery='$delivery',
c.quit='$quit',
c.unsubscription='$quitdate',
c.alert='$alert'
WHERE c.id='$ceid'
So the MySQL-query is right so far as it seems.
So the problem must be somewhere else, before or after the query. Most likely it happens before the query as I used to outcomment the if(!emtpy...)-part. But what is it?
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script type="text/javascript" charset="utf-8" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<?
$link = mysqli_connect("server", "user", "pw", "db");
?>
<body>
<h1>Kundenansicht</h1>
<p>Kundennummer <?php echo $_GET["id"]; ?></p>
<p><?php echo $_GET["name"]; echo " "; echo $_GET["surname"]; ?></p>
<p>Vertrag <?php echo $_GET["cid"]; ?></p>
<?
$uid = $_GET["id"];
echo $uid;
echo "<br>";
$name = $_GET["name"];
$surname = $_GET["surname"];
$cid = $_GET["cid"];
echo "CID: ";
echo $cid;
echo "<br>";
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
mysqli_set_charset($link,"utf8");
$sql = "SELECT * FROM customer WHERE id ='".$cid."' AND custnumber = '".$uid."'";
$result = mysqli_query($link,$sql) or die (mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
<div id="AddContract" class="w3-container">
<form action="customerview.php?id=<? echo $uid ?>&name=<? echo $name ?>&surname=<? echo $surname ?>" method="post">
<label>ID</label> <!-- e.g. PluSStrom-->
<input class="w3-input w3-border" type="number" name="id" id="id" value="<? echo $row["id"]; ?>">
<label>Anbieter</label> <!-- e.g. PluSStrom-->
<input class="w3-input w3-border" type="text" name="company" id="company" value="<? echo $row["company"]; ?>">
<label>Vertragsnummer</label> <!-- Vertragsnummer-->
<input class="w3-input w3-border" type="number" name="contractnumber" id="contractnumber" value="<? echo $row["contractnumber"]; ?>">
<label>Lieferdatum</label> <!-- Kündigungsfrist in Wochen-->
<input class="w3-input w3-border" type="date" name="deliverydate" id="deliverydate" value="<? echo $row["delivery"]; ?>">
<label>Kündigungsfrist (Wochen)</label> <!-- Kündigungsfrist in Wochen-->
<input class="w3-input w3-border" type="number" name="quit" id="quit" value="<? echo $row["quit"]; ?>">
<label>Kündigungsdatum</label>
<input class="w3-input w3-border" type="date" name="qdate" id="qdate" value="<? echo $row["unsubscription"]; ?>">
<input type="submit" class='w3-btn w3-black' name="submit" value="Eintragen">
</form>
<?
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ceid = mysqli_real_escape_string($link, $_POST['id']);
$company = mysqli_real_escape_string($link, $_POST['company']);
$contractnumber = mysqli_real_escape_string($link, $_POST['contractnumber']);
$customernumber = $uid;
$quit = mysqli_real_escape_string($link, $_POST['quit']);
$quitdate = mysqli_real_escape_string($link, $_POST['qdate']);
$delivery = mysqli_real_escape_string($link, $_POST['deliverydate']);
$qd = $quit * 7;
$alert = mysqli_real_escape_string($link, date('Y-m-d', strtotime($quitdate. " - $qd days")));
if(isset($_POST['submit']))
{
if(!empty($customernumber) || !empty($contractnumber) ){
$sql_upd = "UPDATE customer AS c SET c.company='$company',
c.contractnumber='$contractnumber',
c.delivery='$delivery',
c.quit='$quit',
c.unsubscription='$quitdate',
c.alert='$alert'
WHERE c.id='$ceid'";
if (mysqli_query($link, $sql_upd)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
} else {
echo "ERROR: Nicht gespeichert. Kundennummer oder Vertragsnummer fehlen!";
}
}
// close connection
mysqli_close($link);
?>
</body>
</html>
Btw: I know working with get is not very safe. And the code isn't a beauty as I want to polish later, but struck with the problem above.

Have solved the problem. First, Ravi was right. Update can't create new entries. And insert did. Because I wanted to move to another page after submitting the form I abused action. Instead of using the update-code on the current page it went to the page referred to in action and added the data through the insert-code on this page.

Related

getting data by id from database after submitting to another page

I m trying to get data on another page by id which is on showdetails.php page.but i m unable to please help.
Showdetails.php
this page shows details of user with id and button which will allow user to edit details on another page
<!DOCTYPE html>
<html>
<head>
<title>Details</title>
</head>
<body>
<?php
require('database.php');
?>
<h1>User Lists</h1>
<?php
$select = "SELECT id, firstname, lastname FROM signup";
$selectdata = $conn->query($select);
if ($selectdata->num_rows > 0){
while($row = mysqli_fetch_array($selectdata)) {
$id = $row['id'];
$first = $row['firstname'];
$last = $row['lastname'];
?>
<form method="get" action="editdetails.php">
<p><b>ID: <?php echo $id; ?></b></p>
<p>Name: <?php echo $first; ?> <?php echo $last; ?></p>
<?php
$edit = "SELECT id FROM signup WHERE id= '" .$id. "'";
$selectedit = $conn->query($edit);
?>
<p><input type="submit" name="display" value="Edit Details"></p>
</form>
<?php
}
}
?>
</body>
</html>
editdetails.php
On this page, user will be able to edit details, and i want details by id
<!DOCTYPE html>
<html>
<head>
<title>Edit User Details</title>
</head>
<body>
<?php
require('database.php');
$select = "SELECT firstname, lastname, age, phone_no, age, username, password FROM signup";
$selectdata = $conn->query($select);
if ($selectdata->num_rows > 0){
$row = mysqli_fetch_array($selectdata);
$first = $row['firstname'];
$last = $row['lastname'];
$age = $row['age'];
$phone_no = $row['phone_no'];
$username = $row['username'];
$password = $row['password'];
}
?>
<?php
if (isset($_POST['update'])) {
# code...
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$age = mysqli_real_escape_string($conn, $_POST['age']);
$phone = mysqli_real_escape_string($conn, $_POST['phone_no']);
$username = mysqli_real_escape_string($conn, $_POST['user']);
$password = mysqli_real_escape_string($conn, $_POST['pass']);
$update = "UPDATE signup SET firstname= '$first', lastname= '$last', age= '$age', phone_no = '$phone', username = '$username', password = '$password' WHERE id= '$id'";
$updatedata = $conn->query($update);
if ($updatedata) {
# code...
echo $status = "Details Updated";
}
else {
# code...
echo $status = "Not Updated";
}
}
if (isset($_POST['delete'])) {
# code...
$delete = "DELETE FROM signup WHERE firstname = $first";
$deletedata = $conn->query($delete);
if ($deletedata) {
# code...
echo $status = "Details Deleted";
}
else {
# code...
echo $status = "Not Deleted";
}
}
?>
<h1>Edit Details</h1>
<form method="post" action= "<?php htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<p>FirstName: <input type="text" name="first" value="<?php echo $first; ?>"></p>
<p>LastName: <input type="text" name="last" value="<?php echo $last; ?>"></p>
<p>Phone no: <input type="number" name="phone_no" value="<?php echo $phone_no; ?>"></p>
<p>Age: <input type="number" name="age" value="<?php echo $age; ?>"></p>
<p>User: <input type="text" name="user" value="<?php echo $username; ?>"></p>
<p>Password: <input type="password" name="pass" value="<?php echo $password; ?>"></p>
<p><input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete"></p>
</form>
<p><?php echo $status; ?></p>
</body>
</html>
Thank You.
Add in your HTML form a hidden input, like so:
<input type="hidden" name="id" value="<?php echo $id; ?>">
Then in your editdetails.php file you can access it with: $_GET["id"].
Update:
Add the hidden input to the form in Showdetails.php.
Then in editdetails.php add at the top of the page $id = (int)$_GET["id"];
Then add to your SELECT query in editdetails.php a WHERE statement for selecting the correct user:
$select = "SELECT ... FROM signup WHERE id = $id";
For the update query you are then good to go since you are already using there WHERE id = $id. (but before your $id variable was not defined)

PHP form, converting input field into a drop down list

The below code is a simple form that is sending the data that is inputted to my local database.
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="school" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
<!-- Right side div -->
</div>
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
</body>
</html>
The issue that I am finding is that I am trying to change the Student City input field into a drop down where the values is retrieve from the database and put into a drop down list for a new user to select.
Could someone advise on what needs to be done please.
i am trying to use the below code and send the below list to my database.
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
<option value="France">France</option>
<option value="Mexico">Mexico</option>
but i am finding it hard to send the these values to the database with my above code as well as where to place this code.
As a rough example of how you could build the dropdown menu using data from your db this should give you the general idea perhaps.
/* store formatted menu options in temp array */
$html=array();
/* query db to find schools/cities */
$sql='select distinct `student_school` from `students` order by `student_school`';
$res=$mysqli_query( $conn, $sql );
/* process recordset and store options */
if( $res ){
while( $rs=mysqli_fetch_object( $res ) ){
$html[]="<option value='{$rs->student_school}'>{$rs->student_school}";
}
}
/* render menu */
echo "<select name='stu_city'>", implode( PHP_EOL, $html ), "</select>";
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
if ($conn->query ( $sql ) === TRUE) {
$cities = ... // build the cities from the query result
} else {
$cities = '<option value="none">No cities found</option>' ;
}
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple><?php echo $cities; ?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>
Use the Select tag: Lets say you hav a column in your database with Student City, like this, lets say the database field is called city
City 1
City 2
City 3
Step 1: Query the database and fetch all the Cities
$sql = "SELECT city FROM table_name";
$result = $conn->query($sql);
Then you come to your dropdown:
<select name="stu_city" id="..." required>
<?php
while($cities = $conn->fetch_array($result){
extract($cities);
echo "<option value='...'>$city</option>";
}
?>
</select>
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
$result = $conn->query ( $sql );
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple>
<?php
if ($result == TRUE) {
while($cities = $conn->fetch_array($result)){
extract($cities);
echo "<option value=''>$city_name</option>";
}
}
else {
echo "<option value='none'>No cities found</option>";
}
?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>

Insert data mysqli and php in form 1 and return to new form 2

Hi all I am new to mysqli and php (currently studying and trying to work on a test database- I have not used security measures at this wont be available public) and trying to get the information I have just submitted in the form to display in a new form which will then receive further user input then submitted to database. Here is an example of what I have done so far:
Form 1 (customer table - cust id =primary key)
Customer Details ie name address telephone etc
dynamic drop down box - consists of 4 options.( would like whatever option is selected here to return a particular form)
The form is currently submitting correctly in the database, but I would like once it has submitted to the database to return the customer info (including the customer id as that is the relationship in the new table) and on the form2(service table - service id is primary key) so the user can input further data to the form and submit.
Hope this makes sense, any help would be appreciated.
Thanks
Response 1
Thank you for my response I probably havent made myself very clear.
Form 1 where dynamic dropdown list is - when user submits forms I would like it to return form 2 with the customer info we inserted in form 1
Form 1
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>test</title>
</head>
<body>
<form action="newbookingcode.php" method="post">
<p>First Name: <input type="text" name="firstname"/>
Last Name: <input type="text" name="lastname"/></p>
<p>Business Name: <input type="text" name="businessname"/></p>
<p>Contact Number: <input type="text" name="number"/>
Alt Number: <input type="text" name="altno"></p>
<p>Email Address:<input type="text" name="email"></p>
<p>Street No:<input tyep="text" name="streetno">
Street Name:<input type="text" name="street"></p>
<p>Suburb:<input type="text" name="suburb">
Postal Code:<input type="text" name="postalcode">
State: <input type="text" name="state"></p>
**<p>Type of Service Required: <select id="category" name="category" >
<option value="nill">---Select Service---</option**
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM serviceType";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value= "'.$row['jobType'].'" >' . $row['jobType'] . '</option>';
}
} else {
echo "0 results";
}
$conn->close();
?>
</p>
</select>
<p>
<input type="submit"/>
</p>
</form>
</body>
</html>
Query in separate file
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType)
VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Check this code and let me know if you have any questions:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM serviceType";
$result = $conn->query($sql);
/************** IMPORTANT *************/
$whichForm = 1;//to know which form to show
$last_customer_id = 0;//to store last customer id
//to store your customer information
$fname=$lname=$bname=$phone=$altphone=$email=$streetno=$street=$suburb=$postcode=$state=$service='';
//To handle post operations after clicking on post.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$whichForm = 2; // to show second form
//if it is first form
if($_POST['action'] == 'firstForm')
{
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];
//Preparing your insert query
$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType) VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";
$conn->query($sql); //insert into db
//get last insert customer id and you already have your customer information
//in the variables above $fname, $lname.....etc
$last_customer_id = $conn->insert_id;
}
else{//do something with your second form
//get last customer info
$sql = "SELECT * FROM serviceType where id = ".$POST_['last_customer_id']."";
$result = $conn->query($sql);
$res = $result->fetch_assoc();
//you can access customer information like res['contactFirstName']
}
}
$conn->close(); //close your connection
?>
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>test</title>
</head>
<body>
<?php
if($whichForm == 1){ //if it is first form
?>
<form id="1" action="test2.php" method="post">
<!-- This input is needed to identify which form -->
<input type="hidden" name="action" value="firstForm" />
<p>First Name: <input type="text" name="firstname" value="<?php echo $fname; ?>"/>
Last Name: <input type="text" name="lastname" value="<?php echo $lname; ?>" /></p>
<p>Business Name: <input type="text" name="businessname" value="<?php echo $bname; ?>"/></p>
<p>Contact Number: <input type="text" name="number" value="<?php echo $phone; ?>"/>
Alt Number: <input type="text" name="altno" value="<?php echo $altphone; ?>"></p>
<p>Email Address:<input type="text" name="email" value="<?php echo $email; ?>"></p>
<p>Street No:<input tyep="text" name="streetno" value="<?php echo $streetno; ?>">
Street Name:<input type="text" name="street" value="<?php echo $street; ?>"></p>
<p>Suburb:<input type="text" name="suburb" value="<?php echo $suburb; ?>">
Postal Code:<input type="text" name="postalcode" value="<?php echo $postcode; ?>">
State: <input type="text" name="state" value="<?php echo $state; ?>"></p>
**<p>Type of Service Required: <select id="category" name="category" >
<option value="nill">---Select Service---</option>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//this if to save the value of the selected category
if($row['jobType'] == $service)
{
echo '<option value= "'.$row['jobType'].'" SELECTED>' . $row['jobType'] . '</option>';
}
else
{
echo '<option value= "'.$row['jobType'].'">' . $row['jobType'] . '</option>';
}
}
}
?>
</select></p>
<button type="submit">Submit</button>
</form>
<?php
}//ending bracket for if($whichForm == 1)
else if($whichForm == 2){ // or just else will do fine
?>
<form id="2" action="test2.php" method="post">
<!-- This input is needed to identify which form -->
<input type="hidden" name="action" value="secondForm" />
<!-- This input is needed to store the last customer id -->
<input type="hidden" name="last_customer_id" value="<?php echo $last_customer_id; ?>" />
<!-- here you put your second form -->
<button type="submit">Submit</button>
</form>
<?php
}//ending bracket for else if($whichForm == 2)
?>
</body>
</html>
Assuming you are using a database object like mysqli to do DB interactions.
Say form1 generate insert query $insertQyery.
And you are executing this query (insert statement) like
$mysqli->query($insertQyery);
After the execution of this insert statement you can use
$customerId = $mysqli->insert_id
Now using this $customerId you can show records details on form2 or use this $customerId as reference on form2.
After customer submit FORM #1
on the next page
let's get the last customer details :-
<?php
//after mysqli connection
$contactFirstName = '';
$contactLastName = '';
$businessName = '';
$sql_get_data = "SELECT * FROM customer ORDER BY customerID DESC limit 1 ";
$query_get_data = mysqli_query($conn, $sql_get_data);
while ($row = mysqli_fetch_array($query_get_data, MYSQLI_ASSOC)) {
//specify which data you want to get from "customer" table
$contactFirstName = $row['contactFirstName'];
$contactLastName = $row['contactLastName'];
$businessName = $row['businessName'];
}
?>
HTML Form#2 :-
<form id="form2" method="post">
<input type="text" value="<?php echo 'contactFirstName'; ?>"
<input type="text" value="<?php echo 'contactLastName'; ?>"
<input type="text" value="<?php echo 'businessName'; ?>"
</form>
Hope this answer will help you.

Big Issues with getting a profile update page to update the databse

I've got a big issue with my website. I've made a profile page which will allow users to amend their details, and then submit. Upon submitting the details should be updated in the database, however I just get a blank page and nothing happens. I've been up for 30+ hours trying to figure things out but no luck. It's likely to be screwed up, as now is my brain.
Any help would be GREATLY appreciated.
Profile amend page:
<?php
session_start();
if (!isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
<!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>Index</title>
<link href="External style sheet layout.css" rel="stylesheet" type="text/css" />
<h1><?php echo date("D M d, Y G:i a"); ?>
<?php $welcome = 'Hi';
if (date("H") < 12) {
$welcome = 'Good Morning';
} else if (date('H') > 11 && date("H") < 18) {
$welcome = 'Good Afternoon';
} else if(date('H') > 17) {
$welcome = 'Good Evening';
}
echo $welcome;
?></h1>
<div class="Login">
<h3><ul>
<?php if(isset($_SESSION['authenticatedUser']) && $_SESSION['authenticatedUser'] != null ) {?>
<li>Welcome <?php echo $_SESSION["authenticatedUser"] ?></li>
<li><span>Log Out</span></li>
<?php } else {?> <li><span>Log In</span></li> <?php } ?>
<li>Register</li>
<li>Basket</li>
</ul></h3>
</div>
</head>
<body>
<div id="container">
<div id="header">
<img src="Images/Schurter3.jpg" width="800" height="300" alt="Schurter" />
</div>
<div id="navigation">
<ul id="navbar">
<li>Home</li>
<li>Components
<ul>
<li>Circuit Protection
<li>Connectors</li>
<li>Switches</li>
<li>EMC Products</li>
<li>Other Products</li>
</ul>
</li>
<li>Electronic Manufacturing Services
<ul>
<li>Application Examples</li>
<li>Processes</li>
</ul>
</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
<?php
include 'db.inc';
//Check to see if a customer ID has been passed in the URL
$memberID = $_GET["memberID"];
// Has a custID been provided? If so, retrieve the customer
// details for editing.
if (!empty($memberID))
{
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databasename) or die ("Unable to select database!");
$query = "SELECT * FROM members WHERE id = " . $memberID;
//Get the recordset
$recordSet = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$row = mysql_fetch_assoc($recordSet);
//Check for errors
//if (!$recordSet)
// print $connection->ErrorMsg();
// else
// {
// Load all the form variables with customer data
$Firstname = $row['Firstname'];
$Surname = $row['Surname'];
$Emailaddress = $row['Emailaddress'];
$Username = $row['Username'];
$Password = $row['Password'];
// }//End else
}
?>
<form name="RegisterForm" action="ProfileUpdate.php" method="post" >
<input type="hidden" name="memberID" value="<?php echo $memberID;?>">
<label>First name*</label>
<input name="Firstname" placeholder="Enter first name here" value="<?php echo $Firstname;?>" required/>
<label>Surname*</label>
<input name="Surname" placeholder="Enter surname here" value="<?php echo $Surname;?>" required/>
<label>Email*</label>
<input name="Emailaddress" type="email" placeholder="Enter email here" value="<?php echo $Emailaddress;?>" required/>
<label>Username*</label>
<input name="Username" type="text" placeholder="Enter a desired username" value="<?php echo $Username;?>" required/>
<label>Password*</label>
<input name="Password" type="password" placeholder="Enter a desired password" value="<?php echo $Password;?>" required/>
<input id="submit" name="submit" type="submit" value="Update Details">
</form>
</body>
</html>
And this is the update action page:
<?php
require('db.inc');
$memberID = $_GET["id"];
echo $memberID;
// trim the POSTed values - gets rid of unecessary whitespace
$Firstname = $_POST['Firstname'];
$Surname = $_POST['Surname'];
$Emailaddress = $_POST['Emailaddress'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
//Here we use validation at the server
// Vaildate the firstname
?>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head><title>Customer Details Error</title></head>
<body bgcolor="white">
<h1>Customer Details Error</h1>
<?=$errorString?>
<br>Return to the customer form
</body>
</html>
<?php
// If we made it here, then the data is valid
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databasename) or die ("Unable to select database!");
// this is an update
if (!empty($memberID))
{
$query = "UPDATE members SET ".
"Firstname = '$Firstname', Surname = '$Surname', " .
"Emailaddress = '$Emailaddress', Username = '$Username', Password = '$Password', " .
" WHERE id = $memberID";
$recordSet = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
echo "Your updates are complete!";
}
?>
<?php
session_start();
if (!isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
Fix this one to:
<?php
session_start();
if (isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
The first one is wrong, it checks for a username if there is no username then it displays the username else it doesnt.
On-topic:
<form name="RegisterForm" action="ProfileUpdate.php" method="post" >
Change the above line to:
<form name="RegisterForm" action="ProfileUpdate.php?id=<?php echo $memberID ?>" method="post" >
As your profileUpdate.php is requesting a member ID, this is necessary and after this, the code should work!

Apparently no error in update query but the record is not updated [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
this is my code for usersedit.php and the other one is for users-edit-action.php
after updating its saying that the data is succfully updated but it doesnot change anything in mysql.. please help me figureout the problem, thankyou
users-edit.php
<?php include("../includes/config.php"); ?>
<?php
if ($_SESSION["isadmin"])
{
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
$accountid=$_GET["id"];
$result = mysql_query("SELECT * FROM accounts WHERE (id='".$accountid."')");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$email=$row['email'];
$type=$row['type'];
}
mysql_close($con);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Edit User</title>
<link rel="StyleSheet" href="../admin/css/style.css" type="text/css" media="screen">
</head>
<body>
<?php include("../admin/includes/header.php"); ?>
<?php include("../admin/includes/nav.php"); ?>
<?php include("../admin/includes/manage-users-aside.php"); ?>
<div id="maincontent">
<div id="breadcrumbs">
Home >
Manage Users >
List Users >
Edit User
</div>
<h2>Edit User</h2>
<form method="post" action="users-edit-action.php">
<input type="hidden" value="<?php echo $accountid; ?>" name="id" />
<label>Email/Username:</label><input type="text" name="email" value="<?php echo $email; ?>" /><br /><br />
<label>Password:</label><input type="password" name="password" value="<?php echo $password;?>" /><br /><br />
<label>First Name:</label><input type="text" name="firstname" value="<?php echo $firstname; ?>" /><br /><br />
<label>Last Name:</label><input type="text" name="lastname" value="<?php echo $lastname; ?>" /><br /><br />
<label>Type:</label><br />
<input type="radio" name="type" value="S" <?php if ($type == 'S') echo 'checked="checked"'; ?> />Student<br />
<input type="radio" name="type" value="T" <?php if ($type == 'T') echo 'checked="checked"'; ?> /> Teacher<br />
<input type="submit" value="Edit" />
</form>
</div>
</body>
<?php include("../admin/includes/footer.php"); ?>
</html>
<?php
} else
{
header("Location: ".$fullpath."login/unauthorized.php");
}
?>
this is users-edit-action.php
<?php include("../includes/config.php");?>
<?php
$id=$_POST["id"];
$firstname=$_POST["firstname"];
$lastname=$_POST["lastname"];
$email=$_POST["email"];
$type=$_POST["type"];
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
$query=("UPDATE accounts SET firstname='".$firstname."' , lastname='".$lastname." ,password='".$password."' , email='".$email."' type='".$type."' WHERE (id='".$id."')");
$result = mysql_query($query);
echo "User has been updated Successfully!!";
mysql_close($con);
?>
please help me figure out and solve the problem
Escape column names that is a reserved keyword of MySQL
$query=("UPDATE accounts
SET firstname='" . $firstname . "' ,
lastname='" . $lastname . " ,
`password`='" . $password . "' ,
email='" . $email . "' , // <== forgot comma
type='" . $type . "' WHERE (id='".$id."')
");
Password should be escaped.
You forgot to add comma between email and type.
Your current query is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$query = "UPDATE accounts
SET firstname = ?,
lastname = ?,
`PassWord` = ?,
email = ?,
type = ?
WHERE id = ?
";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $firstname);
$stmt->bindParam(2, $lastname);
$stmt->bindParam(3, $password);
$stmt->bindParam(4, $email);
$stmt->bindParam(5, $type);
$stmt->bindParam(6, $id);
$stmt->execute();
echo ($stmt) ? "Successful" : "Error Occured";
?>
this will allow you to insert records with single quotes.

Categories