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::";
}
}
?>
Related
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
Hi I have meet a problem here.
I need to log in an account here
but after i key in all the details and click Sign-In the page will redirect me back to the log in page. But actually the account is already logged in just that it cant redirect back to the Home Page after log in.
What problem is this? Im using Session.
and i put my session_start in connect.php(which is use to connect to database)
Below is The Code
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
//Code Refer to http://www.w3schools.com/php/func_http_setcookie.asp
if(isset($_SESSION['user'])!="")
{
header("Location: Home.php");
}
if(isset($_POST['btn-login']))
{
$username = mysql_real_escape_string($_POST['username']);
$upass = mysql_real_escape_string($_POST['password']);
$res=mysql_query("SELECT * FROM user WHERE u_username='$username'");
$row=mysql_fetch_array($res);
if($row['u_password']==md5($upass))
{
$_SESSION['user'] = $row['u_ID'];
header("Location: Home.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
?>
<?php
$year = time() + 31536000;
setcookie('rememberme', $_POST['username'], $year);
if ($_POST['rememberme'])
{
setcookie ('rememberme',$_POST['username'], $year);
}
else
{
setcookie(rememberme, $past);
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link rel="stylesheet" href="Style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>AngelService</label><br/>
<p>Royal Borough of Greenwich</p>
</div>
</div>
<center> Home Page | View Post | Post A Service</center>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="username" placeholder="Your Username" required value="<?php
echo $_COOKIE['rememberme']; ?>"/>
</td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Your Password" required />
</td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td>
<input type="checkbox" name="rememberme" value="rememberme" style="font- size:6px;"> Remember Me<br>
</td>
</tr>
<tr>
<td>
Sign Up Here</td>
</tr>
</table>
</form>
</div>
</center>
<div id="footer">
<div id="center" align="center">
<br/>
<p>Angel Services | Royal Borough of Greenwich | Created By UOG Student: Kuai Boon Ting</p>
</div>
</div>
</body>
</html>
You are missing action="Your redirection page" in form tag i.e.,
<form method="post" action="forexample-Home.php">
.....
</form>
There are several things you can do to improve your code. For starters, you do not need to close and open PHP tags directly after each other, like you have
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
could just be
<?php error_reporting(0);
include_once 'connect.php';
The statement if(isset($_SESSION['user'])!="") doesn't do exactly what you think it does. isset($_SESSION['user']) returns a boolean (true/false), so checking whether or not a boolean is empty won't work. You can do if (!empty($_SESSION['user'])) {... to check if it's set and if it's empty or not. Check out the documentation for isset() and documentation for empty().
For your actual problem though: Note also that your header(); functions cannot be called after any output is made to the browser (any whitespace, HTML or PHP echo). This would appear as a PHP Warning, which will be reported should you put error_reporting(-1); instead of ignoring all errors (as you currently are doing with having error_reporting set to 0).
The other answer suggested using the HTML action-attribute for the form, but in case the login is invalid, it's best to have it sent to the same page, and only redirect should the login be valid. This is called "validate and redirect".
These pointers below are just to improve your code, and not necessarily the cause of your problem.
If you want to set a cookie, it has to be done before any and all output is sent to the browser (see this post), so in case the if($row['u_password']==md5($upass)) statement fails, and it enters the else-brackets, your cookie will not be set.
You should stop using mysql_* functions if you can. They are deprecated, and will be removed in the future. Switch over to mysqli_* or PDO instead. (Check out this post).
Usage of md5 hashing is not that secure. If you have PHP 5.5.0 or higher, you should perhaps look into usage of password_hash and password_verify
After every header("Location: ...."); you should always put a exit;, so that the code stops executing after it's redirecting. (Check out this post).
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.
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
I have a billing page which fetches data from the cart.
I am having a problem submitting these values to the database. How do i correct my php to get it to submit to the database correctly?
For example, i have a transactions table in my database, and i want all payment details to go there, which can later be fetched and outputted in the admin section as a receipt of order.
I cannot get the name, address, email, phone to submit correctly. It comes up with 0 in the database, how do i fix this?
How can i specifically use AJAX when the button is clicked to show a loading bar/page and then the success message?
I also get the error:
Notice: Undefined index: command in F:\xamppnew\htdocs\web\billing.php on line 5
Code:
<?php
include "storescripts/connect_to_mysql.php";
session_start();
if($_REQUEST['command']=='update'){
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$address=$_REQUEST['address'];
$phone=$_REQUEST['phone'];
$item_id = $_SESSION['item_id'];
$quantityorder = $each_item['quantity'] = $_SESSION['quantity1'];
$cartTotal = $_SESSION['cartTotal'];
// Add this product into the database now
$sql = mysqli_query($link,"insert into transactions values('','$item_id','$quantityorder','$cartTotal','$name','$address','$email','$phone')");
die('Thank You! your order has been placed!');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />
<title>Billing Info</title>
<script language="javascript">
function validate(){
var f=document.form1;
if(f.name.value==''){
alert('Your name is required');
f.name.focus();
return false;
}
f.command.value='update';
f.submit();
}
</script>
</head>
<body>
<div align="center" id="mainWrapper">
<?php include_once("template_header.php");?>
<div id="pageContent">
<div style="margin:24px; text-align:left;">
<br />
<form name="form1" onsubmit="return validate()">
<input type="hidden" name="command" />
<div align="center">
<h1 align="center">Billing Info</h1>
<table border="0" cellpadding="2px">
<tr><td>Product ID:</td><td><?php echo $item_id = $_SESSION['item_id'];?></td></tr>
<tr><td>Total Quantity:</td><td><?php echo $each_item['quantity'] = $_SESSION['quantity1']; ?></td></tr>
<tr><td>Order Total:</td><td>£<?php echo $cartTotal = $_SESSION['cartTotal'];?></td></tr>
<tr><td>Your Name:</td><td><input type="text" name="name" /></td></tr>
<tr><td>Address:</td><td><input type="text" name="address" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone" /></td></tr>
<tr><td> </td><td><input type="submit" value="Place Order" /></td></tr>
</table>
</div>
</div>
<?php include_once("template_footer.php");?>
</form>
</body>
</html>
did you use Mysqli to connect ?
if yes, change mysql_query to mysqli_query
and you need to add 'name' attribute to the submit button
and do this
if(isset($_POST['submit'])){....
It is a good practice to use addslashes over your values before concat them in an sql query
$name = addslashes($_REQUEST['name']);
$email = addslashes($_REQUEST['email']);
$address = addslashes($_REQUEST['address']);
$phone = addslashes($_REQUEST['phone']);