How to debug a mistake when inserting data into the table? - php

PHP code didn't insert.
<?php
$message = " ";
require "database.php";
if (isset($_POST["submit"])) {
if (empty($_POST["email"]) || empty($_POST["password"])) {
$message = "Email or Password is Incorrect";
} else {
$email = '$_POST[email]';
$pass = '$_POST[password]';
if ($email && $pass) {
$db = mysqli_select_db($conn, "auth");
$sqli = "INSERT INTO users (email, password) VALUES($email, $pass)";
if (mysqli_query($conn, $sqli)) {
$message = "New record created successfully";
} else {
$message = "Cannot create user!";
}
}
}
}
?>
$conn = mysqli_conncect("localhost","root","","auth");
I tried everything but not found the mistake to insert the query into the table.

Remove the single quotation in your else statement. PHP will interpret it as a string instead of a POST variable.
That is:
$email = $_POST['email'];
$pass = $_POST['password'];

Related

How to stop mysqli_query from adding records with missing info?

I have form that subscribers enter their email address and this gets posted to mysql database. The problem is that if you visit the page, even without subscribing, a record is added to the database even without the required email address. Even worse, it seems to be adding records every three seconds. How can i stop this? Is there something wrong in my code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
header('location: index.php');
mysqli_close($conn);
Just check with the if statement if there is an email you can save and put saving to database into that if statement as below:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
$emailErr = ''; //it is a good practice to initialize variable before its use.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
//if you have an email in $email and there is no
//error in $emailErr
if(!empty($email) && empty($emailErr)) {
//insert it to the db.
//THIS IS INSECURE WAY - Check links in comments!
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
header('location: index.php');
exit();

PHP file doesn't execute code after connecting to a database

After I run my PHP code, hello1 is printed on the screen, but not hello2. I assume there's something wrong with my code for connect.
I can't find what's wrong with my code. Unfortunately to me my code seems correct even after going over it multiple times. How can I fix it?
BTW, I am running MAMP on a MacBook Air.
<?php
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
echo "hello2";
if (!$connect) {
printf("Connection failed: %s\n", $mysqli->connect_error);
die();
echo "hello3";
}
session_start();
if (isset($_POST["Sign Up"]))
{
if (empty($_POST["Email"]) || empty($_POST["Password"]))
{
echo '<script> alert ("Both Feldsa are required)</script">';
}
else
{
$_SESSION['email'] = $_POST['Email'];
$_SESSION['password'] = $_POST['Password'];
$_SESSION['Repeatpassword'] = $_POST['Repeatpassword'];
$_SESSION['name'] = $_POST['name'];
$_SESSION['weight'] = $_POST['weight'];
$_SESSION['feet'] = $_POST['feet'];
$_SESSION['inches'] = $_POST['inches'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['goal'] = $_POST['Goal'];
// Escape all $_POST variables to protect against SQL injection
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$RepPassword = $mysqli->escape_string(password_hash($_POST['Repeatpassword'], PASSWORD_BCRYPT));
$name = $mysqli->escape_string($_POST['name']);
$Weight = $mysqli->escape_string($_POST['weight']);
$feet = $mysqli->escape_string($_POST['feet']);
$inches = $mysqli->escape_string($_POST['inches']);
$age = $mysqli->escape_string($_POST['age']);
$goal = $mysqli->escape_string($_POST['goal']);
$hash = $mysqli->escape_string(md5(rand(0, 1000)));
// Check if user with that email already exists
// We know user email exists if the rows returned are more than 0
$result = $mysqli->query("SELECT * FROM User WHERE Email_Address='$email'") or die($mysqli->error);
if ($result->num_rows > 0) {
$_SESSION['message'] = 'User with this email already exists!';
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO User (Email_Address, Password, Full Name, Weight, Feet, Inches, Age, Goal, hash) "
. "VALUES ('$email', 'password', 'name', 'Weight', 'feet', 'inches', 'age', 'goal', 'hash')";
}
if (! $mysqli->query($sql)
{
$_SESSION['message'] = 'Registration successfully';
echo $_SESSION['message'];
header("location: loginaccount.html");
}
}
else {
$_SESSION['message'] = 'Registration failed!';
echo $_SESSION['message'];
}
}
if (isset($_POST["Login"]))
{
$email = $mysqli->escape_string($_POST['Email']);
$result = $mysqli->query("SELECT * FROM User WHERE Email_Address='$email'");
if ($result->num_rows == 0) { //
{
$_SESSION['message'] = "User with that email doesn't exist!";
echo $_SESSION['message'];
}
else {
$user = $result->fetch_assoc();
if (password_verify($_POST['password'], $user['Password'])) {
$_SESSION['email'] = $user['Email_Address'];
$_SESSION['name'] = $user['Full Name'];
$_SESSION['weight'] = $user['Weight '];
$_SESSION['feet'] = $user['Feet '];
$_SESSION['inches'] = $user['Inches '];
$_SESSION['age'] = $user['Age '];
$_SESSION['goal'] = $user['Goal '];
$_SESSION['logged_in'] = true;
$_SESSION['active'] = $user['Active'];
header("location: loginaccount.html");
}
}
mysqli_close($connect);
session_destroy();
?>
At the start of your script:
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
At line 3 here, you try and use $mysqli. That variable doesn't exist. You haven't declared it, so at that point, you are going to get a PHP runtime error when you try and reference the method of an object, which is in fact a non-existent variable.
It's actually worse than that, because you are mixing procedural mysqli with object oriented mysqli. What you really need is this, but the obvious issue is that your mysqli connection variable is named $connect!
echo "hello1";
$connect = new mysqli("localhost:8888", "Capstone", "", "capstone");
$connect->set_charset('utf8');
You can also use try/catch to find more about errors
try{
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
echo "hello2";
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
P.S. - in $mysqli->set_charset("utf-8"); $mysqli is not defined, use $connect here

this code wont insert user save data into the sql database

<?php
$con = mysqli_connect("localhost","root","","social_network") or die("Connection was not established");
function InsertUser(){
global $con;
//if sign up button is pressed
if(isset($_POST['sign_up'])){
$name = $_POST['u_name'];
$pass = $_POST['u_pass'];
$email = $_POST['u_email'];
$country = $_POST['u_country'];
$gender = $_POST['u_gender'];
$b_day = $_POST['u_birthday'];
$name = $_POST['u_name'];
$date = date("d-m-y");
$status = "unverified";
$posts = "No";
//checks if the email already existist in the system
$get_email = "select * from users where user_email='$email'";
$run_email = mysqli_query($con,$get_email);
$check = mysqli_num_rows($run_email);
//if email validation
if ($check==1) {
echo "<script>alert('This email is already registered!, Try another one')</script>";
exit();
}
//password properties string length
if(strlen($pass)<8){
echo "<script>alert('Password should be minimum 8 characters')</script>";
exit();
}
else {
//inserting user input into the database
$insert = "INSERT INTO users (user_name,user_pass,user_email,user_country,user_gender,user_dob,user_image,register_date,last login,status,posts) VALUES ('$name','$pass','$email','$country','$gender','$b_day','default.jpg','$date','$date','$status','$posts')";
$run_insert = mysqli_query($con,$insert);
if($run_insert){
echo "<script>alert('Registration Successfull!')</script>";
}
}
}
}
?>
The mistake is in your query
cant give a column name like "last login"
Remove the space between and try to change the column name of "status" to anything else

Error Too Many Redirects

Trying to create my server.php script, so everythning was fine, till now. I wanted to prevent form resubmission and added header('location: index.php'); to my script. And then I faced the problem:ERR_TOO_MANY_REDIRECTS. And as many of you already understand my database was full of a junk. So, here is my code:
<?php
$username = $email = $password = "";
$usernameErr = $emailErr = $passwordErr = "";
$servername = 'localhost';
$serveruser = 'root';
$serverpassword = 'root';
$db = 'example';
$conn = new mysqli($servername, $serveruser, $serverpassword, $db);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['register'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
if(empty($username)) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-z ]*$/", $username)){
$usernameErr = "Only letters and whitespaces allowed";
}
}
if(empty($email)) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Wrong email format";
}
}
if(empty($password)) {
$passwordErr = "Password required";
} else {
$password = test_input($_POST["password"]);
}
}
if ($usernameErr == "" && $emailErr == "" && $passwordErr == "") {
$sql = "INSERT INTO users (username, email, password)
VALUES('$username','$email','$password')";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("location: index.php");
}
function test_input($data) {
$data = trim($data);
$data = htmlspecialchars($data);
$data = stripslashes($data);
return $data;
}
?>
To prevent TOO MANY REDIRECT put this code
if ($usernameErr == "" && $emailErr == "" && $passwordErr == "") {
$sql = "INSERT INTO users (username, email, password)
VALUES('$username','$email','$password')";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("location: index.php");
}
within
if(isset($_POST['register'])) { //.................}
this block after checking errors
And to prevent re-submission of form use accepted answer on this question
Preventing form resubmission
You can do couple of ways to stop this:
1) You can write either of these, unset($_POST['register']); or $_POST = array(); just before header('location:index.php');so it will not pass through if(isset($_POST['register'])) condition and so it will not go in infinite loop.
2) Or use full URL in header like this: header("location: mydomain.com/index.php"); It will stop infinite loop too.

Empty fields can get inserted into my database

I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?
The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong
Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.

Categories