I am starting to learn the basics of SQL and PHP codes.
I am trying to create a simple newsletter subscription page. this would require the user to enter their email and submit. That will then get added to my database.
Now, this works well when the HTML and PHP code are separate and the submission occurs but redirects to the PHP page with the echo.
I want to get the message on the same page and I tried merging the PHP code in the page as below
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_connect("hostname", "username", "password");
mysql_select_db("db name");
$user = $_POST['email'];
$query = "INSERT INTO tablename(columname)VALUES('$email')";
echo "inserted";
}
?>
<html>
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
</html>
Hoever with this code it just doesnt do anything.
What have am I doing wrong here? Appreciate your expert advice.
There are few mistakes in the code, you can fix them by doing the following:
Save the file as a php file first. For example name it "email.php".
Make the form action="email.php"
Don't write two complete separate codes in the same file, one for php file and the other for html file like you did. You can include the html code inside the php code using heredoc syntax which allows you to include a long html code like the following:
echo<<<_HTMLCODE
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
_HTMLCODE;
In the query syntax, add $user instead $email because the variable $user contains the value submitted by the form.
Add a code to excute the inserted query. for example:
mysql_query($query);
So your final code will be like this:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_connect("hostname", "username", "password");
mysql_select_db("db name");
$user = $_POST['email'];
$query = "INSERT INTO tablename VALUES('$user')";
mysql_query($query);
echo "inserted";
}
echo<<<_HTMLCODE
<form method="POST" action="email.php" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
_HTMLCODE;
?>
I have tried the code above after I added the data of my database on the localhost and after I created a table for the emails and it worked. Here is the edited code with my database access info and the table name in my code editor:
When i opened the table emails in my database, I found the email that I had submitted using the form (your modified code):
(advice: use mysqli instead of mysql)
Please use prepare statements to prevent Sql Injections.
Here is sample code try this.
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli ("localhost", "root", "usbw", "test");
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
if (isset($_POST['submit'])) {
$email = filter_input(FILTER_VALIDATE_EMAIL, $_POST['email']);
$sql = "INSERT INTO table (email) VALUES (?)";
$stmt = $connect->prepare($sql);
$stmt->bind_param('s', $email);
$result = $stmt->execute();
if ($result) {
$msg = 'Succesfully added';
} else {
$msg = 'OOPS Error Occured';
}
}
?>
<html>
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
</html>
Related
i am trying to create a login and registration page using php and mysql but i met with some problem.
I reference to this video and the code is below (the code is incomplete, i only did for registration).
So the problem is that when i submit an entry using the register side, my database shows a blank record. I tried various method like
$reg = "INSERT INTO usertable (user,pwd) values ('".$user."','".$pwd."')";
but it did not work and when i did this:
$reg = "INSERT INTO usertable (user,pwd) values ('ABC','1234')";
it worked. What should i do to insert entry using the input text?
<?php
session_start();
$conn = mysqli_connect('localhost', 'root', '1234');
mysqli_select_db($conn,'registeration');
$user = $_POST["user"];
$pwd = $_POST["pwd"];
$s = "select * from usertable where user = '$user'";
$result = mysqli_query($conn,$s);
$num = mysqli_num_rows($result);
if($num == 1){
echo"Username Already Taken";
}
else{
$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
mysqli_query($conn,$reg);
}
?>
<h2> Register Here </h2>
<form action="index.html" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>
A easy way to know what's full SQL query string the program or you have made.
$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
echo $reg
It is better use {} to instead of . to insert variable into a string.
$reg = "INSERT INTO usertable (user,pwd) values ('{$user}','{$pwd}')";
To be sure the POST/GET action target is correct,
For your current code I am not sue index.html can handle it, probably it should be $_SERVER["PHP_SELF"]
To understand PHP String Operators, please refer to
https://www.php.net/manual/zh/language.operators.string.php
I found my mistake. I wrote my php and the register table (together in registration.php) however, my form redirects me to index.html. I copied and pasted my php into my index.php (changed the name) and it worked.
Thanks for those who helped me!
<h2> Register Here </h2>
<form action="index.php" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>
My issue is when I go to this page to register (see picture below), the prompt "The email address...." appears right away even though I haven't typed anything yet. How do I remove that? Here's my code below.
<?php
$mysqli = mysqli_connect("localhost", "dbusername", "dbpassword", "dbtable");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$sql = "INSERT INTO tablename(firstname, lastname, email, password, age, gender, startdate) VALUES ('".$_POST["firstname"]."', '".$_POST["lastname"]."', '".$_POST["email"]."', PASSWORD('".$_POST["password"]."'), '".$_POST["age"]."', '".$_POST["gender"]."', now())";
$res = mysqli_query($mysqli, $sql);
if ($res === TRUE) {
echo "Your account '".$_POST["email"]."' has just been created. Thank you for joining us!<br/>";
echo "<br/>";
echo "<a href='userlogin.php'>Go to Login</a>";
} else {
echo "The email address '".$_POST["email"]."' is already in use, try again!";
}
mysqli_close($mysqli);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Information</title>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<form method="post" action="">
<fieldset> <legend><h3> User Information </h3></legend>
<p><strong>First Name:</strong><br/>
<input type="text" name="firstname"/></p>
<p><strong>Last Name:</strong><br/>
<input type="text" name="lastname"/></p>
<p class="lowercase"><strong>Email:</strong><br/>
<input type="text" name="email"/></p>
<p><strong>Password:</strong><br/>
<input type="password" name="password"/></p>
<p><strong>Age:</strong><br/>
<input type="number" name="age"/></p>
<p><strong>Gender:</strong><br/>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female<br>
<p><input type="submit" name="submit" value="Create Account"/></p>
</fieldset>
</form>
</body>
</html>
The reason for this is your if/else logic.
The first if checks if the connection failed and if it didn't, it goes to the query and there most likely already exists a record, so it goes to the else showing that the record exists.
You need to first check if a record exists, then run the INSERT if it does not exist.
I need to state that your code is open to SQL injection. Use a prepared statement. Plus, don't store plain text passwords, use a safe hashing method.
Here are a few references for you to read:
SQL injection
Prepared statements
How to use password_hash
Check if a record exists:
check if row exists with mysql
Error checking that will serve you well:
Error reporting
MySQLi error
Edit:
You could also place your PHP before your HTML and check to see if the submit button was clicked and then if any inputs are not empty, run the PHP/Query.
Example:
if(isset($_POST['submit'])) {
// Run your code
} else {
// Do something else
}
I have some PHP and HTML code which should send data from the form to my MySQL database. However, on clicking Submit in the form, the page reloads and nothing happens. No echo or anything. The HTML is in the same file as the PHP file.
PHP
<?php
if(isset($_POST['submit'])){
$usernamep = $_POST['usernameinput'];
$passwordp = $_POST['passwordinput'];
$servername = "localhost";
$username = "USERNAMECENSOR";
$password = "PASSWORDCENSOR";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO accounts (username, password)
VALUES ('$usernamep', '$passwordp')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
HTML
<form method="POST" action="">
<input type="text" name="usernameinput"><br>
<input type="password" name="passwordinput"><br>
<input type="submit" class="button" value="Sign in">
</form>
Note: I know this code is currently subject to SQL injection, and the password is not encrypted. It is temporary starting code in an attempt to get it working first.
You lack the name attribute in the submit button, add name="submit".
<form method="POST" action="">
<input type="text" name="usernameinput"><br>
<input type="password" name="passwordinput"><br>
<input type="submit" name="submit" class="button" value="Sign in">
</form>
Your test is wrong. You have no input named "submit" (with attribute name = submit). It should be:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
...
}
A broad test like this will not even need a named submit. The HTML form may even be posted on another event using jQuery or JavaScript.
In your PHP file, you use isset($_POST['submit']). You don't have any form input with name="submit". You could make your submit button be
<input type="submit" name="submit" class="button" value="Sign in">
You have to include your php file into the action of the form tag.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="usernameinput"><br>
<input type="password" name="passwordinput"><br>
<input type="submit" class="button" value="Sign in">
</form>
I wanted to make a simple login page using php and mysql database where I have created table members (id, username, password).
When I run my program, it's not entering the if block and directly moving to else block
<html>
<body>
<form method="POST" action="process.php">
Username:
<input type="text" name="username">
Password:
<input type="password" name="password">
<input type="submit" value="Login">
</form>
</body>
</html>
My PHP code is
<?php
include("includes/dbConnect.php");
$username=$_POST['username'];
$password=$_POST['password'];
$username=stripcslashes($username);
$username=stripcslashes($password);
$username=$conn->real_escape_string($username);
$password=$conn->real_escape_string($password);
//query
$sql="SELECT * FROM members WHERE username='$username' AND password ='$password'";
$result= $conn->query($sql);
$row=$result->fetch_assoc();
if($row['username']==$username && $row['password']==$password)
{
echo "Welcome";
}
else
{
echo "fail";
}
?>
Please help me out and rectify my error
P.S. I am new to php code so if anyone would like to give me any advice It will be most welcome
Your second line here:
$username=stripcslashes($username);
$username=stripcslashes($password);
is mistakenly assigning to the $username variable again.
I'm trying to create a registration page. The page is successfully connected to phpMyAdmin database but it does not echo anything when i click the register button.
<html>
<head>
</head>
<body>
<?php
INCLUDE "connect.php";
INCLUDE "functions.php";
INCLUDE "titlebar.php";
?>
<div id="loginform">
<h1>Register</h1>
<form name="Register" action="register.php" method="post">
<?php
if(isset($POST["submit"])){
$username = $_POST["username"];
$password = md5 ($_POST["password"]);
if(empty($username) or empty($password)){
echo "<p>Fields Empty!</p>";
} else {
mysql_query("INSERT INTO login VALUES('',$username','$password','2','')");
echo "<p>Successfully Registered!</p>";
}
}
?>
<p>
<label for="username">Username: </label>
<input type="text" name="username" id="username"/></p><p>
<label for="password">Password: </label>
<input type="password" name="password" id="password"/></p><p>
<input type="submit" name="submit" value="Register" />
</p>
</form>
</div>
</body>
The problem is with the post method.
use $_POST instead of $POST
You have mysql error
Not: $username'
but '$username'
And next time display mysql errors with mysql_error().
At the beginning, I am not sure what isset($_POST['submit'] should return, but as already mentioned in the comments you missed a single quote.
Additionaly i would use:
$password = password_hash($_POST['password'],
md5 is deprecated and thus not safe. If you write a login script you can use password_verify(plainPW, hashPW)
You also need to specify a database and login into it. I recommend to look at the W3 Schools examples they are very in-depth and have good examples.
W3 school mysqli page
also write a die() at the end of your script and do not foregt to close the connection.