Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this form which is meant to take in user input then once submit is pressed it stores the values in the database. For some reason upon pressing submit the user is redirected to the view page but the data is not inserted in the database.
Here is the Add Record Code:
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connection.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($memberID = '', $username = '', $password ='', $firstname ='', $lastname ='', $address ='', $email ='', $error = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($memberID != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($memberID != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solmemberID red; color:red'>" . $error
. "</div>";
} ?>
<form action= "" method="post">
<div>
<?php if ($memberID != '') { ?>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>" />
<p>MemberID: <?php echo $memberID; ?></p>
<?php } ?>
<strong>Username: *</strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
<strong>Password: *</strong> <input type="password" name="password" value="<?php echo $password; ?>"/><br/>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>"/><br/>
<strong>Address: *</strong> <input type="text" name="address" value="<?php echo $address; ?>"/><br/>
<strong>Email: *</strong> <input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
NEW RECORD
*/
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$username = htmlentities($_POST['username'], ENT_QUOTES);
$password = htmlentities($_POST['password'], ENT_QUOTES);
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
$address = htmlentities($_POST['address'], ENT_QUOTES);
$email = htmlentities($_POST['email'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($username == '' || $password == '' || $firstname == '' || $lastname == '' || $address == '' || $email == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($username, $password, $firstname, $lastname, $address, $email, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT into members (username, password, firstname, lastname, address, email) VALUES (?, ?, ?, ?, ?, ?)"))
{
$stmt->bind_param($username, $password, $firstname, $lastname, $address, $email, $error, $memberID);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
Here is the view page:
<!DOCTYDOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>View Records</h1>
<p><b>View All</b> | View Paginated</p>
<?php
// connect to the database
include('connection.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM members ORDER BY memberID"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>memberID
</th><th>username
</th><th>password
</th><th>firstname
</th><th>lastname
</th><th>address
</th><th>email";
while ($row = $result->fetch_object())
//print "<pre>"; print_r($row); exit;
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->memberID . "</td>";
echo "<td>" . $row->username . "</td>";
echo "<td>" . $row->password . "</td>";
echo "<td>" . $row->firstname . "</td>";
echo "<td>" . $row->lastname . "</td>";
echo "<td>" . $row->address . "</td>";
echo "<td>" . $row->email . "</td>";
echo "<td><a href='edit.php?memberID=" . $row->memberID . "'>Edit</a></td>";
echo "<td><a href='delete.php?memberID=" . $row->memberID . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
Add New Record
</body>
</html>
The first error is the bind_param called with incorrect arguments. See the documentation of mysqli_stmt_bind_param
An other error is the number of params to bind required (by the sql query you build with prepare() which differs from how many you bind with bind_param.
I also suggest you to replace the line $stmt->***; to add more error checkpoint
$res = $stmt->bind_param(/* correct your code according to the doc :) */);
if (!$res)
echo 'error when binding params : '.$stmt->error;
else
{
$res = $stmt->execute();
if (!$res)
echo 'error at stmt->execute() '.$stmt->error;
}
You need to tell the datatypes like so:
$stmt->bind_param("sssssssi", $username, $password, $firstname, $lastname, $address, $email, $error, $memberID);
that is assuming all are strings except the id which i assume is integer
Related
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.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I have reviewed the code and everything appears right so I am not sure what is wrong. I keep getting the following error s1s01 1136 column count does match.
I believe I used all the correct security codes please note if I did not thank you.
<?php
include ('wording/en-translation.php');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<?php
// define variables and set to empty values
$user_nameErr = $user_emailErr = "";
$user_name = $user_email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_name"])) {
$user_nameErr = "Name is required";
} else {
$user_name = mysql_real_escape_string($_POST["user_name"]);
//check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/",$user_name)) {
$user_nameErr="Only letters and white spaces allowed";
}
}
if (empty($_POST["user_email"])) {
$user_emailErr = "Email is required";
} else {
$user_email = mysql_real_escape_string($_POST["user_email"]);
//check if email is well-formed
if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
$user_emailErr = "Invalid Email Format";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user_name = mysql_real_escape_string($_POST["user_name"]);
$user_email = mysql_real_escape_string($_POST["user_email"]);
}
function mysql_real_escape_string($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="user_name"><?php echo WORDING_REGISTRATION_USERNAME; ?></label>
<input id="user_name" type="text" pattern="[a-zA-Z0-9]{2,64}" value="<?php echo $user_name; ?>" name="user_name" required />
<span class="error">* <?php echo $user_nameErr;?></span><br>
<label for="user_email"><?php echo WORDING_REGISTRATION_EMAIL; ?></label>
<input id="user_email" type="email" name="user_email" value="<?php echo $user_email; ?>" required />
<span class="error">* <?php echo $user_emailErr;?></span>
<input type="submit" name="register" value="<?php echo WORDING_REGISTER; ?>" />
</form>
<?php
echo $user_name;
echo "<br>";
echo $user_email;
echo "<br>";
?>
<?php
$servername = "localhost";
$username = "admin";
$password = "";
$dbname = "login";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(user_name, user_email)
VALUES(
". mysql_real_escape_string($user_name) ."',
". mysql_real_escape_string($user_email) ."'
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
</
You're generating broken SQL, by having completely WRONG quoting on your values:
$sql = "INSERT INTO users(user_name, user_email)
VALUES(
". mysql_real_escape_string($user_name) ."',
^---start sql string
". mysql_real_escape_string($user_email) ."'
^---end of sql string
)";
That means you're generating
INSERT INTO users (user_name, user_email) VALUES (Bob, 'bob#example.com')
^--unknown field
you're also mixing mysql libraries, which is flat out IMPOSSIBLE, and you're vulnerable to sql injection attacks.
In short, this code is totally cargo-cult programming, and you really need to sit back and learn PHP properly.
Code as of 20 January 2014
<?php
session_start();
// connect to the database
include('connect.php');
$message = $_GET['message'];
// check if the form has been submitted then process it
if (isset($_POST['submit']))
{
// Get data from table
//set the id manually for test purposes
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check for empty fields and display error message
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
$message = "Please enter data in all fields" ;
header("Location: edit.php?message=$message");
}
else
{
// save the data to the table
mysql_query("UPDATE registration SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
}
// redirecr and display message
$message = "Your changes have been saved";
header("Location: edit.php?message=$message");
exit;
}
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM registration WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from the table
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
//dummy echo
print $message;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/all.css" />
<link rel="stylesheet" href="styles/forms.css" />
<script type="text/javascript" src="javascript/jquery-1.7.1.min.js"></script>
<link href='//fonts.googleapis.com/css?family=Cantora+One' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Voltaire' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Ubuntu:400,500' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
</head>
<div class="container">
<form action="" method="post" enctype="multipart/form-data" name="edit" id="editrecord">
<fieldset>
<legend><span class="headingreg">Edit Details</span></legend>
<div class="formreg">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<br style="clear:left;"/>
<label for="forename">Forename</label><div><input type="text" id="forename" name="forename" class="insetedit" value="<?php echo $forename; ?>"/><br/></div>
<label for="forename">Surname</label><div><input type="text" name="surname" class="insetedit" value="<?php echo $surname; ?>"/><br/></div>
<label for="forename">Username</label><div><input type="text" name="username" class="insetedit" value="<?php echo $username; ?>"/><br/></div>
<label for="forename">Password</label><div><input type="text" name="password" class="insetedit" value="<?php echo $password; ?>"/><br/></div>
<label for="forename">email</label><div><input type="text" name="email" class="insetedit" value="<?php echo $email; ?>"/><br/></div>
<input type="submit" name="submit" class="submit2" value="submit">
</div>
</fieldset>
</form>
<br style="clear:left;"/>
<br style="clear:left;"/>
</body>
</html>
INDENTS REMOVED
I am following a tutorial for editing and deleting stored records in a database.
http://www.falkencreative.com/forum/records/view.php
In the tutorial one page displays the records in a database and another is used to edit the records :
http://www.falkencreative.com/forum/records/edit.php?id=33004
The problem is all the records in the database are displayed. What changes do I need to make so that I can display and edit a record based on a specified id on a single page? e.g.
$id = "429";
Eventually I will use sessions but for testing purpose I want to set the id manually.
I tried putting the code in a single page but got numerous errors e.g. headers already sent.
Here's the edit.php page with my attempt to set the id manually.
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $forename, $surname, $username, $password, $email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Forename: *</strong> <input type="text" name="forename" value="<?php echo $forename; ?>"/><br/>
<strong>Surname: *</strong> <input type="text" name="surname" value="<?php echo $surname; ?>"/><br/>
<strong>Username: *</strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
<strong>email: *</strong> <input type="text" name="password" value="<?php echo $password; ?>"/><br/>
<strong>password: *</strong> <input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check that forename/surname fields are both filled in
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $forename, $surname, $username, $password, $email, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE login SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
// show form
renderForm($id, $forename, $surname, $username, $password, $email, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
And the view.php page :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM login")
or die(mysql_error());
// display data in table
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Forename</th> <th>Surname</th> <th>Username</th> <th>eMail</th> <th>Password</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['forename'] . '</td>';
echo '<td>' . $row['surname'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['password'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
REMOVED FUNCTION AND ERROR VARIABLE
<?php
include('connect.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check empty fields
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
// generate error message
echo 'ERROR: Please fill in all required fields!';
}
else
{
// save the data to the database
mysql_query("UPDATE registration SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
// Redirect
echo "Your changes have been saved";
header("Location: edit.php");
}
}
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM registration WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
//dummy echo
echo 'formatting is messed up';
}
?>
You will just need to replace the $_GET['id'] with the code that provides the id.
If you are using sessions for example, replace $_GET['id'] with $_SESSION['id']
In your code from the file edit.php:
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
Change to:
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
Of course, in order to get to the point of executing that code, you would need to remove the conditional statements, since you are no longer getting the information from the $_GET.
I also added a LIMIT 1 to the query, so that you only return one record; you probably would anyway, but if id didn't have a unique index (such as a primary key), it may return multiple records.
Also, in this example, you could nearly replace all of the deprecated mysql_ references with mysqli_. It won't protect you the way mysqli can with prepared statements, but it still should work.
Finally, the renderForm function is a poorly formed function. You can only have one <html> declaration per page, and if you called the function more than once, it would have multiple declarations.
So im trying to have a user update their profile from update.php and then display it in userprofile.php but I am getting the error :"Cannot update: Duplicate entry 'username' for key 1". Ive tried to find a solution but im pretty stuck. Any help would be appreciated.
Here is update.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>
<title>User Profile Update</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php
session_start();
if(!isset($_SESSION['logged']) || $_SESSION['logged'] = TRUE)
{
$userError = "Error! Invalid Username.";
$passError = "Error! Invalid Password.";
$emailError = "Error! Invalid Email.";
$conError = "Error! Passwords do not match.";
$errorCheck = false;
$regex = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
if (isset($_POST['update']))
{
if(empty($_POST["firstName"])){
echo $userError;
$errorCheck = True;
}
elseif(empty($_POST["lastName"])){
echo $passError;
$errorCheck = True;
}
elseif(empty($_POST["userName"])){
echo $userError;
$errorCheck = True;
}
elseif(empty($_POST["pass"])){
echo $passError;
$errorCheck = True;
}
elseif(preg_match($regex, $_POST["email"]) != 1) {
echo $emailError;
$errorCheck = True;
}
elseif($_POST["pass"] != $_POST["pass2"]){
echo $conError;
$errorCheck = True;
}
elseif($_POST["address"] != $_POST["address"]){
echo $conError;
$errorCheck = True;
}
if(isset($_POST['update']) && (!$errorCheck)){
$user="bparis";
$pass="soccerguy998";
$database="bparis";
$passwordSub=$_POST["pass"];
$encrypted_mypassword=md5($passwordSub);
$con=mysql_connect("localhost", $user, $pass)
or die ('Couldnt connect to server');
mysql_select_db($database,$con)
or die('could not connect to db');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$key_id = $_POST["userName"];
$key_id2 = $_POST["email"];
//$location = $_POST['location'];
update($key_id2);
}else
{
userupdate();}
}else
{userupdate();}
}else
{ //if no user is logged in, display error
echo "<h1>Access denied</h1>";
echo "<h3><a href=login.php>Click here to login</a></h3>";
}
?>
<?php
function update($email){
$_SESSION['email'] = $email;
$sQry = "SELECT email FROM members WHERE email = " . (int)$_SESSION['email']; // Int userid
$obQry = mysql_query($sQry) or die(mysql_error()); // Shortcut, bad but usable
if (mysql_num_rows($obQry) == 1)
{
// Single record exists:// EDIT USER_PROFILE
$sReplace = "UPDATE members (username,password,email,firstName,lastName,address) VALUES('$_POST[userName]','$encrypted_mypassword','$_POST[email]','$_POST[firstName]','$_POST[lastName]','$_POST[address]')";
// Remember, I assumed that email is an integer!
}
else
{
$passwordSub=$_POST["pass"];
$encrypted_mypassword=md5($passwordSub);
$sReplace = "INSERT INTO members (username,password,email,firstName,lastName,address) VALUES('$_POST[userName]','$encrypted_mypassword','$_POST[email]','$_POST[firstName]','$_POST[lastName]','$_POST[address]')";
}
$obUpdate = mysql_query($sReplace) or die('Cannot update: ' . mysql_error());
if($obUpdate){
$subject = "Profile updated ";
$message = "You have updated your profile with Belfort Furniture. If not please contact customer service at : 703-406-7600";
$Belfortemail = "akomala.akouete#belfortfurniture.com";
echo "<b>profile updated</b>";mail($email, $subject,$message, "From:" . $Belfortemail);}else{
echo "Try update again";}
}
?>
<?php
function userupdate(){
?>
<table>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<h1>Profile Update</h1>
<hr>
<tr><td>First Name:</td><td>
<input type="text" name="firstName" maxlength="20">
</td></tr>
<tr><td>Last Name:</td><td>
<input type="text" name="lastName" maxlength="20">
</td></tr>
<tr><td>Username:</td><td>
<input type="text" name="userName" maxlength="20">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="20">
</td></tr>
<tr><td>Confirm Password:</td><td>
<input type="password" name="pass2" maxlength="20">
</td></tr>
<tr><td>Email:</td><td>
<input type="text" name="email" maxlength="50">
</td></tr>
<tr><td>Address:</td><td>
<input type="text" name="address" maxlength="100">
</td></tr>
<!--<tr>
<td class="right">address 1: </td>
<td><input type="text" name="location" value="" size="60" /></td>
</tr>-->
<tr><th colspan=2><input type="submit" name="update" value="UPDATE"></th></tr>
</form>
</table>
<?php
echo "<br><h3><a href=usersProfile.php>View your profile</a></h3>";
}
?>
</body>
</html>
and here is userprofile.php
<?php
session_start();
# DB INFO #
$user="xxxx";
$pass="xxxxx";
$database="xxxxx";
$con=mysql_connect("localhost", $user, $pass)
or die ('Couldnt connect to server');
mysql_select_db($database,$con)
or die('could not connect to db');
$result = mysql_query("SELECT userName,email,firstName,lastName,address FROM members") or die(mysql_error());
showpUsers($result);
function showpUsers($result)
{
?>
<table border="1">
<tr>
<?php
$headings = array("Usernam","Email","First Name","Last Name","Address");
foreach($headings as $info) {
echo "<th border='1'>" . $info . "</th>";
}
?>
</tr>
<?php
if(count($result)>0){
$list = array("username","email","firstName","lastName","address");
//while($data = mysql_fetch_row($result)){
$data = $result;
echo "<tr border='1'>";
for($i=0;$i<count($data);$i++) {
echo "<td border='1'>" . $data[$i] . "</td>";
}
echo "</tr>";
//}
}else{
echo "<b>Empty users list</b>";
}
?>
</table>
<?php
}
echo "<a href=update.php><button type='button'>USER UPDATE</button> </h1>";
?>
<hr/>
<br/>
<h3>Return Home Page</h3>
There are two situations I can see that might cause this:
You have two or more rows in the database with the same username, and your INSERT statement is being called. Check for this explicitly by only calling this block if the number of rows returned was 0. At the moment you aren't testing for it at all.
Your username is the PRIMARY KEY for the table. In this case you should alter your table so that it has a unique auto_incrementing primary key.
Oh, and rewrite the whole thing to fix the massive SQL injection vulnerabilities. Don't let this code anywhere near a public web site in the state it's in.
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.