ok I've searched stackoverflow and many other sites, I've tried all kinds of solutions for this but nothing seems to work.
I am processing a form in PHP, checking for missed entries and erroring if missed or adding to the SQL DB if ok, the form itself works just fine, the processing works, the form is either error thrown and displayed or added to the Database, I want that page to then display either error or sucess wait a short time and then auto forward either back to the form if there was an error, or to the page that displays the db contents if the add was successful. Nothing I seem to try here works. please help: My code so far:
//If errors present
if ($errormsg) {
echo "<div class=\"box red\">$errormsg</div>";
sleep(2);
echo '<script>' . "\n";
echo 'window.location="blogmake.html?blogid=" + blogid;';
echo '</script>';
}
if ($secim == "3"){ //If all present and correct post comment to DB
if ($valname && $valemail && $valcom){
$con = mysql_connect("xxxx","User","pass");
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("dbname", $con);
$fulcom = mysql_real_escape_string ($_POST['comment']);
mysql_query("INSERT INTO tabname(blogid, date, email, name, comment) VALUES ('$blogid', CURRENT_TIMESTAMP(),'$valemail','$valname','$fulcom')") or die('Error: ' . mysql_error());
mysql_close($con);
echo "<div class=\"box green\">Your comment has been submitted</div>";
sleep(2);
echo '<script>' . "\n";
echo 'window.location="blogread.php?blogid=" + blogid;';
echo '</script>';
}
}
?>
</div>
You should probably use either an HTML meta tag:
<meta http-equiv="refresh" content="2;URL='http://yoursite.com/blogread.php?blogid=<?= $blogid ?>'" />
or JavaScript's setTimeout function:
setTimeout(function(){
window.location="blogread.php?blogid=<?= $blogid ?>";
}, 2000);
The meta tag has two important parameters: 2 is the number of seconds after which a redirection happens; and URL=... is the url to which it should redirect.
SetTimeout has two parameters in this case, the first one is the function that will be executed (the whole function part); and the other one is the delay time in milliseconds after which that function will be executed (the number 2000).
Note that I used <?= $blogid ?> in both cases - that's just a short code for this: <?php echo $blogid; ?>. Of course, you can use it however you want, for example using echo to echo the whole code, just like you were doing.
You need:
<meta http-equiv="refresh" content="3;url=http://www.google.com/" />
Change 3 for your seconds and url= by your webpage, ie:
echo '<meta http-equiv="refresh" content="2;url=blogread.php?blogid='.blogid.'" />';
Related
I'm having issue when echoing alert() in php. It show everything in the string.
echo "<script type='text/javascript'>alert('Thank you for your enquiry, we will contact you as soon as possible, have a nice day!');</script>";
Output
You can use javascript code between ending and starting php tags like below,
?>
<script type="text/javascript">
alert('Thank you for your enquiry, we will contact you as soon as possible, have a nice day!');
</script>
<?php
// rest of the php code will go here.
?>
OR try this please,
<?php
echo '<script type="text/javascript">';
echo 'alert("Thank you for your enquiry, we will contact you as soon as possible, have a nice day!");';
echo '</script>';
?>
Solution: I fixed it by removing everything. and just echo the message directly without the alert(). I'm not sure why it behave like this because this is my custom plugin. I will update if I found the source of this behavior. Thank you for all the replies.
echo 'Email Successfully Sent. We will reply soon!';
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.
I am trying to display an alert box before redirecting to another page, here is my code, when I remove the header function it works properly but when it is here it will just redirect to the page without showing the alert box.
<html>
<body>
<?php
include("dbconfig.php");
$tempid = mysqli_real_escape_string($dbconfig, $_POST['tempid']);
$sql_query = "DELETE FROM Visits
WHERE visitid = '$tempid'";
$result = Mysqli_query($dbconfig, $sql_query);
if ($result) {
echo '<script language="javascript">';
echo 'alert("visit deleted successfully")';
echo '</script>';
header("location:../SearchCountry/search.php");
}
?>
</body>
</html>
PHP is executed at the server side. It renders HTML/JS/CSS and sends it to the web browser, the web browser then parses and executes the JavaScript (In your case, show the alert dialog.)
However, once you call
header ("location:../SearchCountry/search.php");
The browser will be informed to redirect the user to ../SearchCountry/search.php immediately, without a chance to parse and execute the JavaScript. That's why the dialog will not show up.
Solution: redirect your user to another page with JavaScript instead of PHP.
<html>
<?php
include("dbconfig.php");
$tempid = mysqli_real_escape_string($dbconfig,$_POST['tempid']);
$sql_query = "DELETE FROM Visits
WHERE visitid = '$tempid'";
$result = Mysqli_query($dbconfig,$sql_query);
if($result){
echo '<script language="javascript">';
echo 'alert("visit deleted successfully");\n';
echo 'window.location.href="../SearchCountry/search.php"'; //Redirects the user with JavaScript
echo '</script>';
die(); //Stops PHP from further execution
}
?>
</body>
</html>
echo "<script>
alert('visit deleted successfully');
window.location.href='SearchCountry/search.php';
</script>";
and get rid of redirect line below.
You were mixing up two different worlds.
Basically, I'm trying to create a login system, and I'm using it what I call "Dynamically" meaning it's included from my other files, and if I wanted to use a different database I would simply pass that database to the login function. I know how to do this by default, but as soon as using a button came in I got a little confused.
Here's what I have in it's most basic form.
<?php
createLogin('test', 'test2');
function createLogin($SQLConnection, $SQLConfig) {
echo "<h1> You are currently not logged in!</h1>";
echo "<form action='handleLogin(".$SQLConnection.",".$SQLConfig.") method='post'>";
echo "<div align='center'>";
echo "<table style='width: 475px'>";
echo "<thead>";
echo "<th>";
echo "<tr>Enter your e-mail and password.</tr>";
echo "</th>";
echo "</thead>";
echo "</table>";
echo "<input type='submit' value='Login' />";
echo "</form>";
}
function handleLogin($foo, $bar) {
echo $foo . " || " . $bar;
}
?>
When I click the submit button however, it simply takes me here...
http://localhost/handleLogin%28test,test2%29%20method=
Now, I read about using Javascript to do this, and to do something like
<script>
function processLoginRequest($SQLConnection, $SQLConfig) {
alert("<?php handleLogin($SQLConnection, $SQLConfig) ?>");
}
</script>
Then I could use
echo "<form action='processLoginRequest(".$SQLConnection.",".$SQLConfig.") method='post'>";
However, the code causes the entire php script to die. (Without error?)
You're using action incorrectly, and the result is as expected. action stores the page to which the form will be submitted. So, yes, when you hit submit it is trying to take you to a page called handleLogin%28test,test2%29%20method= because that is what your action says to do.
What you can do is simply leave the action blank, which will submit the form to the current page. Then, on that page, check if the form has been submitted, and if so, call your function.
Inside the function that creates the form make these changes:
function createLogin() {
...
echo "<form action='' method='post'>";
....
echo "<input type='submit' value='Login' name='login'/>";
}
Then, at the top of the page that renders the form, add something like this:
// Check if login form has been submitted - if so, handle
if (isset($_POST['login'])) {
handleLogin($SQLConnection, $SQLConfig);
}
// Render login form. No need to pass config parameters here.
createLogin();
If you really want to keep everything in a single function, I suppose you could also do it like this:
function createLogin($SQLConnection, $SQLConfig) {
if (isset($_POST['login'])) {
handleLogin($SQLConnection, $SQLConfig);
}
else {
echo "<h1> You are currently not logged in!</h1>";
echo "<form action='' method='post'>";
echo "<div align='center'>";
echo "<table style='width: 475px'>";
echo "<thead>";
echo "<th>";
echo "<tr>Enter your e-mail and password.</tr>";
echo "</th>";
echo "</thead>";
echo "</table>";
echo "<input type='submit' value='Login' name='login'/>";
echo "</form>";
}
}
You do NOT want to pass your SQL Configuration parameters back to JavaScript, because anyone can look at your JavaScript code when they browse your page, and then they'll have everything they need to connect and play around in your database.
You will have to pass some kind of flag to your form, to let your PHP code know (when it receives the form's data later) what kind of SQL settings it should use.
Example:
<form method="POST" ...>
<type input="hidden" name="loginMode" value="<?php echo $loginMode; ?>" />
</form>
Again, don't pass any sensitive data in there, just have some kind of unique value like "mySql" for $loginMode or the other options.
And then, when you're handling the HTTP POST in your PHP:
if ($_POST['loginMode'] == 'mySql')
{
// ... create connection based on $SQLConnection, $SQLConfig
}
else if ($_POST['loginMode'] == 'otherMethod') ...
Your JavaScript is probably failing because of the the contents of $SQLConnection and $SQLConfig. If you have a double quote in them it would fail.
Also designing and implementing a safe and robust login system is actually pretty difficult and you should opt using a framework that has been tested over time.