Below is my Html and php code both in separate files for my insert query it is trying to insert registration details but it keeps failing, any reasons where i am going wrong.
I have trying using different types of speech marks but it still doesnt work and the textbook i have shows this method. The database can log users in and check if user exists but can not insert data. Thanks.
<?php
include 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<?php
include 'header.php';
?>
<div id="logincontent">
<div id="registerform" class="loginform-in">
<h1>Registration</h1>
<fieldset>
<form id="myForm" action="registerscript.php" method="POST">
Email: <input type="text" name="username"/><br />
Password: <input type="password" name="pass"/><br />
First Name: <input type="text" name="fname"/><br />
Last Name: <input type="text" name="lname"/><br />
Address 1: <input type="text" name="add1"/><br />
Address 2: <input type="text" name="add2"/><br />
Postcode: <input type="text" name="pcode"/><br />
Telephone: <input type="text" name="phone"/><br />
<button id="submit">Register</button>
</form>
<div id="ack"></div>
</fieldset>
</div>
</div>
</body>
</html>
PHP File
<?php
include('db.php');
$email = mysql_real_escape_string( $_POST["username"] );
$pass = mysql_real_escape_string( md5($_POST["pass"]) );
$firstname = mysql_real_escape_string( $_POST["fname"] );
$surname = mysql_real_escape_string( $_POST["lname"] );
$add1 = mysql_real_escape_string( $_POST["add1"] );
$add2 = mysql_real_escape_string( $_POST["add2"] );
$pcode = mysql_real_escape_string( $_POST["pcode"] );
$phone = mysql_real_escape_string( $_POST["phone"] );
if( empty($email) || empty($pass) )
{
echo "Email and Password are Mandatory";
exit();
}
$res = mysql_query("SELECT email FROM members WHERE email='$email'");
$row = mysql_fetch_row($res);
if( $row > 0 )
echo "The Email $email has already been taken. Click Forgot Password to Retrieve";
else
{
$sql = "INSERT INTO members (memberid, firstname, surname, address1, address2, postcode, telephone, email, password) VALUES (
'',
'$firstname',
'$surname',
'$add1',
'$add2',
'$pcode',
'$phone',
'$email'
'$pass')";
if( mysql_query($sql) )
echo "Registration Successfull";
else
echo "An Error Occured Please Try Again";
}
?>
You missed a comma here
'$phone',
'$email', //<-------------- Here
'$pass')";
Remove memberid from $sql = insert into ... this is probably an auto_increment type value in your mysql database.
BTW you are better off using mysqli or pdo instead of using mysql_. And with prepared statements you would limit the risk for SQL injection.
Add the following to find MySQL Error:
else
echo "An Error Occured Please Try Again";
echo mysql_errno($res) . mysql_error($res);
Related
I am new to PHP and web development, and trying to create an HTML form that will submit data into MYSQL.
Upon checking phpmyadmin after submission of the form, it shows that there has been a row submitted,
however the row is completely blank. I had a problem before this one, that instead of a blank row, it would be "1" submitting instead of the data inserted into the HTML form. Now, no data submits into the database.
Here is the PHP:
<?php
Include("connection.php");
// HTML Identification
$lname = isset($_POST['lastname']);
$fname = isset($_POST['firstname']);
$email = isset($_POST['email']);
$phone = isset($_POST['phonenum']);
$addr = isset($_POST['address']);
$city = isset($_POST['city']);
$state = isset($_POST['state']);
$zip = isset($_POST['zipcode']);
//Database Insertion
$sql= "INSERT INTO CustomerInfo (LastName, FirstName, Email, PhoneNum, Address, City, State, ZipCode)
VALUES ('$lname', '$fname', '$email', '$phone', '$addr', '$city', '$state', '$zip')";
// Insertion
$ds= mysqli_query($conn, $sql);
// - Insertion Confirmation
if($ds)
{
print 'Row Inserted!';
print ' Response Recorded!';
}
?>
The HTML Form:
!DOCTYPE html>
<html>
<head>
<title> GS Entry Form </title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css#2/out/water.css" </link>
<style>
h1 {text-align: center;}
h2 {text-align: center;}
</style>
</head>
<body>
<h1>Customer Entry Form</h1>
<h2>Please Input Contact Information</h2>
<form action="database.php" method="POST">
First Name:<br />
<input type="text" name="firstname" />
<br /><br />
Last Name:<br />
<input type="text" name="lastname" />
<br /><br />
Email:<br />
<input type="text" name="email" />
<br /><br />
Phone Number:<br />
<input type="text" name="phonenum"/>
<br /><br />
Address:<br />
<input type="text" name="address"/>
<br /><br />
City:<br />
<input type="text" name="city"/>
<br /><br />
State:<br />
<input type="text" name="state"/>
<br /><br />
Zip Code:<br />
<input type="text" name="zipcode"/>
<br /><br />
<button type="button" name= "submit" value= "submit" />
</form>
</body>
</html>
Here, also, is the connection.php referenced:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create Connection
$conn= mysqli_connect("$servername:3306","$username","$password","$dbname");
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " .$conn->connect_error);
}
else echo "Connection successful! "
?>
I don't think it has anything to do with the connection, but I figured I would post it to cover all the bases. The attached imgur picture is what my database has been looking like after submissions have been made.
I truly am not sure what to do now, any help would be greatly appreciated.
Thank you! -G
EDIT:
This is what my PHP code looks like after the changes suggested from #EinLinuus:
<?php
Include("connection.php");
// HTML Identification POST
if(isset($_POST['firstname'])) {
$fname = $_POST['firstname'];
}else{
die("Firstname is missing");
}
if(isset($_POST['lastname'])) {
$lname = $_POST['lastname'];
}else{
die("Lastname is missing");
}
if(isset($_POST['email'])) {
$email = $_POST['email'];
}else{
die("Email is missing");
}
if(isset($_POST['phone'])) {
$phone = $_POST['phone'];
}else{
die("Phone Number is missing");
}
if(isset($_POST['addr'])) {
$addr = $_POST['addr'];
}else{
die("Address is missing");
}
if(isset($_POST['city'])) {
$city = $_POST['city'];
}else{
die("City is missing");
}
if(isset($_POST['state'])) {
$state = $_POST['state'];
}else{
die("State is missing");
}
if(isset($_POST['zip'])) {
$zip = $_POST['zip'];
}else{
die("Zip Code is missing");
}
//Database Insertion
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt= $conn->prepare("INSERT INTO CustomerInfo(FirstName, LastName, Email, PhoneNum, Address, City, State, ZipCode) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssssss', $fname, $lname, $email, $phone, $addr, $city, $state, $zip);
$stmt->execute();
// Insertion
$sql= mysqli_query($conn, $stmt);
// - Insertion Confirmation
if($ds)
{
print 'Row Inserted!';
print ' Response Recorded!';
}
$stmt->close();
$conn->close();
?>
My HTML remains the same, besides adding ID attributes to each variable to no effect. I appreciate the help!
The isset function returns if the variable is declared or not -> the return type is a boolean.
$test = [
"hello" => "world"
];
var_dump(isset($test["hello"])); // bool(true)
var_dump(isset($test["something"])); // bool(false)
You can use isset to check if the field exists in the $_POST variable, but don't save the result of the isset function to the database. If you do so, the boolean will be converted to a number (true => 1, false => 0) and this number gets stored in the database.
Example:
if(isset($_POST['lastname'])) {
die("lastnameis missing");
}
$lname = $_POST['lastname'];
Security
This code is vulnerable to SQL Injections. You should never trust user input. I'd recommend to use prepared statements here:
$stmt = $mysqli->prepare("INSERT INTO CustomerInfo (LastName, FirstName, ...) VALUES (?, ?, ...)");
$stmt->execute([$lname, $fname]);
In the SQL statement, replace the actual values with ?. Now you can execute the statement and pass the values to the execute function. In the example above, $lname will replace the first ?, $fname the second, ...
I'm trying to create a very basic registration and login system in PHP. I am very new to this, so I followed a video on YouTube. I'm guessing my problem is that I'm using some function that may have been depreciated in PHP 7. I have included the code I have below. What should I correct? I know I don't have much error handling or such yet. I just want to get the basics down and create a page where the user can register, login, and then have their user id or name displayed on the page. I got that part to work, but nothing shows up in the database when I log in. Also, how do you get the host name? I'm using a webhosting service, and not working locally. Thank you for your help!
dbh.php:
<?php
$conn = mysqli_connect("localhost", "usernamehere", "passwordhere",
"mylogindatabase");
if(!$conn)
{
die("Connection failed: ".mysqli_connect_error());
}
?>
welcome.php:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="login.php" method="POST">
<input type="text" name="uid" placeholder="Username">
<br />
<input type="password" name="pwd" placeholder="Password">
<br />
<button type="submit">LOGIN</button>
</form>
<?php
if(isset($_SESSION['id']))
{echo $_SESSION['id'];}
else{
echo "You are not logged in!";
}
?>
<br />
<br />
<br />
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="First Name">
<br />
<input type="text" name="last" placeholder="Last Name">
<br />
<input type="text" name="uid" placeholder="Username">
<br />
<input type="password" name="pwd" placeholder="Password">
<br />
<button type="submit">SIGN UP</button>
</form>
<br />
<br />
<br />
<form action="logout.php">
<button>Log Out</button>
</form>
</body>
</html>
signup.php:
<?php
session_start();
include 'dbh.php';
$first = $_POST['first'];
$last = $_POST['last'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
echo $first;
echo $last;
echo $uid;
echo $pwd;
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first, $last, $uid, $pwd')";
$result = $conn->query($sql);
header("Location: welcome.php");
?>
login.php:
<?php
session_start();
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
echo $first;
echo $last;
echo $uid;
echo $pwd;
$sql = "SELECT * FROM user WHERE uid='$uid' AND
pwd='$pwd'";
$result = $conn->query($sql);
if(!$row = $result->fetch_assoc())
{
echo "Your username or password is incorrect!";
} else{
$_SESSION['id'] = $row['id'];
}
header("Location: welcome.php");
?>
logout.php:
<?php
session_start();
session_destroy();
header("Location: welcome.php")
?>
Your insert query should be like this :
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
Read this for host : http://php.net/manual/en/function.gethostname.php
EDIT: While this will work and will execute correctly, be warned that
your application will be vulnerable to SQL injection attacks without
the proper countermeasures, so when using MySQLi try to use prepared
statements instead of concatenated queries as they are vulnerable
against SQL injection. This might seem complicated and tedious at
first for beginners, but it is very necessary to keep your application
secure. You can use either prepared statements which are preferable or
simply escape the variables (less secure)
Read more here:
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/mysqli.real-escape-string.php
you have small error in your sql query
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
learn more about sql inset query at
http://www.w3schools.com/sql/sql_insert.asp
You have typo mistake in your code. You forgot quotes in your query
So instead of this
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first, $last, $uid, $pwd')";
use this
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
Also,if you want to explore more then you can see this docs
Maybe you forget in :
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first, $last, $uid, $pwd')";
Your query should be:
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
If you need the example of how to create login multiuser, read more:
Detailed Technology Center
I am inserting data in my WAMP database from user input:
PHP
<?php
$con=mysqli_connect("127.0.0.1","beni","2155","visitbulgaria");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$forename = mysqli_real_escape_string($con,$_POST['Forename']);
$surname = mysqli_real_escape_string($con,$_POST['Surname']);
$email = mysqli_real_escape_string($con,$_POST['Email']);
$username = mysqli_real_escape_string ($con,$_POST['Username']);
$password = mysqli_real_escape_string ($con,$_POST['Password']);
$sql="INSERT INTO `customer`(`Forename`, `Surname`, `Email`, `Username`, `Password`)
VALUES ('$forename', '$surname', '$email', '$username', '$password')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
HTML
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="Forename">
Lastname: <input type="text" name="Surname">
Email: <input type="text" name="Email">
username: <input type="text" name="Username">
pass: <input type="text" name="Password">
<input type="submit">
</form>
</body>
</html>
whah happens here is that on submit it does work but when I look at the database in phpMyAdmin it has only added the first three record (forename, surname and email and then the username and password field are left blank, and I have no idea how to fix that and why it is doing it.
So here I am trying to create a logbook with some simple php.
The problem is that nothing is being added to the database I created. Whenever I check the database I just keep getting an empty dataset after adding and submitting text on the guestbook form.
Can anybody see any problems with my code?
<?php
$sql = mysql_connect("localhost" , "root") or die(mysql_error);
mysql_select_db("guestbook" , $sql);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
echo ("Message succesfully added.");
}
?>
<html>
<head>
<title>Guestbook</title>
</head>
<form action="index.php" method="post">
Name: <input type="text" name="name"/><br>
Email: <input type="text" name="email"/><br>
<input type="submit" value="Post!"/>
</form>
</html>
<?php
$result = mysql_query("SELECT * FROM message ORDER BY id DESC");
while($row = mysql_fetch_array($result))
{
?>
<table>
<tr>
<td>Name:</td>
<td><?php echo $row['name'] ?></td>
</tr>
<tr>
<td>Message:</td>
<td><?php echo $row['email'] ?></td>
</tr>
</table>
<?php
}
?>
Replace
mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email'");
With
mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
I think that name is a reserved word in mysql isn't it?
you might have to modify your inset script as follows:
$query = mysql_query("INSERT INTO message (`name` , email) VALUES ('$name', '$email')");
Having said that, your script is WIDE open to an injection attack. You should be using PDO and also verifying data before you go sticking it into an SQL statement. What do you do when your user enters bob;drop table users; as his name and your query runs?
Edit: Also, you had a bracket missing.
Edit 2: If you are still getting an error run this and let us know what you see:
$sql = "INSERT INTO message (`name` , email) VALUES ('$name', '$email')";
echo $sql;
There is a good chance you see that one of the variables is empty.
Edit 3:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
if(!empty($name) && !empty($email))
{
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
echo ("Message succesfully added.");
}
else
{
echo "It seems that either name or email was empty, so not inserting data.<br>";
}
}
?>
Edit 4 - aka Goodness me!
I also noticed that I failed to add the extra bracket to the code that I copied from your question. I have edited it to include it from now on.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = mysql_real_escape_string($_POST['username']);
$username = mysql_real_escape_string($_POST['useremail']);
if(!empty($name) && !empty($email))
{
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$username', '$useremail')");
echo ("Message succesfully added.");
}
else
{
echo "It seems that either name or email was empty, so not inserting data.<br>";
}
}
<html>
<head>
<title>Guestbook</title>
</head>
<form action="index.php" method="post">
Name: <input type="text" name="username"/><br>
Email: <input type="text" name="useremail"/><br>
<input type="submit" value="Post!"/>
</form>
?>
// Make sure you stick this </html> at the BOTTOM of you php file.
</html>
Alright, so recently I watched a tutorial and coded along with it in Notepad++. I am attempting a simple MYSQL login/register form, but when I login- it gives me the "Wrong U/P" error echo I wrote. It saves everything in the database as the md5 and stuff. Here is my codes.
register.php
<?php
require('config.php');
if(isset($_POST['submit'])){
//Preform the verification of the nation
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($email1 == $email2) {
if($pass1 == $pass2) {
//All good. Carry on.
$name = mysql_escape_string($_POST['name']);
$lname = mysql_escape_string($_POST['lname']);
$uname = mysql_escape_string($_POST['uname']);
$email1 = mysql_escape_string($_POST['email1']);
$email2 = mysql_escape_string($_POST['email2']);
$pass1 = mysql_escape_string($_POST['pass1']);
$pass2 = mysql_escape_string($_POST['pass2']);
$pass1 = md5($pass1);
$sql = mysql_query("SELECT * FROM `users` WHERE `uname` = '$uname'");
if(mysql_num_rows($sql) > 0) {
echo "Sorry, that user already exists!";
exit();
}
mysql_query("INSERT INTO `users` (`id`, `name`, `lname`, `uname`, `email`, `pass`) VALUES (NULL, '$name', '$lname', '$uname', '$email1', '$pass1')");
}else{
echo "Sorry, your passwords do not match<br><br>";
exit();
}
}else{
echo "Sorry, your emails do not match.<br><br>";
}
}else{
$form = <<<EOT
<form action="register.php" method="POST">
First Name: <input type="text" name="name" /><br />
Last Name: <input type="text" name="lname" /><br />
Username: <input type="text" name="uname" /><br />
Email: <input type="text" name="email1" /><br />
Confirm Email: <input type="text" name="email2" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name="pass2" /><br />
<input type="submit" value="Register" name="submit" />
</form>
EOT;
echo $form;
}
?>
login.php
<?php
require('config.php');
if(isset($_POST['submit'])){
$uname = mysql_real_escape_string($_POST['uname']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass = md5($pass);
$sql = mysql_query("SELECET * FROM `users` where `uname` = '$uname' and `pass` = '$pass'");
if(mysql_num_rows($sql) > 0){
echo "You are now logged in.";
exit();
}else{
echo "Wrong U/P combination";
}
}else{
$form = <<<EOT
<form action="login.php" method="POST">
Username: <input tye="text" name="uname" /><br>
Password: <input type="password" name="pass" /><br>
<input type="submit" name="submit" value="Login" />
</form>
EOT;
echo "$form";
}
?>
and config.php
<?php
mysql_connect("localhost", "X", "X");
mysql_select_db("X");
?>
The config.php code is correct, but I am not giving away X.
As you can see, this code echos out an error for login.php if it's incorrect. It gives me that error even if it is correct. I used MD5 hash passes, so please help!
Firstly, you're using the ` tag in there - this should be ' .
You need to either interpolate or concatenate your variables; i.e; instead of
mysql_query("INSERT INTO `users` (`id`, `name`, `lname`, `uname`, `email`, `pass`) VALUES (NULL, '$name', '$lname', '$uname', '$email1', '$pass1')");
use;
mysql_query("INSERT INTO 'users' ('id', 'name', 'lname', 'uname', 'email', 'pass') VALUES (NULL, '{$name}', '{$lname}', '{$uname}', '{$email1}', '{$pass1}')");
Anyway, aside from some good practice, have a look at this line;
$sql = mysql_query("SELECET * FROM `users` where `uname` = '$uname' and `pass` = '$pass'");
Just a small typo ruining everything for you. Change SELECET to SELECT , and you should be good to go.
Best of luck!
Eoghan
you don't need the following lines:
$email2 = mysql_escape_string($_POST['email2']);
and
`$pass2 = mysql_escape_string($_POST['pass2']);`
2. run SELECET * FROM users in order to see that the user/pwd really made it to the DB
3. add echo "$uname $pass <br>"; to the login form to make sure that it passed correctly
The other two answers are correct, but you have a more fundamental issue with this: you are using the old, deprecated mysql_* functions. Those functions are an old, procedural interface to MySQL and don't support the modern features of that RDBMS. I suggest using mysqli or PDO for an OOP approach to database access.
If you are going to stick to this ancient code, you should at least use mysql_real_escape_string() instead of mysql_escape_string().