I am writing a script right now to update a MySQL data entry through a PHP form. I know there are lots of tutorials and also a lot of answers here on Stackoverflow. My problem is that I get a "Updated data successfully" message but the data are not updated inside my database. Maybe someone find the error or can tell me what I did wrong and what I have to change. Here is the needed code:
Form:
<?php
session_start();
if(empty($_SESSION)) // if the session not yet started
session_start();
if(!isset($_SESSION['email'])) { //if not yet logged in
header("Location: login.php");// send to login page
exit;
}
include 'header.php';
$get = "SELECT * FROM user email WHERE email = '".$_SESSION['email']."'";
$result_get = mysqli_query($connect, $get);
$_SESSION['data'] = mysqli_fetch_assoc($result_get);
?>
<form method="POST" action="update_profile.php" class="form-horizontal form-label-left">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Vorname:</label>
<div class="col-md-9 col-sm-9 col-xs-12">
<input type="text" name="firstname_parent" class="form-control" value="<?php echo $_SESSION['data']['firstname_parent']; ?>">
</div>
</div>
<button type="submit" name="update" value="update" class="btn btn-warning btn-lg btn-block">PROFIL VERVOLLSTÄNDIGEN</button>
</form>
update_profile.php:
<?php
session_start();
// Create connection credentials
$db_host = 'localhost';
$db_name = 'DBNAME';
$db_user = 'DBUSER';
$db_pass = 'DBPASS';
// Create mysqli object
$connect = new mysqli ($db_host, $db_user, $db_pass, $db_name);
// Error Handler
if ($connect->connect_error) {
printf ("Connection failed: %s\n", $connect->connect_error);
exit();
}
// Check if form is submitted
if (isset ($_POST['update'])) {
$update_firstname_parent = mysqli_real_escape_string ($connect, $_POST['firstname_parent'] );
}
$sql = mysqli_query ($connect, "UPDATE `user` SET
firstname_parent='".$update_firstname_parent."' WHERE email = '".$_SESSION['email']."'";
if (mysqli_affected_rows($connect) == 0) //<--
{
die('Could not update data: ' . mysql_error());
} else {
echo "Updated data successfully\n";
}
mysql_close($connect);
?>
EDIT:
I changed the update_profile.php due to some comments here. Now I do not get a "Updated data successfully" message, now I only get a blank page and no data is updated inside the database.
Thanks,
Chris
Your update query is wrong. Change it
$sql = mysqli_query ($connect, "UPDATE `user` WHERE email = '".$_SESSION['email']."' (`firstname_parent`)
VALUES ('$update_firstname_parent')");
to
$sql = mysqli_query ($connect, "UPDATE `user` SET
firstname_parent='".$update_firstname_parent."' WHERE email = '".$_SESSION['email']."'");
Isn't your if statement incorrect? You are checking to see if something is changed and then outputting the error rather than the otherway around?
if (mysqli_affected_rows($connect) == 1)
{
die('Could not update data: ' . mysql_error());
} else {
echo "Updated data successfully\n";
}
to
if (mysqli_affected_rows($connect) == 0) //<--
{
die('Could not update data: ' . mysql_error());
} else {
echo "Updated data successfully\n";
}
your QUERY is wrong.
USE
"UPDATE ''user SET firstname_parent='".$update_firstname_parent."' WHERE email = '".$_SESSION['email']."'";
There was syntax error in your UPDATE and a missing session_start(); in the update.php file. This should work just fine.
update.php
<?php
session_start();
// Create connection credentials
$db_host = 'localhost';
$db_name = 'DBNAME';
$db_user = 'DBUSER';
$db_pass = 'DBPASS';
// Create mysqli object
$connect = new mysqli ($db_host, $db_user, $db_pass, $db_name);
// Error Handler
if ($connect->connect_error) {
printf ("Connection failed: %s\n", $connect->connect_error);
exit();
}
// Check if form is submitted
if (isset ($_POST['update'])) {
$update_firstname_parent = mysqli_real_escape_string ($connect, $_POST['firstname_parent'] );
}
$sql = mysqli_query ($connect, "UPDATE `user` SET
firstname_parent='".$update_firstname_parent."' WHERE email = '".$_SESSION['email']."'");
if (mysqli_affected_rows($connect) == 1)
{
die('Could not update data: ' . mysql_error());
} else {
echo "Updated data successfully\n";
}
mysql_close($connect);
?>
<?php
session_start();
if(empty($_SESSION)) // if the session not yet started
session_start();
if(!isset($_SESSION['email'])) { //if not yet logged in
header("Location: login.php");// send to login page
exit;
}
include ('header.php');
$get = "SELECT * FROM user email WHERE email='".$_SESSION['email']."'";
$result_get = mysqli_query($connect, $get);
$_SESSION['data'] = mysqli_fetch_assoc($result_get);
?>
<form method="POST" action="update_profile.php" class="form-horizontal form-label-left">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Vorname:</label>
<div class="col-md-9 col-sm-9 col-xs-12">
<input type="text" name="firstname_parent" class="form-control" value="<?php echo $_SESSION['data']['firstname_parent']; ?>">
</div>
</div>
<button type="submit" name="update" value="update" class="btn btn-warning btn-lg btn-block">PROFIL VERVOLLSTÄNDIGEN</button>
</form>
First thing to know if the data is correct try to echo
echo($connect, "UPDATE `user` SET
firstname_parent='".$update_firstname_parent."' WHERE email = '".$_SESSION['email']."'";
if the data shows then your code is correct but here's mine:
$sql = mysqli_query("UPDATE user SET firstname_parent='".$update_firstname_parent."' WHERE email = '".$_SESSION['email']."'");
Related
Have a PHP form for a registration system:
<div class="col-md-6 login-right">
<h2> Register Here </h2>
<form action="registration.php" method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="user" class="form-control" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary"> Register</button>
</form>
</div>
And a registration.php created:
<?php
session_start();
$con = mysqli_connect('localhost','root', 'test');
mysqli_select_db($con, 'userregistration');
$name = $_POST['user'];
$pass = $_POST['password'];
$s = " select * from usertable where name = '$name'";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo " Username Already Taken";
}else{
$reg = " insert into usertable(name , password) values ('$name' , $pass')";
mysqli_query($con, $reg);
echo" Registration Successful";
}
?>
Also have a MySQL database created with Database: userregistration »Table: usertable. And the MySQL not sure, quite new to this isn't being populated with the inputted data from the php. When the data is inputted into the php form it requests the registration.php page which works successfully but doesn't populate the table with the data inputted.
You should be actively checking that the connection is successful first, and then also checking that the query was successfully executed too in order to debug this further.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (mysqli_query($conn, $reg)) {
echo "New record created successfully";
} else {
echo "Error: " . $reg . "" . mysqli_error($conn);
}
You should then also close the connection
in a form i put in a checkbox (switch), how do i post after submitting to checking the status of the switch for MySQL update? thank you
Consequently the MySQL table does not change.
From checkbox and submit
<form method="POST" action="process.php">
<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
<input type="checkbox" id="switch-1" class="mdl-switch__input" checked>
<span class="mdl-switch__label">Autenticazione a due fattori</span>
</label>
....
<input onclick="conferma();" class="mdl-button mdl-js-button
mdl-button--raised mdl-js-ripple-effect mdl-button--accent" type="submit"
value="Salva" name="submitBtn">
</form>
Switch control and MySQL update (process.php)
<?php
session_start();
mysql_connect(localhost) or die(mysql_error());
mysql_select_db("*******") or die(mysql_error());
$user = $_SESSION['users'];
if(isset($_POST['submitBtn'])) { //form submission occured
if(!isset($_POST['switch-1'])){
$sql = "UPDATE `*******`.`login_users` SET `auth` = \'checked\' WHERE username = '$user'";
header("location: https://*******.php");
} else {
$sql = "UPDATE `*******`.`login_users` SET `auth` = \'unchecked\' WHERE username = '$user'";
header("location: https://*******.php");
}
}
?>
1) Modify your form
<form method="POST" action="process.php">
<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
<input type="checkbox" name="switch-1" id="switch-1" class="mdl-switch__input" checked>
<span class="mdl-switch__label">Autenticazione a due fattori</span>
</label>
....
<input type="submit" value="Salva" name="submitBtn" class="mdl-button mdl-js-button
mdl-button--raised mdl-js-ripple-effect mdl-button--accent" >
</form>
2) Create a new process.php page in the same working directory and add these.
EDIT:
<?php
session_start();
$user = $_SESSION['users'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "YourDBName";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submitBtn'])) { //form submission occured
if(isset($_POST['switch-1'])){
$sql = "UPDATE login_users SET auth = 'checked' WHERE username = '$user'";
} else {
$sql = "UPDATE login_users SET auth = 'no' WHERE username = '$user'";
}
if ($conn->query($sql)) {
echo "Updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Form Submission Error";
}
$conn->close();
?>
Hope it's helpful.
I've been looking at my code for days, but can't seem to find the problem. I'm new in PHP, so I'm not really familiar with all of it.
Below is my code. No errors. No registered session variable values.
db-config.php
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mcsh';
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
login.php
<form id="user-login" action="index.php" method="POST">
<h1>Administrator Login</h1>
<input type="text" name="username" placeholder="Username" required/>
<input type="password" name="password" placeholder="Password" required/>
<button type="submit">Login</button>
Forgot your password?
</form>
<?php
if (!empty($_POST)) {
if (!empty($_SESSION['username'])) {
header("Location: index.php");
}
$username = $_POST['username'];
$password = $_POST['password'];
include("../config/db-config.php");
$sql = "SELECT `userid`, `password` FROM users WHERE userid = '" . $username . "' AND userlevel = '99'";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
if (password_verify($password, $row['password'])) {
$_SESSION['username'] = $row['userid'];
header("Location: index.php");
exit;
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
?>
index.php
<?php
session_start();
include("../config/config.php");
if (empty($_SESSION['username'])) {
header("Location: login.php");
}
else {
//the rest of the index page...
?>
Your form in login.php submits to index.php. In index.php, if the username is not yet in the session, you are redirected back to login.php. There you check if (!empty($_POST)) { at the beginning of your PHP code.
$_POST will be empty, because you have redirected to that page, not POSTed to it, so the PHP code will not be executed.
Remove the action="index.php" and that form will submit to itself (login.php). Also, move the HTML form code below the PHP code so that you will not have output before the redirect header if the login is successful.
I want to make a query that deletes a post(thread) from a page but in that page I have multiple posts, I have in my database a field called id_thread is the unique id of every post but I'm listing multiple posts of the same user in the page, this is the code of the page where the posts are listed:
<?
session_start();
if(isset($_SESSION['id']))
{
$servername = "(...)";
$username = "(...)";
$password = "(...)";
$dbname = "(...)";
$connect = mysqli_connect($servername, $username, $password, $dbname);
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
}
else
{
header(" url=index.php");
}
?>
(... hidded non relative html code ....)
<?
$id = (isset($_GET['id'])) ? $_GET['id'] : $_SESSION['id'];
$query = mysqli_query($connect,"SELECT * FROM thread inner join category on thread.id_type=category.id_type WHERE username = '".$id."'");
echo '<div class="container marg-t-100">'."All posts from User: ".$id.'</div>';
echo '<div class="container-fluid marg-t-25">';
while($row = mysqli_fetch_array($query))
{
echo '<div class="col-md-1"></div>';
echo '<div class="col-md-11">';
echo '<form role="form" action="delete.php" method="post"><a type="submit" class="btn btn-danger marg-t-10 pull-right">Delete Thread</a></form>';
echo $row['title'] ."<br><br>".$row['content']."<br><br>".'<div class="pull-right">'. "date: ".$row['data']."<br>"."author: ".$row['username']."<br>".$row['name'].'</div>' ."<br><br><br><hr><br>";
echo '</div>';
}
echo '</div>';
mysqli_close($connect);
?>
(...)
this is an image of the page im talking about:
I want that when I click "Delete Thread" the respective post(thread) gets deleted from database.
If you see in the page code above you can see that the delete button takes action at delete.php, this is my code on that file:
<?php
session_start();
if(isset($_SESSION['id']))
{
$servername = "(...)";
$username = "(...)";
$password = "(...)";
$dbname = "(...)";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$id = (isset($_GET['id'])) ? $_GET['id'] : $_SESSION['id'];
$query = mysqli_query($connect,"Delete FROM thread WHERE username = '".$id."' and id_thread ='".(I WANT THE RELATIVE ID HERE)."'");
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
}
else
{
header(" url=index.php");
}
?>
In your page that lists user's posts, inside the form add a hidden field with a value of the post ID and a name attribute in which you will use later in your POST variables.
echo '<form role="form" action="delete.php" method="post"><button type="submit" class="btn btn-danger marg-t-10 pull-right" value="Delete Thread"><input type="hidden" name="thread_id" value="'.$row['id'].'"></form>';
And in delete.php query part:
$query = mysqli_query($connect,"Delete FROM thread WHERE username = '".$id."' and id_thread ='.$_POST['thread_id']);
<?
echo '<form role="form" action="delete.php?id='.$row['thread_id'].'" method="post"><input type="submit" class="btn btn-danger marg-t-10 pull-right" value="Delete Thread"></form>';
delete.php
<?php
session_start();
if(isset($_SESSION['id']))
{
$servername = "(...)";
$username = "(...)";
$password = "(...)";
$dbname = "(...)";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$id=$_SESSION['id'];
$thread_id = $_GET['title'];
$query = mysqli_query($connect,"Delete FROM thread WHERE username = '".$id."' and thread_id ='".$thread_id."'");
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
}
else
{
header(" url=index.php");
}
?>
I hope this is what you asked for.
I think I am successfully connecting to my database by:
<?php
$user = 'root';
$pass = '9KSroMDjEqNmEYY4';
$db = 'chatservice';
$host = '127.0.0.1';
$conn = new mysqli($host, $user, $pass, $db, 3306) or die("Unable to connect");
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
?>
My question is how I would use the registration code to successfully add a user to the database. When entering the form I press register I do not get any error messages stating that the registration didn't succeed. It seems that the php code is not being reached after the initial connection. I am new to php and mySQL so any tips on formatting would be nice too!
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$id', '$password')";
$result = mysqli_query($query);
if($result){
$msg = "Registered Sussecfully";
echo $msg;
}
else
$msg = "Error Registering";
echo $msg;
}
?>
<div class="register-form">
<title>Chat Page Start</title>
<form action="" methods="POST">
<p>
<label>Username: </label>
<input id="user" type="text" name="user" placeholder="user" />
</p>
<p>
<label>ID: </label>
<input id="IDNUM" type="text" name="IDNUM" placeholder="ID number" />
</p>
<p>
<label>Password: </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" value="Register" />
</form>
</div>
Another thing is how would I check the status of my database connection and where I should be checking this status?
your database connection is mysqli_connect and you execute the query in mysql_query is not proper.
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', ' $id ', '$password')";
$result = mysqli_query($query,$conn);
if($result){
$msg = "Registered Sussecfully";
}
else
$msg = "Error Registering";
}
?>
You are connecting database using mysqli:
$conn = new mysqli('localhost', $user, $pass, $db, 3306) or die("Unable to connect");
And executing query using mysql:
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$IDNUM', '$password')";
$result = mysql_query($query);