I have directory entry form where I can add and edit users in the directory. I am able to view existing users and all the attributes but when I enter new user data or edit the existing user data, I am unable to make changes on Database. Let me know if given information is not sufficient
case "submit":
//user clicked the "submit" button on either the "edit record" page or "add new record" page.
$id=$_POST['ID'];
$FName=$_POST['Fname'];
$LName = $_POST['Lname'];
$Position =$_POST['position'];
$Phone=$_POST['phone'];
$Email=$_POST['email'];
$Site = $_POST['site'];
$Room=$_POST['room'];
$Bio=$_POST['bio'];
$Status=$_POST['status'];
$DeptID=$_POST['DeptID'];
$SortOrder=$_POST['SortOrder'];
$Image = $_FILES['image']['name'];
$Old_image = $_POST['old_image'];
$edit=$_POST['edit'];
if($Image == '')
$Image=$Old_image;
if($edit) {
//user came from the "edit record page"
//update user information in database
$sql = mysql_query("UPDATE directory SET
FName = '$FName', LName = '$LName', position='$Position',
phone = '$Phone', email = '$Email', site = '$Site', room = '$Room',
bio = '$Bio', status = '$Status', DeptID = '$DeptID', SortOrder = '$SortOrder',
image = '$Image'
WHERE ID = '$id';"
);
//uploads staff photo only if staff photo has been changed by user.
img_upload($Old_image);
$Result = mysql_query($sql, $ownDB) or die(mysql_error());
if($sql){
//info successfully updated
echo "Record Modified.";
}
} else if($add) {
//add new user to database
$sql = mysql_query("INSERT INTO directory
(FName, LName, position,
phone , email , site,
room , bio ,
status, DeptID , SortOrder,
image)
VALUES ('$FName', '$LName', '$Position',
'$Phone', '$Email', '$Site', '$Room',
'$Bio', '$Status', '$DeptID', '$SortOrder', '$Image');");
//uploads staff photo only if staff photo has been changed by user.
img_upload();
$Result = mysql_query($sql, $ownDB) or die(mysql_error());
if($sql)
//user successfully added
echo "Record Added.";
}
break;
You have multiple problems:
a) Vulnerable to SQL injection attacks
b) Bad code:
This:
$sql = mysql_query("UPDATE directory SET etc.... ");
is actually EXECUTING your query, and returning a statement handle, NOT the sql string you just defined.
You then take this $sql
handle, and try re-run it as another query:
$Result = mysql_query($sql, $ownDB) or die(mysql_error());
which is totally invalid. mysql_query
expects an SQL STRING, not a result handle.
You want:
$sql = "UPDATE blah blah blah";
$result = mysql_query($sql) or die(mysql_error());
instead. Note now $sql
is just a string definition, not a function call result.
c) You are using the deprecated and obsolete mysql_*() functions. Don't. Switch to mysqli (note the i
), or PDO.