When I refresh/reload the page the message(Host Name, User Name and Database Name are mandatory.) is showing. I prefer to show the message only after the submission of form.
Consider my index.php page:
// Create database
$sql = "CREATE DATABASE $dbname";
if (mysqli_query($conn, $sql)) {
echo "<div class='msg'>Database created successfully</div>";
} else {
echo "<div class='msg'>Error creating database: " . mysqli_error($conn) ."</div>";
}
mysqli_close($conn);
}else{
echo "<div class='msg'>Host Name, User Name and Database Name are mandatory.</div>";
}
}?>
<form method="post" action="index.php" class="dbform" >
<table>
<tr><td>Host Name</td><td><input type="text" name="hostname" value="localhost"></td></tr>
<tr><td>User Name</td><td><input type="text" name="username"></td></tr>
<tr><td>Password</td><td><input type="text" name="pass"></td></tr>
<tr><td>Database Name</td><td><input type="text" name="dbname"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" name="subbtn" value="Create"></td></tr>
</table>
</form>
Expected bahaviour: When click the submit button, if the fields are empty show the Host Name, User Name and Database Name are mandatory. message, It is working ok.
But when I refresh the page the message is also showing. How can I solve this?
It's because the browser is reloading the last request you performed on that page, which is a POST request to the index.php.
When you hit reload it is again performing that same request.
Most browsers ask for a confirmation before resubmitting a post request.
What you can do solve you problem is store your messages in session and redirect to the page.
Start of your PHP code add
session_start();
Then store your messages in session
$_SESSION['msg'] = 'Your message';
Then when you have processed the current request redirect.
header('Location: YOUR_URL');
die();
Then you can check if there is any message and output
<?php if (!empty($_SESSION['msg']) : ?>
<div class='msg'><?php echo $_SESSION['msg']; ?></div>
<?php endif; ?>
Related
I'm trying to create a form on a webpage, which takes an id number entered by the user, and deletes the corresponding record in a database. I'm unable to get it working.
This is the delete code which isn't working:
<?php
if (isset($_POST['deleteSubmit'])) {
$details = $conn->real_escape_string($_POST['deleteNum']);
$deleteSQL = "DELETE FROM userName WHERE id = '$details'";
$result = $conn->query($deleteSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>DELETE NAME (DELETE)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="num">Enter User Reference to be Deleted:</label><br>
<input num="deleteNum"type="number"><br>
<input num="deleteSubmit" type="submit" value="Delete">
</form>
For reference, this is the post code which is working (it's being used to add names to the database):
<?php
if (isset($_POST['nameSubmit'])) {
$details = $conn->real_escape_string($_POST['newName']);
$insertSQL = "INSERT INTO userName (name) VALUES ('$details')";
$result = $conn->query($insertSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>ENTER NAME (POST)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="fname">Enter Name:</label><br>
<input name="newName"type="text"><br>
<input name="nameSubmit" type="submit" value="Submit">
</form>
The database connection file is being called in both programs and is working for the post.php element, which is why I haven't included it or reference to it.
The database has one table called userName which contains two columns id (which is auto incremented) and name.
I've tried changing some of the syntax on the delete.php file with no success. I've ran the $deleteSQL code directly in my database and it works.
I see no error messages when enter an id and click the delete button.
For anyone who reads this in future, the query was solved by #kenlee;
(1) Change num="deleteSubmit" to name="deleteSubmit"
(2) change num="deleteNum" type="number" to name="deleteNum" type="number"
(3) Please use paratemerized prepared statement in your queries
I am trying to redirect a to a new php page after the user has clicked on the submit button. I have got it to successfully send the form information to the MySQL database but then I cannot get a successful redirect.
I then changed some code and got it to successfully redirect but not send the form information to the database. My other php file is named nextForm.php and I have tried replacing the action="$_SERVER[PHP_SELF]" with the path to the nextForm.php file and I have tried using a require nextForm.php; line in the code where I want to redirect.
Here is the code I have currently:
<?php
//establish a connection to the MySQL db or terminate if ther is an error
$conn = mysqli_connect("localhost","root","mysql","covid_tech",3306) or die(mysqli_connect_error());
//HTML form to prompt user input
print <<<_HTML_
<FORM style="text-align:center" method="POST" action="$_SERVER[PHP_SELF]">
<div class="Customer_Name">
Enter Customer Name: <input type="text" name="Customer_Name" class="textbox">
</div>
<br/>
<div class="Contact_Name">
Enter Contact Name: <input type="text" name="Contact_Name" class="textbox">
</div>
<br/>
<div class="Contact_Phone">
Enter Contact Phone Number: <input type="text" name="Contact_Number" class="textbox">
<br/>
</div>
<button class="btn btn-1" style="text-align:center" onclick='disappear(this)' name="name_submit" method="POST" type="submit" value="find_cusName"><span>Enter Customer Name</span></button>
</FORM>
_HTML_;
//check to make sure the POST request was sent and check to make sure that there is a vlaue in the System POST variable
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['Customer_Name'])){
//SQL string to find the name that was input on the page
$find_name_sql = "SELECT cusName,cusID from customer where cusName = '$_POST[Customer_Name]'";
//run the query on the db
$result_find_name = mysqli_query($conn, $find_name_sql);
//Check to see if the query returned any rows
if(mysqli_num_rows($result_find_name) > 0){
//If it did, it should only be 1 row and we fetch it
$row = mysqli_fetch_row($result_find_name);
//set our current_id variable to the value in $row[1] which is the cusID attribute from the db
$current_id = $row[1];
}
else{
//sql statment to insert a new customer into the customer table of the db
$insert_first_customer = "INSERT INTO customer (cusName,contactName,contactNo) values('$_POST[Customer_Name]','$_POST[Contact_Name]','$_POST[Contact_Number]')";
//run the insert query
$add = mysqli_query($conn,$insert_first_customer);
}
//redirect to next form page here
}
mysqli_close($conn);
?>
The action attribute simply works as a way to direct your GET/POST requests. If you would like to redirect after running your PHP code, you should use the header() function or use a meta tag.
Example:
header('Location:'.$_SERVER['SERVER_NAME'].'/nextForm.php');
or
echo '<meta http-equiv="refresh" content="0;url=nextForm.php">';
and finish your code with the exit() function so an attacker could not bypass your redirect.
I'm new to PHP. I want to display a message that the database is updated after each time I redirect it after entering the data.
$sql = "INSERT INTO incoming (recipt, userid, username, money)
VALUES ('$recipt', '$userid', '$username', '$money')";
if ($conn->query($sql) === TRUE) {
echo "<script>window.open('incoming2.php','_self')</script>";
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
2 methods
1-you can redirect to any page adding message in get variable and check at that page if that variable is set then display it as message
//redirect to index.php with msg as
header('location:index.php?msg=2 records updated');
//at index page where you want to display message
if(isset($_GET['msg']) && !empty($_GET['msg'])){
echo '<p class="myMsg">'.$_GET['msg'].'</p>'
}
2- second method is to save the message to session variable and access it at page but you will have to unset that variable as below
//sending message assuming session_start() is written at to of all pages
$_SESSION['msg']="2 records updated or what ever your message is";
//where you want to display message
if(isset($_SESSION['msg']) && !empty($_SESSION['msg'])){
echo '<p class="myMsg">'.$_SESSION['msg'].'</p>'
unset($_SESSION['msg']);
}
Pass the message to your url:
echo "<script>window.open('incoming2.php?message=New+record+created+successfully','_self')</script>";
Then you can get the message in incoming2.php:
echo urldecode($_GET['message']);
Be careful: sanatize your input!
Use header("Location: incoming2.php"); instead of echoing JS.
Also, check your SQL statement for SQL injection vulnerabilities.
If you are posting the data on the same page you could do the following:
<?php
if(isset($_REQUEST["submit"])){
// mySQL code here
// return either success or failed
$confirmation="success";
}
?>
<html>
<head>
<title>Feedback</title>
</head>
<body>
<div>
<?php
if(isset($confirmation)){
echo $confirmation;
}
?>
</div>
<form method="post" action="">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" Value="Submit">
</form>
</body>
</html>
If you are sending the data to a separate page:
On the receiving page:
<?php
// mySQL code here
// return either success or failed
//redirect to index.php with confirmation as true or false
header('location:index.php?confirmation=success');
?>
and on the page that you Sent the data from:
<html>
<head>
<title>Feedback</title>
</head>
<body>
<div>
<?php
//at index page where you want to display message
if(isset($_GET['confirmation']) && !empty($_GET['confirmation'])){
echo $_GET['confirmation'];
}
?>
</div>
<form method="post" action="uploaddata.php">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" Value="Submit">
</form>
</body>
</html>
You can then use CSS3 animations to fade the message in and out for a better user experience :-)
I'm trying to make a login page with session() function and I had some problem with the code, but I don't know why.
What I want to do after that is in my admin page I want it to say "welcome (the username that inserted in the form)", but I dont know how.
I tried with session() but its shows me:
PHPSESSID
What should I do?
This is the code
<?php
$sid = $_POST["username"];
session_start();
include("../inc/passwords.php");
if ($_POST["ac"]=="log") { /// do after login form is submitted
if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted
$_SESSION["logged"]=$_POST["username"];
} else {
echo 'Incorrect username/password. Please, try again.';
};
};
if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not
header('Location: index.php'); //// if user is logged show a message
} else { //// if not logged show login form
echo '<table align="center" border="0">
<h3 style="color: #555" align="center" class="">بالرجاء تسجيل الدخول للمتابعة</h3>
<form action="login.php" method="post"><input type="hidden" name="ac" value="log">
<tr><td>الاســـــــم</td><td>:</td><td><input type="text" name="username" size="20"> </td></tr>
<tr><td>كلمة السر</td><td>:</td><td><input type="password" name="password" size="20"> </td></tr>
<tr><td> </td><td> </td><td><input class="buttons" type="submit" value="تسجيل الدخول"></td></tr>
</form>
</table>';
};
?>
Just for knowledge:
Most important things to be remember.
Always start session after php tag starts.
e.g.
<?php
session_start();
If you start it like:
<?php
$sid = $_POST["username"];
session_start();
It will through error message : headers already sent etc
I would recommend taking a look at the piece of code:
if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted
$_SESSION["logged"]=$_POST["username"];
}
You need to make sure the $_SESSION["logged"] is actually set. Perhaps try performing an echo on it. If it is empty, it would be the logic not evaluating to true.
Also make sure you do a session_start() on your index.php page.
it wont work using session with the welcome thing
try by using mysql
like
when the admin puts it name and password
his name is putted in a table in mysql
and in the index for the admin page
you query the table
like
$username = $_POST['username'];
mysql_query(SELECT username FROM admins where username='$username');
I am creating my own website just to get some experience. I've been working on it for 3 days and am at the point where I can sign up and sign in.
When signing in, if the combination of the username and password is not found in the database, my code displays an error message telling the user that either he didn't sign up yet or he is entering a wrong user email or password.
But, the message is displayed in a new page, instead of the sign in page.
I looked at some tutorials online, but didn't find a good explanation for it. Could someone please give me some advise?
I am using PHP for the database connection.
I just typed a very basic example:
<?php
//login.php
$msg = ''; //to store error messages
//check whether the user is submitting a form
if($_SERVER['REQUEST_METHOD'] == 'POST') //check if form being submitted via HTTP POST
{
//validate the POST variables submitted (ie. username and password)
//check the database for a match
if($matchfound == TRUE) //if found
{
//assign session variables and other user datas
//then redirect to the home page, since the user had successfully logged in
header('Location: index.php');
}
else
{
$msg = 'Error. No match found !'; //assign an error message
include('login_html.php'); //include the html code(ie. to display the login form and other html tags)
}
}
else //if user has not submitted the form, just display the html form
{
include('login_html.php');
}
//END of login.php
?>
login_html.php :
<html>
<body>
<?php if(!empty($msg)) echo $msg; ?> <!-- Display error message if any -->
<form action="login.php" method="post">
<input name = "username" type="text" />
<input name = "password" type="password" />
<input name = "submit" type="submit" value="Submit" />
</form>
</body>
</html>
This is not a complete code. But I just created it for you to understand how this can be done. :)
Good luck
Your opening form tag should look like this: <form action="" method="post">. The empty "action" attribute will cause the page to post back to itself. Just check the $_POST for username and password to determine whether to test for a match or just show the form.
And please be sure to hash your passwords and sanitize your inputs!
you can do it without going to a new page.
<?php session_start(); ?>
<?php
if(isset($_POST) && isset ($_POST["admin_login"])){
$user_data_row = null;
$sql="SELECT * FROM table_name WHERE <table_name.field name>='".mysql_real_escape_string($_POST['email'])."'
and <table_name.field name='".mysql_real_escape_string($_POST['password'])."'
;
$result=mysql_query($sql);
$user_data_row=mysql_fetch_assoc($result);
if(is_array($user_data_row)){
$_SESSION['user_id'] = $user_data_row['id'];
header("Location: <your page name>");
}else{
$_SESSION['message'] = "Valid email and password required";
}
}
?>
<?php if(isset($_SESSION['message'])){
echo "<li>{$message}</li>";
?>
<form action="" method="post" id="customForm">
<label>Email:</label>
<input type="text" id="email" name="email">
<label>Password:</label>
<input type="password" id="password" name="password">
<input type="submit" value="Login" id="send" name="admin_login">
</form>
may be its helps you....
Basically what you need to do, is post the form to the same page.
Once you have that, at the type just check for the $_POST: if($_SERVER['REQUEST_METHOD'] == 'POST')
If it is a post, check the username and password and either show an error or redirect to the signed in page. After this, display the login form.
So, if it's an error, they'll get the error and then the login form. If it's not posted, they'll get just the login form, and if it's a valid login, they'll get redirected to the proper page before the login form is shown.