This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 7 years ago.
I have a drop down box from which the user selects a value. I want to post this value to Map.php where it will be used. I currently have my form posting to Map.php which is fine - however, I want to navigate to index.php after the user has made their selection and clicked the button, rather than navigating to Map.php. I have looked for a solution to this, but they all appear to be for situations where you would be visiting the page that the data is posted to...
userInterface.php
<form name="formname" method="post" action="Map.php">
<div id='userList'>
<?php
//get constants for database
require("database.php");
// Opens a connection to a MySQL server
$connection = mysqli_connect ($server, $username, $password);
$query = "SELECT distinct user FROM route";
$result = mysqli_query($connection, $query);
echo '<select name="dropdown" style="width:400px;">';
$count = 1;
while($r = mysqli_fetch_assoc($result)){
echo "<option value =".$count.">".$r['user']."</option>";
$count++;
}
echo '</select>';
?>
<input type="submit" id="button" value="Get Started!" />
Map.php
$value = $_POST['dropdown'];
if($value==1){....
Just use header like this :
header('Location: http://www.example.com/');
Based on PHP docs : http://php.net/manual/en/function.header.php
Related
In my code, I am retrieving data from the database using a while loop so i can have all the $FormData['fullname'] in the db.
What i want to do is, have each name display on the page and also have clickable so when someone clicks a name, it gets their user_id and pulls up information about them.
The problem i am having is that I can't figure out a way to make a it so where i can get the user_id when the user clicks a name. I tried putting a "name" in the button attribute and I checked if isset() but that didn't work.
If someone can properly figure out a way for me to basically, display all the fullnames in my database and when someone clicks a name, it pulls up information about them that is stored in the database. Here is my code
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch()){
echo "<button name='name'>$formData[fullname]</button>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(isset($_POST['name'])){
echo "ok";
}else{
echo "bad";
}
}
}
As far i can see you are trying hit a button inside the while loop , i would not say its a bad approach , but i will suggest you not to do that . and from your code i can see you have lack of understanding post and get request learn from here . and other than this you need to know the transition of web url . how its actually works . anyway , i have given a sample code without . i hope it will help you understanding this concept.
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch(PDO::FETCH_ASSOC)){
$id = $formData['formdataid'];
echo "<a href='somepagename.php?infoid={$id}'>". $formData['fullname']."</a></br>";
}
now in the somepagename.php file or in the same page you can actually show the details information for instance
if(isset($_GET['infoid'])){
$stmt = $handler->prepare("select * from formdata where formdataid='"$_GET['infoid']"'");
$qry = $stmt->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
echo "<p>id =".$row['formdataid']."</p></br>";
echo "<p>id =".$row['name']."</p></br>";
echo "<p>id =".$row['email']."</p></br>";
echo "<p>id =".$row['address']."</p></br>";
code is not executed , it may have semicolon or comma error warning . you have to fix those on your own . this example above shown you only the way it works .
if still you have problem ask , or see the documentation
I should stress that this is not production code and you should totally validate the data input coming in before posting queries to your DB. You can do something like this.
<?php
// Connect
$connection = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Grab all users
$sql = 'SELECT * FROM users';
$users = mysqli_query($connection, $sql);
if (($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['user_id'])) {
$query = "SELECT * FROM users WHERE user_id = {$_POST['user_id']};";
$user = mysqli_fetch_assoc(mysqli_query($connection, $query));
}
?>
// This only runs if our $user variable is set.
<?php if (isset($user)) : ?>
<?php foreach ($user as $key => $value) : ?>
<span><?= print_r($value) ?></span>
<?php endforeach; ?>
<?php endif; ?>
// Display all users in a dropdown and when the button is clicked
// submit it via post to this page.
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select name="user_id">
<?php foreach ($users as $user) : ?>
<option value="<?= $user['user_id'] ?>"><?= $user['name'] ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Submit</button>
</form>
This is going to refresh your page every time. If you want to have an interactive page you are going to need to use JavaScript/AJAX to update the page elements without reloading the page. This example just demonstrates how you can achieve this with PHP and HTML.
you need to know about server-side language(php) and client-side language(javascript).
php runs before page loaded. it cannot runs when click something by itself(with ajax, it can).
most interactions without page move runs with javascript.
in your case, there are two methods.
store all information into hidden input or button's attribute. and get them by user_id via javascript.
use ajax to call another php that can select informations you need by user_id.
both use javascript or jquery. so you must learn about them.
I want to get my application when a item is deleted pop up a messege and redirect to another page. I used javascipt for the popup and php header for the redirection. Now its only doing or the popup or the redirect depending which one is listed first. how do i fix this?
<?php
session_start();
require_once('../../includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: ../../login.php');
$Cursist = mysqli_query($con, "SELECT id FROM users WHERE id =".$_SESSION['id']);
if(!$Cursist){
header('location: ../login.php');
}
$test = $_GET['id'];
$sql = "DELETE FROM cursus WHERE id = $test";
$result = mysqli_query($con, $sql);
if ($result) {
echo "<script type='text/javascript'>alert('Verwijdert!')</script>";
header("Location: ../cursussen.php?destoyed=true&destroyed_id=".$_GET['id']);
}else {
echo "mislukt";
}
?>
If you send sometrhing before header will not work. You can use only header before sending sometrhing to the client.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
http://php.net/manual/en/function.header.php
You could do with javascript but It not recommended because the user could have javascript disabled:
echo "<script type='text/javascript'>";
echo "alert('Verwijdert!')";
echo "document.location.href='index.html'";
echo "</script>";
The best way is to use session and header, you can save a var in session and show a message when the var is true and when you show the messasge delete the session var
delete.php
$_SESSION['deleted'] = true;
header("Location: index.php);
index.php
<?php if($_SESSION['deleted']){ ?>
<?php unset($_SESSION['deleted']) ?>
<div>Item was deleted</div>
<?php } ?>
Well, the problem is that the redirect immediately moves you to a new page, so any javascript on the old page becomes irrelevant. You might be able to use a delay before redirect so that the javascript alert can display.
Otherwise, introduce a variable that you send to the redirect destination page, and use this variable to trigger a javascript popup there.
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 years ago.
I'm fairly new with PHP programming and still getting myself familiar with the methods and syntax. Right now, I have no knowledge of session yet.
I want the user to get a message that the "user doesn't exist or incorrect login details" if he/she types incorrect login details on the form. Otherwise, redirect user to the next page.
I tried using the header() method of PHP but when I put it after the alert() message line, my alert() message doesn't even show.
nextpage.php
<?php
if(isset($_POST['btnLogin'])){
$con = mysqli_connect("localhost","root","","myDb")or die("cannot connect");
if(!$con){
die("Connection failed: " . mysqli_connect_errno() );
}
$studentNo = $_POST['studentNo'];
$username = $_POST['userName'];
$password = $_POST['password'];
$selectQuery = "SELECT * FROM registered WHERE student_no = '$studentNo' AND username = '$username' AND password = '$password' ";
$result = mysqli_query($con,$selectQuery);
if(mysqli_num_rows($result) == 0){
echo '<script language="javascript">';
echo 'alert("User doesn\'t exist or incorrect login details")';
echo '</script>';
header("Location: login.php"); //take user back to login.php if user doesn't exist
}else{
//do this if user exists
//get Parameters for studentNo, userName, password
}
}
?>
login.php
<form action="nextpage.php" method="POST">
<label>Student No</label>
<input type="text" name="studentNo" placeholder="Student No" required />
<br />
<label>Username</label>
<input type="text" name="userName" placeholder="Username" required />
<br />
<label>Password</label>
<input type="password" name="password" placeholder="Password" required />
<br />
<button type="submit" name="btnLogin">Login</button>
</form>
header() takes user back to login.php but it doesn't display the message.
Is there any other better way to do what I'm trying to do? Validate the login details first before redirecting to page two. Otherwise, don't redirect.
I researched and found that I can post data through <form> or other javascript syntax. I would prefer to learn how to do it with plain php and html
I hope you can help me.
Thank you.
You can display a message on the login page itself by adding a value onto the header itself and having an if statement on your login.php.
For example, change your header to
header("Location: login.php?error=1");
And on your login.php file, add this.
if(isset($_GET['error']) && $_GET['error'] == "1") {
echo '<div class="alert alert-danger">Login failed</div>
}
EDIT: Having seen CD001's comment, i'd recommend reading up on php & mysql on how to better protect yourself from sql injections etc. Here is a good place to start.
First of all, you cannot send a header() when you have already echo'ed output.
Secondly, the alert will never show up, even if redirecting would work, because the <script> is not on login.php. It is not magically stored somewhere to showup later.
Using session you can do like this
In your login.php before html code put this
<?php
session_start();
?>
This will start the session. When user submits the form, in nextpage.php, first you need to put again session_start(); on top of the script, after doing users authentication, you can set session like this
if(mysqli_num_rows($result) == 0){
header("Location: login.php?error=User doesnot exists"); //take user back to login.php if user doesn't exist
}else{
//do this if user exists
//get Parameters for studentNo, userName, password
$_SESSION['user_id'] = '<userId>';
//..
header("Location: <secure_page>");
}
In the secure_page where you've redirected the user, in that php script again on top of the script put session_start(); and after that you can check session
if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] != "") {
header("Location: login.php?error=access denied");
}
This will make sure that un-authenticated users can't access this page.
About the issue of not showing alert
In you're script, where you're using javascript code, there you'll need to add the type.
echo '<script type="text/javascript" language="javascript">';
Another problem with the code is javascript will execute only after you're page is loaded but after echoing all those you're using header("location:login.php"); which will redirect the user without showing javascript alert
Well like others said there are better ways of doing this but if you still want to go with your solution then this will work for you:
echo '<script language="javascript">';
echo 'alert("User doesnt exist or incorrect login details");';
echo 'location.href="http://www.yoursite.com/login.php";';
echo '</script>';
remove the php header redirection.
When update button is submitted a function edit_page() is called. This function alter the database table row with new data entered.
This works fine table altered correctly entries are ok.
But problem is that when update button is submitted
1. Entries is database inserted or altered correctly.
2. But when page reloads content of this updated page remains as it is as previous or like before updation on front end or just after submission.
My code:
<?php
function edit_page()
{
add_cat();
global $page_id;
?>
<?php
if (isset($_GET['page_action']) && ($_GET['page_action'] == 'edit'))
{
$page_id = $_GET['post'];
}
?>
<?php
$page_id = $_GET['post'];
$result = mysql_query("SELECT * FROM pages WHERE page_id = '$page_id'"); //execute the SQL query and return records
$row = mysql_fetch_array($result);
$page_title = $row['page_title'];
$page_content = $row['page_content'];
?>
<form method="post" action="" name="edit_page" class="edit_page">
<h4>Page Title:</h4> <input type="text" name="title" class="title" placeholder="Add title of the Page" required value="<?php echo $page_title;?>"/><br/>
<h4>Page Content:</h4><br/>
<textarea cols="80" id="content" name="content" rows="10"><?php echo $page_content;?></textarea>
<input type="hidden" name="page_edits" value="yes" />
<input type="submit" name="edit_page" class="button" value="Update"/>
<?php
save_edits(); }
function save_edits()
{
if (isset($_POST['edit_page']) && $_POST['page_edits'])
{
$page_id = $_GET['post'];
$page_id = $_GET['post'];
$page_title = $_POST['title'];
$page_content = $_POST['content'];
$date = date('Y-m-d h:i');
$query = "UPDATE pages SET page_title='$page_title', page_content='$page_content', date_gmt='$date' WHERE page_id = '$page_id'";
$result = mysql_query($query) or die("Unable to create Page: " . mysql_error());
}
}
?>
<div class="right_sidebar">
<?php edit_page();?></div>
Finally, my mean is that i just want functionality like wordpress in which when update button is clicked just after that we see updated data.
You're doing PHP the procedural way here. That means the statements are executed one after another so the problem lies in the way you place your statements.
In your code, you are displaying the form first and only then updating it, so that's why the previous values get fetched although update is happening only later.
Solution: The function save_edits() and its call should come first followed by edit_page().
Another important thing in terms of security, you are directly inserting the value you get from the address bar. Right now the way it is, someone can drop your whole table by writing in a piece of code. You could use mysql_real_escape_string() to prevent it (although not totally) or better yet:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Lastly, you are not closing your <form> tag.
I am trying to create a website using html in gedit, and i need to be able to log in or register at the homepage which then takes the user to their page on the website, where they are able to input a message, i need the message to go into a database, and to be able to show it at another page on the website. I am confused on how to link html to MySQL when information is created using a form.
I would appreciate if anyone can help me please,
Thanks in advance.
You need to use some server side language to do this. The way it would work is the form would have a URL associated with it for where it would submit the data to. This page should be a PHP script or ASP page or something like that.
Once you have a PHP script you can connect to the database and insert in the records as required with the data.
Here is a good resource if you're not familiar with this:
http://www.w3schools.com/php/php_mysql_insert.asp
You will need to use some sort of server side language like PHP for example. With PHP you can connect to a DB and insert data according to forms that you submit.
I know this answer to your query comes very late (6 years too late) but for the sake of all the newbies out there who googled and reached this page in search of the same question, here's a good response:
Tutorial to use an HTML web-page to interact with a MySQL database using PHP
The tutorial takes you through establishing a mysql connection using php on a web page, connecting to a mysql table and retrieving the results and displaying them back on the web page.
This tutorial uses the PHP MySQL commands:
mysqli_connect
mysqli_query
mysqli_fetch_array
mysqli_close
The Plan
make the connection and select the database
perform the query on the table
print out the data
close the connection
First Up – Connecting to a MySQL database
You need your MySQL server address (if the database is on the same server as the web server it will most likely be localhost or 127.0.0.1), username, password and database name. Create a filenamehere.php file and open and close the php code with tags before the html, you can put regular html after it. Open the file in a browser and you should see nothing apart from the title tag, if you see the error the username/password or database name may be wrong.
PHP will require that mysqli is enabled (it is on most PHP set ups).
<?php
//Step1
$db = mysqli_connect('localhost','username','password','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
</body>
</html>
The variable $db is created and assigned as the connection string, it will be used in future steps. If there is a failure then an error message will be displayed on the page. If it is successful you will see PHP connect to MySQL.
Performing a database query
The mysql query is actually performed in the body of the html page, so additional php opening and closing tags will be required. For the query we are going to specify a read of all fields from a given table. The $query variable selects all rows in the table. You just need to use your table name.
<?php
//Step1
$db = mysqli_connect('localhost','root','root','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
//Step2
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying database..');
?>
</body>
</html>
Again the returned page in the browser should be blank and error free, if you do receive the error – ‘Error querying database..’ check the table name is correct.
Put the data on the page
Here we are making a $result variable which stores the query we just made above, now we just need to go through all the rows of that query which we need mysqli_fetch_array which stores the rows in an array, so now we are storing the $result in mysqli_fetch_array and passing that into a variable called $row.
The $row now can be output in a while loop, here the rows of data will be echoed and displayed on the page to when there is no longer any rows of data left, this example uses 4 fields in the table first_name, last_name, email and city.
<?php
//Step1
$db = mysqli_connect('localhost','root','root','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
//Step2
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while ($row = mysqli_fetch_array($result)) {
echo $row['first_name'] . ' ' . $row['last_name'] . ': ' . $row['email'] . ' ' . $row['city'] .'<br />';}
?>
</body>
</html>
Here you should see the all data as output from your table.
Closing off the connection
Closing the connection will require another set off opening and closing php tags after the closing html tag. It is good practice to close the database connection when the querying is done.
<?php
//Step1
$db = mysqli_connect('localhost','root','root','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
//Step2
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying database.');
//Step3
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while ($row = mysqli_fetch_array($result)) {
echo $row['first_name'] . ' ' . $row['last_name'] . ': ' . $row['email'] . ' ' . $row['city'] .'<br />';}
//Step 4
mysqli_close($db);
?>
</body>
</html>
Database connections should always be closed off. You do not need to keep the connection variable $db after the initial connection but is considered best practice.
You need to use PHP, try WAMP it has PHP, MYSQL databse
here is a simple form
Your database table test
create table test
(id int not null auto_increment primary key,
firstname nvarchar(20)
);
Then using Server side PHP
//tst.php file
<?php
$connect=mysql_connect('hostname','username','password');
mysql_select_db('databaseName');
if(isset($_POST['submit']))
{
$firstname=mysql_real_escape_strings($_POST['firstname']);
$ret=mysql_query("insert into test(firstname) values ('$firstname')")
}
?>
<html>
<head> </head>
<body>
<form method="post">
<input type="text" name="firstname" />
<input type="submit" name="submit" Value="Submit" />
</form>
</body>
</html>