I want to update a MySQL database with an input form, essentially a settings page where a user can update/change their information. With this code below, the echo at the bottom runs and I'm not getting any errors, but the database isn't updated. I tested it both on my local machine and on a server and it didn't work with either, although I'm not sure that would have anything to do with it. $_SESSION['yourName']
is already set when the user logs in, so it will equal the current value in the database. I know there are tons of sql injection hole in here, but this is just a proof-of-concept code, not ready to go live. I tried running the query in phpMyAdmin and it worked fine.
PHP
if(isset($_POST['name']) || isset($_POST['password']) || isset($_POST['location']) || isset($_POST['img'])) {
//put this in an external file for a little extra security
$username = "my_username";
$password = "my_password";
$database = "database_name";
$con = mysql_connect('localhost',$username,$password);
if (!$con) {
die('Oh poop.... Could not connect: ' . mysql_error());
}
//print item from database
mysql_select_db($database, $con);
if(isset($_POST['name'])) {
$query = 'UPDATE users SET username=' . $_POST['name'] . 'WHERE username=' . $_SESSION['yourName'];
mysql_query($query);
$_SESSION['yourName'] = $_POST['name'];
}
if(isset($_POST['password'])) {
$query = 'UPDATE users SET password=' . $_POST['password'] . 'WHERE username=' . $_SESSION['yourName'];
mysql_query($query);
}
if(isset($_POST['location'])) {
$query = 'UPDATE users SET location=' . $_POST['location'] . 'WHERE username=' . $_SESSION['yourName'];
mysql_query($query);
$_SESSION['location'] = $_POST['location'];
}
if(isset($_POST['img'])) {
$query = 'UPDATE users SET img=' . $_POST['img'] . 'WHERE username=' . $_SESSION['yourName'];
mysql_query($query);
$_SESSION['img'] = $_POST['img'];
}
echo '<script type="text/javascript">alert("changes saved")</script>';
}
HTML
<form method="post">
new name: <input type="text" name="name" /><br />
new password: <input type="text" name="password" /><br />
new location: <input type="text" name="location" /><br />
new img: <input type="text" name="img" /><br />
<input type='submit' name='save' value='save' />
<input type='submit' name='logout' value='logout' />
</form>