How to stop insert into after refreshing a page in php pdo - php

when i refresh page auto submit . how to stop insert data when page refresh ? i want insert data when click add button and without redirect another page.
plz help me. i want to came page display show data.
<?php
try{
$host='localhost';
$name='pdo';
$user='root';
$pass='';
$dbc = new PDO("mysql:host=$host;dbname=$name",$user,$pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
//---------------------------------------------------------------------
if (isset($_POST['add']))
{
$stmt = $dbc->prepare("insert into user (frist,last,web) values (:frist,:last,:web)");
$stmt->bindParam(':frist',$_POST['frist']);
$stmt->bindParam(':last',$_POST['last']);
$stmt->bindParam(':web',$_POST['web']);
$stmt->execute();
}
?>
<!DOCTYPE html>
<html>
<head>
<title> the digital craft - PDO</title>
</head>
<body>
<header>
<h1>Mysql PDO</h1>
</header>
<div>
<form method="post">
<input name="frist" placeholder="frist name">
<input name="last" placeholder="last name">
<input name="web" placeholder="web site">
<button name="add" type="submit">Add</button>
</form>
</div>
<hr>
<table>
<thead>
<tr>
<th>ID</th>
<th>Frist Name</th>
<th>Last Name</th>
<th>Website</th>
<th>Save</th>
</tr>
</thead>
<tbody>
<?php
$stmt=$dbc->query("SELECT * FROM user");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($data=$stmt->fetch()){
?>
enter code here<tr>
<td><input name="id" value="<?=$data['id']?>"></td>
<td><input name="frist" value="<?=$data['frist']?>"></td>
<td><input name="last" value="<?=$data['last']?>"></td>
<td><input name="web" value="<?=$data['web']?>"></td>
<td><button name="save" type="submit">save</button></td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>

You could redirect the user to other/same page after submit logic has been run. After that, refreshing shouldn't submit the form again.

A little addition to what Siim said:
you can do this with header("Location: name_of_file.php"); after $stmt->execute();

Related

Manipulating HTML code with external PHP file called from a form

I want to write a basic form with inputs that executes an external php file. That file should do some calculations with the inputs and append the output to a table.
My HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Prices</title>
</head>
<body>
<form name="priceform" method="get" action="add-item.php">
<input name="item_name" placeholder="Item Name">
<input name="amount" placeholder="Amount">
<input name="price_per_unit" placeholder="Price per Item">
<button type="submit" name="submit">Submit</button>
</form>
<div id="pricetable">
<table>
<thead>
<tr>
<th>Name</th>
<th>Amount</th>
<th>Netto</th>
</tr>
</thead>
<tbody>
<!-- Append rows here -->
</tbody>
</table>
</div>
My PHP Code
<?php
$item_name = $_GET["item_name"];
$amount = $_GET["amount"];
$price_per_unit = $_GET["price_per_unit"];
//do calculations
echo "
<tr>
<td>$item_name</td>
<td>$amount</td>
<td>$price_per_unit</td>
</tr>";
?>
I want the table row to append to my table in the html file.
Thanks for the help in advance.
You can merge these files together, or if you want external php file, you can just call it like this:
index.php:
...
<div id="pricetable">
<table>
<thead>
<tr>
<th>Name</th>
<th>Amount</th>
<th>Netto</th>
</tr>
</thead>
<tbody>
<?php include "calculate.php";?>
</tbody>
</table>
</div>
...
calculate.php is that calculation php file.
You can do this in two ways:
save the previously added lines somewhere (session, database?) and load them each time you refresh the page, adding a new line at the end with new data (and of course, re-save them with this new data)
or each time send previously added lines in the form. So you need to add a lot of hidden values to the form in which all previously submitted values will be stored.

Is this the correct syntax for config.php?

I am a complete php beginner. My trainer dived into it without much explanation.
Other php questions in stackoverflow seems to follow some other syntax, so I'm confused.
Below are config.php and index.php files. Database name is practice in this code.
Table name is fbsign. Trainer said values should be inserted into database but when I tried with table, it worked last time.
This is driving me crazy for half a day. I don't know what I am doing wrong.
Also, does field name in the database and php code should be the same?
Q update: Yes, I did run the code. It says,'connected but not saved'?
PS: I thought SOF is to help people. I wouldn't ask the question if I knew the answer.
<?php
$con=new mysqli('localhost','root','','practice') or die(mysqli_error());
if(!$con)
{
echo "not connected";
}
else
{
echo "connected";
}
?>
**index.php**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>sign up form</title>
</head>
<body>
<div id="content">
<h2>Create an account</h2>
<p>It's free and always will be.</p>
<form name="signup" method="post" action=" ">
<table>
<tr>
<td><input type="text" name="fname" placeholder="first
name" /></td>
</tr>
<tr>
<td><input type="text" name="sname"
placeholder="surname" /></td>
</tr>
<tr>
<td><input type="numbers" name="mob" placeholder="mobile
number or email address" /></td>
</tr>
<tr>
<td><input type="password" name="pass" placeholder="new
password" /></td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="Create
Account"/> </td>
</tr>
</table>
</form>
</div> <!-- end of content -->
</body>
</html>
<!-- start of php -->
<?php
include('config.php');
extract($_POST);
if(isset($submit))
{
$query="insert into fbsign values('$fname','$sname','$mob,'$pass')";
if($con->query($query))
{
echo "data saved";
}
else
{
echo "not saved";
}
}
?>
Syntax in the sense that it's the most common practice for formatting, layout and methods?
Possibly.
Is it secure and properly done?
Not at all.
For starters, try using PDO with prepared statements. You also pass raw, untreated user inputs to your data by using extract($_POST), extract() should never be used on user inputs either from a $_GET or $_POST request. Check out this post here for a details on sanatizing user inputs.
<?php
include('config.php');
if(isset($_POST['submit']))
{
$fname=$_POST['fname'];
$sname=$_POST['sname'];
$mob=$_POST['mob'];
$pass=$_POST['pass'];
$ins="insert into fbsign (fname,sname,mob,pass)values('$fname','$sname','$mob','$pass')";
$ex=$con->query($ins);
if($ex)
{
echo "successfully inserted::";
}
else
{
echo "ERROR::";
}
}
?>

how to stop data automatically insert into database in php

I have problem in this code.
In this code when i press save data button , the data insert into database but when i refresh page then it's automatically insert into database, what should i do in my code then stop automatically insert data into database, thanks in advance
<?php
require './database/databaseConnection.php';
if(isset($_POST['save_button']))
{
if(($_POST['fname']&&($_POST['lname'])))
{
$first_name=$_POST['fname'];
$last_name=$_POST['lname'];
$qry="INSERT INTO user_master(first_name,last_name) values('$first_name','$last_name')";
$result= mysql_query($qry)or die(mysql_error());
if($result){
echo 'SuccessFully saved data';
}
else{
echo 'Data Not Inserted!';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="bootStrap/css/bootstrap.min.css">
<link rel="stylesheet" href="bootStrap/css/bootstrap.css">
</head>
<body>
<div class="container jumbotron ">
<form action="" method="post">
<table class="table-responsive">
<div class="form-group form-inline">
<tbody>
<tr>
<td> <label for="fname" class="label-info">First Name</label></td>
<td><input class="form-control" type="text" name="fname"></td>
<td><label for="lname" class="label-info">Last Name</label></td>
<td><input class="form-control" type="text" name="lname"></td>
</tr>
</tbody>
</div>
</table>
<button type="submit" name="save_button" class="btn-success" >Save Data</button>
</form>
</div>
</body>
</html>
This is happening because your action is empty
Update your action to this
action="<?php echo $_SERVER['PHP_SELF']; ?>"
Make a separate php file that will insert data to database. Give this in the form action attribute.
<form action="insert.php" method="post">
......
......
</form>
insert.php file
<?php
require './database/databaseConnection.php';
if(isset($_POST['save_button']))
{
if(($_POST['fname']&&($_POST['lname'])))
{
$first_name=$_POST['fname'];
$last_name=$_POST['lname'];
$qry="INSERT INTO user_master(first_name,last_name) values('$first_name','$last_name')";
$result= mysqli_query($qry)or die(mysql_error());
if($result){
echo 'SuccessFully saved data';
}
else{
echo 'Data Not Inserted!';
}
}
}
?>
You can use header() to redirect to your previous page if you want. Thus not allowing the refreshing of insert.php
header("location: your_page.php");
it will be safe if you use Prepared Statements
Take a look

Unable to access fetch dBase data. The login page keep looping back to thesame page

Each time i tried to log in through : webhost/adminlogin.php , am redirected back to thesame page. Is there any thing i forgot to add? Thank you for your help.. Here is my script below
This is my adminlogin.php
<?php session_start(); if(isset($_SESSION[ 'admin_login'])) header( 'location:admin_homepage.php'); ?>
<!DOCTYPE html>
<html>
<head>
<noscript>
<meta http-equiv="refresh" content="0;url=no-js.php">
</noscript>
<meta charset="UTF-8">
<title>Admin Login - Online Banking</title>
<link rel="stylesheet" href="newcss.css">
</head>
<?php include 'header.php'; ?>
<div class='content'>
<div class="user_login">
<form action='' method='POST'>
<table align="center">
<tr>
<td><span class="caption">Admin Login</span>
</td>
</tr>
<tr>
<td colspan="2">
<hr>
</td>
</tr>
<tr>
<td>Username:</td>
</tr>
<tr>
<td>
<input type="text" name="uname" required>
</td>
</tr>
<tr>
<td>Password:</td>
</tr>
<tr>
<td>
<input type="password" name="pwd" required>
</td>
</tr>
<tr>
<td class="button1">
<input type="submit" name="submitBtn" value="Log In" class="button">
</td>
</tr>
</table>
</form>
</div>
</div>
<?php include 'footer.php'; ?>
<?php include '_inc/dbconn.php'; if(!isset($_SESSION[ 'admin_login'])){ if(isset($_REQUEST[ 'submitBtn'])){ $sql="SELECT * FROM admin WHERE id='1'" ; $result=mysql_query($sql); $rws=m ysql_fetch_array($result); $username=m ysql_real_escape_string($_REQUEST[
'uname']); $password=m ysql_real_escape_string($_REQUEST[ 'pwd']); if($username==$rws[8] && $password==$rws[9]) { $_SESSION[ 'admin_login']=1; header( 'location:admin_hompage.php'); } else header( 'location:adminlogin.php'); } } else { header(
'location:admin_hompage.php'); } ?>
I think there may be a few issues with your script. One obvious one is that you are outputting html content before you send the headers at the bottom of the script.
HTTP headers must be sent to the client before any other content.
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.
I would suggest that unless you need to continue processing. You move all your login code to the top of the script and call 'exit()'; after you have sent the headers to the client to prevent any further processing or content being sent to the client.

showing div near save button if condition is true

I have simple code in php to enter name and address to the database.If name is already present in the database printing the message saying that it is already present ,if not entering data into database.But i want message has to be displayed near save button
<form method="POST" action="" >
<table>
<tr>
<td><br>Name t</td><td><br><input type="text" name="Name" id="wgtmsr" required/></td>
</tr>
<tr>
<td><br>Address</td>
<td><br/><textarea rows="3" cols="33" name="Address" id="inc_address" required></textarea></td>
</tr>
<tr>
<td><br></td><td><input type="submit" class="sav" name="rep" value="Save" id="btnsize" /></td>
</tr>
</table>
<?php
if (isset($_POST['rep']))
{
$Name=$_POST['Name'];
$Address=$_POST['Address'];
try{
$test=/* query check if name already present in database*/
if(!$test)
{
/*then insert into database*/
}else{
?> <div id="msg">
<?php echo "alreday present";?>
</div>
<?php
}
}catch(Exception $e) {
//echo "Error ".$e->getMessage();
}
}
But div is coming above the table.Please give suggestions so how can i style it near the save button
style:
#msg
{
color:#EA6262;
font-size:14pt;
margin-left:27% ;
margin-bttom:5% ;
}
Insert div after save button like
<input type="submit" class="sav" name="rep" value="Save" id="btnsize" /><span class="err" id="add_err"></span>
You can print the error using javascript.
document.getElementById("add_err").innerHTML = "Already having name!";
I tried similar thing its working
<?php
/**
* Created by PhpStorm.
* User: root
* Date: 3/9/15
* Time: 4:03 PM
*/
?>
<html>
<head>
<title></title>
</head>
<body>
<form>
<input type="submit" name="submit" /><span class="adderr" name="adderr" id="adderr"></span>
</form>
<?php
$var=0;
if($var==0)
{?>
<script>
document.getElementById("adderr").innerHTML = "Already having name!";
</script>
<?php
}
?>
</body>
</html>
It works fine

Categories