PHP insert data to Mysql - php

I am experimenting with PHP and Mysql. I have created a database and table at mu localhost using xampp. I have also created a file that suppose to populate my table by executing a query, but the strange thing is that i get no errors but at the same time no DATA has been inserted into my DataBase:
CODE:
register.php:
<?php
session_start();
if(isset($_POST['submitted'])){
include('connectDB.php');
$UserN = $_POST['username'];
$Upass = $_POST['password'];
$Ufn = $_POST['first_name'];
$Uln = $_POST['last_name'];
$Uemail = $_POST['email'];
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, emial) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
if(!mysql_query($NewAccountQuery)){
die(mysql_error());
}//end of nested if statment
$newrecord = "1 record added to the database";
}//end of if statment
?>
<html>
<head>
<title>Home Page</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Create Account</h1>
<div id="login">
<ul id="login">
<form method="post" action="register.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input type="submit" submit="submit" value="Create Account" class="button">
</form>
</div>
<form action="index.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="Cancel" onclick="index.php" class="button">
</li>
</ul>
</div>
</article>
<aside>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
I have also one include file which is connectDB:
<?php
session_start();
$con = mysql_connect("127.0.0.1", "root", "");
if(!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("eshop", $con) or die("Cannot select DB");
?>
Database structure:
database Name: eshop;
only one table in DB : users;
users table consists of:
user_id: A_I , PK
username
password
first_name
last_name
email
I spend a substantial amount of time to work this out did research and looked at some tutorials but with no luck
Can anyone spot what is the root of my problem...?

It is because if(isset($_POST['submitted'])){
you dont have input field with name submitted give the submit button name to submitted
<input name="submitted" type="submit" submit="submit" value="Create Account" class="button">
Check your insert query you have more fields than your values
Change :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
to :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('','$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
Considering user_id is auto increment field.
Your email in query is written wrongly as emial.

Is error reporting turned on?
Put this on the top of your screen:
error_reporting(E_ALL);
ini_set('display_errors', '1');

Some good answers above, but I would also suggest you make use of newer MySQLi / PDO instead of outdated 2002 MySQL API.
Some examples: (i will use mysqli since you wrote your original example in procedural code)
connectDB.php
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>
this should work quite nicely and all you need to add is your proper posted values and build the form to post it, that's all.

<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);`enter code here`
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>

Related

Get Always Validation Error in Login Page Even Correct Data is Given

Following is the Code for LOGIN page used with html & php.
The problem I am facing is that , even after submitting correct information Login is failed .
Is there any problem with the query I used?
<html>
<head>
<title>login</title>
<link rel="stylesheet" href="css/insert.css" />
</head>
<body>
<div class="maindiv">
<!--HTML form -->
<div class="form_div">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <!-- method can be set POST for hiding values in URL-->
<h2>Login Form</h2>
<label>Email:</label><br />
<input class="input" type="email" name="mail" />
<br />
<label>Password:</label><br />
<input class="input" type="text" name="pass" />
<br />
<input class="submit" type="submit" name="submit" value="Login" />
PHP
//Selecting Database from Server
$db = mysql_select_db("tanni", $connection);
if(isset($_POST['submit'])){
//Fetching variables of the form which travels in URL
$mail = $_POST['mail'];
$pass = $_POST['pass'];
if($mail!=''&&$pass!=''){
$query=mysql_query("SELECT* FROM user WHERE mail='".$mail."' and pass='".$pass."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res){
$_SESSION['mail']=$mail;
}else {
echo'You entered username or password is incorrect';
}
}else{
echo'Enter both username and password';
}
}
//Closing Connection with Server
mysql_close($connection);
?>
</form>
</div>
<div class="formget"><a href=http://www.formget.com/app><img src="formget.jpg" alt="Online Form Builder"/></a>
</div>
</div>
</body>
</html>
What is the problem in the code?
Need space between select and * at SELECT* FROM
Your query would be
SELECT * FROM user WHERE...
Use mysql_num_rows() to check number of rows return from your query instead mysql_fetch_row
mysql is deprecated instead use mysqli or PDO
You need to start session at the top of your page
session_start();
Don't store plain password into database use password hashing technique
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/faq.passwords.php
Your code is open for sql injection read
How can I prevent SQL injection in PHP?
Your whole code would be
<?php
session_start();
//Establishing Connection with Server
$connection = mysql_connect("localhost", "root", "");
//Selecting Database from Server
$db = mysql_select_db("tanni", $connection);
if (isset($_POST['submit'])) {
//Fetching variables of the form which travels in URL
$mail = $_POST['mail'];
$pass = $_POST['pass'];
if ($mail != '' && $pass != '') {
$query = mysql_query("SELECT * FROM user WHERE mail='" . $mail . "' and pass='" . $pass . "'") or die(mysql_error());
$res = mysql_num_rows_row($query);
if ($res == 1) {
$_SESSION['mail'] = $mail;
} else {
echo'You entered username or password is incorrect';
}
} else {
echo'Enter both username and password';
}
}
//Closing Connection with Server
mysql_close($connection);
?>

Failed Mysqli query in login php script : cannot successfully login

I have this PhP script called checklogin.php which is supposed to query 'Email' and 'motdepasse' values from a table called 'membres' (not members), the variables type are varchar (50) for Email and char (120) for motdepasse.
index.html :
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<title> Welcome to Pop </title>
<link href="normalize.css" rel="stylesheet" />
<link href="style.css" rel="stylesheet" />
</head>
<body>
<form action = "checklogin.php" method="post" name="login_form">
<section class="loginform cf">
<ul>
<li><label for="usermail">Email</label> <input name="usermail" placeholder="yourname#email.com" required="" type="email" /></li>
</ul>
<ul>
<li><label for="password">Password</label> <input name="password" placeholder="password" required="" type="password" /></li>
<li></li>
</ul>
<input type="submit" name="submit" value="Login" />
<ul>
</ul>
<p><a accesskey="N" href="Newaccount.html" title="Redirecting ">Create an account</a></p>
</section>
</form>
</body>
</html>
checklogin.php :
<?php
session_start();
$link = new MySQLi("localhost", "DBusername", "DBpassword", "DBname") ;
error_reporting(E_ALL);
if ( mysqli_connect_error() )
{
$logmessage = 'MySQL error : ' . mysqli_connect_error() ;
die('could not connect to database');
}
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$query= "SELECT Email, motdepasse FROM membres WHERE Email='".$Email."' AND motdepasse='".$Password."' LIMIT 1 ";
if ($result = mysqli_query($link,$query ))
{
if( mysqli_num_rows($result) == 1 )
{
echo "login successful" ;
}
else
{
echo "wrong username or password" ;
}
}
else
{
echo' Couldnt select from table. Please check query';
}
?>
My problem is that even though the connection to the DB is made without any problem whatsoever, I get the wrong username/password message even when information typed are matching the ones in 'membres' , Email and motdepasse columns. I since added error report function but only get notices.
In your HTML there are inputs named usermail and password but in your PHP code you are trying to get $_POST['Email'] and $_POST['Password']. So just change that two lines to this:
$Email = $_POST['usermail'];
$Password = $_POST['password'];
you send data from form like
<input name="usermail" ...
so the variable is usermail but in your script you handle $_POST['Email'] and it really does not exist... first check your names of your form elements and debug what you sent via top line
var_dump($_POST); exit();
tip: always test what you have with what you expect and compare

Querying another table after login

This seems like it should be simple, but I've tried it every which way and can't seem to get it to work.
I have this login script which I adapted from an online tutorial. What I'd like to do is have users sign in with a username and password, and if these are correct, have it go after their lab results in another table (same database) and display them. I can get it to sign in, but that's it. Here's the login code:
<?php //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
/*This is where I'm assuming the new query needs to go.
Query a different table named "data" and pick out information according to
$username which was put in earlier */
echo "<br><a href='logout.php'>Logout</a>";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password   :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div><?php }
?>
</body>
</html>
A "Join" is what I get when I google it but that doesn't seem right. Could someone help?
You can just use a different query for making it easy:
$sql = mysql_query("SELECT * FROM data WHERE user = '" . mysql_real_escape_string($username) . "'");
Then you can process with this.
Please note that you should not use MySQL driver as it is deprecated, use MySQLi(mproved) instead. And you should escape the POSTed values, this is very important!
Your last else statement is trying to echo the HTML.
You should be using mysqli or PDO since mysql is deprecated.
<?php //Start the Session
session_start();
// require('connect.php');
// Establish connection with database
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `people` WHERE username='$username' and password='$password'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$count = mysqli_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
echo "Valid";
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
echo "Username: $username";
echo "Session Username:".$_SESSION['username'];
// This is where I'm assuming the new query needs to go.
// Query a different table named "data" and pick out information according to $username which was put in earlier
echo "
Logout";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="test.php" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div>
</body>
</html>

Trying to delete a member from the database

I am having some trouble trying to delete a member from the database I'm using, I don't think it is getting the Username correctly. Here is the form I am using for HTML
deleteForm.php
<?php
//begin our session
session_start();
?>
<html>
<head>
<title>Welcome</title>
</head>
<form action="deleteUser.php">
<p>
<center><label for="Username">Enter username to delete</center></label>
<center><input type="text" id="Username" name="Username" value="" maxlength="20" /></center>
<center><input type="submit" value="Delete Member"></center>
</p>
</form>
</body>
</html>
And this is the code to handle the deletion itself:
deleteUser.php
<?php
//begin our session
session_start();
//Check if username, password have been sent
if((!filter_input(INPUT_POST, 'Username')))
{
echo 'Please enter a valid username';
}
else
{
//Enter the valid data into the database
$memberUsername = filter_input(INPUT_POST, 'Username', FILTER_SANITIZE_STRING);
echo $memberUsername;
$SQLhostname = "****";
$SQLusername = "****";
$SQLpassword = "****";
$databaseName = "****";
try
{
echo "in the try block";
// Create connection
$conn = mysqli_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect MySQL");
$db_selected = mysqli_select_db($conn, $databaseName)
or die("Could not select database");
$deleteMember = "DELETE FROM customers
WHERE name =
'$memberUsername'";
$result = $conn->query($deleteMember);
if(! $result ){
die('Could not delete member: ' . $conn->error);}
else{
echo "Member deleted <br/>";
}
mysqli_close($conn);
}
catch (Exception $ex)
{
//To be added
}
}
?>
The problem is it always enters the if statement and asks for a valid username which I'm assuming is not being set.
Add method attribute to your form.
<form action="deleteUser.php" method="post">
<!--^^^^^^^^^^-->
<p>
<center><label for="Username">Enter username to delete</center></label>
<center><input type="text" id="Username" name="Username" value="" maxlength="20" /></center>
<center><input type="submit" value="Delete Member"></center>
</p>
Just as a quick FYI:
Whenever a method is omitted in a form, it defaults to GET and you're using INPUT_POST therefore you should either be using INPUT_GET or add a post method, i.e: method="post".
Consult the manual:
http://php.net/manual/en/function.filter-input.php
Plus, and for your added safety, your code is open SQL injection. Do use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
in the form tag add "method" attribute:
<form ... method="POST">
In the PHP script you van find the value of inputs in the variable $_GET:
$_GET[Username'']
Kevin

PHP error whilst confirming successful row insertion

people
Overview i am crating a dummy website for learning purposes therefore its functionalists are basic and security in not on the agenda atm.
I am experiencing this minor problem that i cant resolve. So why i am trying to do is to add a new account and echo a message saying that the insertion was suspenseful, but i get an error message in a place where i want to add a new record saying that the variable which suppose to hold the message is undefined.
A lil more: So when i am in the Home page of the wbesite and click a register button that is when the error message pops up but when i actually submit a query to add a account that error message changes to the message i want to show.
<?php
if(isset($_POST['submited'])){
include('connect_mysql.php');
$username= $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$email = $_POST['email'];
$NewAccountQuery = "INSERT INTO users (username, password, first_name, last_name, email) VALUES ('$username','$password', '$firstname', '$lastname', '$email')";
if(!mysql_query($NewAccountQuery)){
die(mysql_error());
}//end of nested if statment
if($NewAccountQuery){
echo $confirm = "1 record added to the database";
}
}//end of if statment
?>
<html>
<head>
<title>Home Page</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Create Account</h1>
<div id="login">
<ul id="login">
<form method="post" action="register.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input name="submited" type="submit" submit="submit" value="Create Account" class="button">
</form>
</div>
<form action="index.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="back" onclick="index.php" class="button">
</li>
</ul>
</div>
</form>
</article>
<aside>
<?php print $confirm; ?>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
ok here is the image before i submit the query:
Image after i submit the query:
echo $confirm = "1 record added to the database";
Should be:
$confirm = "1 record added to the database";
echo $confirm;
It looks like you don't need the echo there as you echo it else where. If all you want to do is assign $confirm to 1 record added to the database, then you just need to assign it, without the echo. Echo basically outputs it to the html in the same way print does.
I think that the error message is pretty clear. $confirm is not defined. You only define it in the "successful query" section. A simple solution is to define it before the entire if(isset($_POST['submited'])){ block. Just put $confirm = ''; and nothing will be printed out.
Some notes:
Since you are learning and this is all new, you should stop using ext/mysql now and use PDO or mysqli as your DB engine (I prefer the former).
Also, if($NewAccountQuery){ is not very meaningful. It will always be true since it's just a string you define earlier. If you switch to PDO you could check PDOStatement::rowCount.
Basically the problem is when you load the homepage for the first time - it won't go into the if(isset($_POST['submited'])) condition since $_POST['submitted'] is not set. And since you are setting the $confirm inside this loop, This statement <?php print $confirm; ?> won't find $confirm variable set. Hence it will give out PHP NOTICE.. So like someone said here either set $confirm = ''; before if condition or you can do something like this while printing
<?php
if(isset($confirm))
print $confirm;
?>
If you are just echoing or printing the string you don't need to assign it to a variable first. Either of these would work:
echo '1 record added to the database';
OR
$confirm = '1 record added to the database';
echo $confirm;
<?php
if(isset($_POST['submited'])){
include('connect_mysql.php');
$username= $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$email = $_POST['email'];
$NewAccountQuery = "INSERT INTO users VALUES ('$username','$password', '$firstname', '$lastname', '$email')"; // simplified query if those are only 5 cols in order
$result = mysql_query($NewAccountQuery);
if($result){
$confirm = "1 record added to the database";
} else {
exit('error inserting row');
}
}
?>

Categories