SQL insert statement with user input to Phpmyadmin isnt working - php

I was trying to make a site and people could sign up/subscribe and i would store their email adresses in a database. I searched online for a solution but couldnt find anything
My code:
<html>
<?php include_once('include/html/hoofd.php') ?>
<body>
<h1 id="css"> ----- </h1>
<br><br><br>
<ul>
<form method="post" action="./emailverwerk.php" class="email" id="css2">
<b><extra space >Register and we will notify you with the the next GREAT deal!</b><br>
<br>
Full Name: <input type="text" class="css2" name="naam" placeholder="Full name"><br>
Email adress : <input type="email" class="css2" name="emailaddress" placeholder="Email Adress"><br>
Email adress : <input type="email" class="css2" name="Emailaddressrepeat" placeholder="Repeat Email "><br>
<a href="http:/----------/emailverwerk.php"><input type ="Submit" value ="Subscribe" id="css3"><br>
<?php
session_destroy();
if (isset($_SESSION["error"])) {
print ($_SESSION["error"]);
}
?>
</form>
</ul>
<ul>
<form method="post" class="actie" id="expired1">
<b>- Claim your free 1000 TRX here!!</b><br>
This is a one time offer! <br>
Click the link below and fill in your details to claim your free 1000 TRX!<br>
<input type="submit" value="Expired!!" id="css3">
</form>
</ul>
</body>
</html>
And my SQLI code :
<?php
session_start();
include_once ("include/database.php");
$name = $_POST["naam"];
$email = $_POST["Emailaddress"];
$emailherh = $_POST["Emailaddressrepeat"];
$sql = "INSERT INTO emaillist (naam , email)
VALUES ('".$_POST["naam"]."','".$_POST["emailaddress"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
Im a first year student as well so my programming experience isnt that big and perfect yet.

You must escape the strings. Else you are disallowing Irish. Think what happens with O'Brian. It will give you a mysterious "syntax error".

Your Anchor tag is not needed around the form submit, and it was not closed .

Related

Failing to get POST values from HTML form in PHP

I am struggling to get values from an HTML form into PHP variables using POST. It used to work but now no matter what I do it isn't working. Here is the php file:
<?php
include "DBConn.php";
session_start();
?>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" href="Register.css" type = "text/css">
</head>
<body>
<div id="container">
<form action="register.php" method = "post">
<label for="name">Name:</label>
<input type="text" id="name" name="txtName" value = <?php if(isset($_POST['txtName'])) echo $_POST['txtName'];?>>
<label for="surname">Surname:</label>
<input type="text" id="surname" name="txtSurname" value = <?php if(isset($_POST['txtSurname'])) echo $_POST['txtSurname'];?>>
<label for="address">Address:</label>
<input type="text" id="address" name="txtAddress" value = <?php if(isset($_POST['txtAddress'])) echo $_POST['txtAddress'];?>>
<label for="email">Email:</label>
<input type="email" id="email" name="txtEmail" value = <?php if(isset($_POST['txtEmail'])) echo $_POST['txtEmail'];?>>
<label for="password">Password:</label>
<input type="password" id="password" name="txtPassword" value = <?php if(isset($_POST['txtPassword'])) echo $_POST['txtPassword'];?>>
<label for="password2">Re-enter Password:</label>
<input type="password" id="password2" name="txtPassword2" value = <?php if(isset($_POST['txtPassword2'])) echo $_POST['txtPassword2'];?>>
<div id="lower">
<input type="submit" value="Register" name = "btnRegister">
</div><!--/ lower-->
</form>
</div>
</body>
</html>
<?php
//Runs if btnRegister is clicked. Registers a user.
if (isset($_POST['btnRegister'])) {
//Assigns form data to variables
$_SESSION["Name"] = $_POST['txtName'];
$_SESSION["Surname"] = $_POST['txtSurname'];
$_SESSION["Email"] = $_POST['txtEmail'];
$_SESSION["Password"] = $_POST['txtPassword'];
$_SESSION["Password2"] = $_POST['txtPassword2'];
$_SESSION["Address"] = $_POST['txtAddress'];
$sqlSelect =
"SELECT *
FROM tbl_Customer
WHERE Email = '{$_SESSION["Email"]}'";
//Runs select query
$result = $conn->query($sqlSelect);
$md5pass = md5($_SESSION["Password"]);
//Checks to see if user exists based on query
if ($result->num_rows == 0) {
//Checks to see if passwords match
if ($_SESSION["Password"] == $_SESSION["Password2"]) {
//Passwords match
echo '<script>alert("Passwords match")</script>';
//Insert statement to insert user into table
$sqlInsert = "INSERT INTO tbl_Customer (Name, Surname, Email, Password, Address)
VALUES ('{$_SESSION["Name"]}','{$_SESSION["Surname"]}','{$_SESSION["Email"]}','$md5pass','{$_SESSION["Address"]}');";
if ($conn->query($sqlInsert) === TRUE) {
echo '<script>alert("Registered successfully")</script>';
}
else {
echo '<script>alert("Registration error: " . $sql . "<br>" . $conn->error)</script>';
}
}
else {
echo '<script>alert("Passwords do not match")</script>';
}
}
else {
//User exists
echo '<script>alert("User already exists, choose a different email.")</script>';
}
header('Location: login.php');
exit();
}
?>
None of the alerts are working indicating that they echos are not working. Also, the second I click the register button I am taken to the login page which means the register button must be working. It doesn't give me any errors or messages.
Remove action="register.php" from <form> tag if your PHP code is on the same page as HTML code. The action attribute specifies where to send the form-data when a form is submitted, since your PHP code is on the same page you should remove action and the form-data will be submitted on that same page.
Or
create a register.php and put PHP code there.

MySQLi Insert into inserts 0?

I have a form on my website that submits data to my (mysql) database. This is done via Mysqli. After submission of the form I get the message:
"inputoftextboxhere" has been added to the database!.
But when I look in my database there is only a value of 0.
insert.php
<?php
//config bestand ophalen.
require_once 'config.php';
if(isset($_POST['submit']))
{
$email = $mysqli->real_escape_string($_POST['email']);
$sql = "INSERT INTO maillist (id, email) VALUES ('', '$email')";
if ($mysqli->query($sql))
{
echo "<center><div class='alert alert-success' role='alert'>".$email." is succesvol toegevoegd aan de database!</div></center>";
}
else
{
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
$mysqli->close();
}
?>
Index.php
<form action="insert.php" method="post" accept-charset="utf-8" class="form" name="submit">
<legend>Email </legend>
<input type="text" name="email" value="" class="form-control input-lg" placeholder="E-mail" /><br />
<button class="btn btn-lg btn-primary btn-block signup-btn" name="submit" type="submit">Voeg nummer toe</button>
</form>
Screenshot of database:
https://gyazo.com/9ec48d3ce4ec6643d8fbcb2f3db42052
Please make sure the datatype of the email column in your database table is text or varchar. If it is set to integer or double probably that might be the issue.
Make sure that the database can store strings, so pick Varchar.
When it is set too boolean/bit or any number-based datatype your database doesnt now how to handle a string input.
Otherwise, debug the value that is getting posted to make sure you aren't just putting a zero in your database.

Retrieve data from database and display in text fields.

Please help me. I written a code but it is not working well.
I want to retrieve data from database and display text fields.
My Code is:
<DOCTYPE html>
<html>
<head><title>Practice</title></head>
<body align="center">
<?php
$con=mysqli_connect("localhost","root","","address_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<form action="1.php" method="post">
Name <br><input type="text" name="name" value="<?php echo $_GET['n']; ?>"><br>
Address 1<br><input type="text" name="address_1" value=""><br>
Address 2<br><input type="text" name="address_2" value=""><br>
Address 3<br><input type="text" name="address_3" value=""><br><br><br>
<input type="submit" name="reset" value="Clear">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="retrieve" value="Retrieve">
</form>
<?php
if (isset($_POST['submit']))
{
$name=$_POST['name'];
$address_1=$_POST['address_1'];
$address_2=$_POST['address_2'];
$address_3=$_POST['address_3'];
if(($name=='')||($address_1=="")||($address_2=="")||($address_3==""))
{
echo "<script>alert('Please fill all fields')</script>";
exit();
}
else
{
mysqli_query($con,"INSERT INTO address_tbl (name,address_1,address_2,address_3)
VALUES ('$name','$address_1','$address_2','$address_3')");
echo "<script>alert('Your record successfull inserted into database...')</script>";
exit();
}
}
if (isset($_POST['retrieve']))
{
$result = mysqli_query($con,"SELECT * FROM address_tbl");
while($row = mysqli_fetch_array($result))
{
$name=$row['name'];echo "<br>";echo "<br>";
$add1=$row['address_1'];echo "<br>";echo "<br>";
$add2=$row['address_2'];echo "<br>";echo "<br>";
$add3=$row['address_3'];echo "<br>";echo "<br>";
echo "<script type='text/javascript'>
window.open('1.php?n=$name','_self'); </script>";
}
}
?>
</body>
</html>
Please help me. give me any hint that I can solve my problem. Thanks
try this ,
mysqli_query($con,"INSERT INTO `1address_tbl` (`name`,`address_1`,`address_2`,`address_3`)
VALUES ('$name','$address_1','$address_2','$address_3')");
it should work fine now. it needs to include ( ` ) around the table names and column name to make sql work correctly. you left them out,
you replace this with yours.
First of all you should have your php in a seperate file called index.php with just php code then create a page called index.html.php in that page use a foreach loop to output data from the database its the most common and practical way of doing what your trying to do .

How to disable writing to database if i made duplicate entry, and show warning in alertbox?

I am a bit new with php, so I need help. On one page i have small form with firstname and lastname fields. On submit i send it to external .php script where i want to check if there is already person with same name in database. If there is already person with entered name in database, I want to cancel writing to database, and return to the html page. I have done this, but I want to display the JS messagebox "Person with this name already exists in db!", and if the writing to base was canceled, i want my input fields show last written values. I've been reading a lot of litertaure, and I'm lost. Thanks for help anyway :)
This is my form:
<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
<input type="submit">
</form>
My php code:
<?php
$con=mysqli_connect("localhost","root","","phptest");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['firstname'])) {
$firstname = $_POST['firstname'];
}
if (isset($_POST['lastname'])) {
$lastname = $_POST['lastname'];
}
$duplicate=mysqli_query($con,"SELECT * FROM persons WHERE FirstName='$firstname'");
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
header( 'Location://localhost/ivanda.php' ) ;
mysqli_close($con);
?>
This line:
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
Change it to this this code:
if(mysqli_num_rows($duplicate)>0)
{
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php'); </script>"; //add this line instead of header
}
-------------------------EDITED----------------------------------
Trys this:
$duplicate=mysqli_query($con,"SELECT * FROM Persons WHERE FirstName='$firstname' limit 1");
if(mysqli_num_rows($duplicate)>0)
{
$row = mysqli_fetch_assoc($duplicate);
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php?firsName=".$row['FirstName']."&lastName=".$row['LastName']."'); </script>"; //add this line instead of header
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
With this you are sending the var via GET on the url...then in your form you should have something like this:
<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname" value="<?php if(isset($_GET['firsName'])){echo $_GET['firsName'];} ?>">
Lastname: <input type="text" name="lastname" value="<?php if(isset($_GET['lastName'])) {echo $_GET['lastName'];} ?>">
<input type="submit">
</form>
PS: Go for mysqli o PDO, remember it...mysql extension is gonna be deprecated soon
Saludos.

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