unknown column 'email' in where clause - php

I have problem with this code. It gives me 'Unknown column 'email' in where clause.
I tried almost everything, but I don't know what is the problem. I am beginner so please be gentle :)
Any ideas how to solve it?
Thanks a lot
session_start();
include('connect.php');
if(isset($_POST['submit']))
//when isn't username in form
if($_POST['firstname'] == '')
{
$_SESSION['error']['firstname'] = 'First name is required';
}
if($_POST['surname'] == '')
{
$_SESSION['error']['surname'] = 'Surname is required';
}
//when email isn't in form
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = 'Email is required';
}
//check if is email in correct format
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//email is in correct format and exist?
$email = $_POST['email'];
$sql1 = "SELECT * FROM users WHERE email = '$email'";
$result1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
if(mysqli_num_rows($result1) > 0)
{
$_SESSION['error']['email'] = 'Email is already used';
}
}
else
//error for wrong format of email
{
$_SESSION['error']['email'] = 'Your email is in wrong format';
}
//when isn't password in form
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = 'Password is required';
}
//when is error -> registration form
/*if(isset($_SESSION['error']))
{
header("Location: index.php");
exit();
}
else
*/
{
$firstname = mysqli_real_escape_string($connect,$_POST['firstname']);
$surname = mysqli_real_escape_string($connect,$_POST['surname']);
$email = $_POST['email'];
$password = mysqli_real_escape_string($connect,$_POST['password']);
$phone_number = mysqli_real_escape_string($connect,$_POST['phone_number']);
$note = mysqli_real_escape_string($connect,$_POST['note']);
$sql2 = "INSERT INTO users (firstname, surname, email, phone_number, note, password) VALUES ('$firstname', '$surname',
'$email', '$phone_number', '$note','$password')";
$result2 = mysqli_query($connect, $sql2) or die('Error: ' .mysqli_error($connect));

the column name email may be wrong or does not exist in the data base use the same column name as defined in the data base

Related

Why is my user being added to one table but not another

I am creating a profile image upload system for my users. Upon signup, the php code should create a user in the table "user" and also create a user in the "profileImg" table. I am getting no errors in my log but the user is being added to "user" but not "profileImg". Can anyone please assist. Thank you in advance.
SIGNUP.INC.PHP:
<?php
session_start();
include '../dbh.php';
$respond = array(
'status' => true,
'message' => 'There was an error',
'redirect' => '../profile.php',
'errors',
);
if (isset($_POST['submit'])) {
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$errorEmpty = false;
$errorEmail = false;
if (empty($first) || empty($last) || empty($email) || empty($pwd)) {
$respond['errors'][] = "Please fill out all fields!";
$respond['errorEmpty'] = true;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$respond['errors'][] = "Please enter a valid email address!";
$respond['errorEmail'] = true;
} else {
$sql = "SELECT email FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$emailcheck = mysqli_num_rows($result);
if ($emailcheck > 0) {
$respond['errors'][] = "That email address already exists!";
$respond['errorEmail'] = true;
}
else {
$encryptpwd = password_hash($pwd, PASSWORD_DEFAULT);
$sql = "INSERT INTO user (first, last, email, pwd)
VALUES ('$first', '$last', '$email', '$encryptpwd')";
$result = mysqli_query($conn, $sql);
$sql = "SELECT * FROM user WHERE email='$email' AND first='$first'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$email = $row['id'];
$sql = "INSERT INTO profileImg (email, status)
VALUES ('$email', 1)";
}
}
}
}
}
echo json_encode($respond);
?>
PROFILE.PHP:
This must be a violation on database level.
See this block of yours:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$email = $row['id'];
$sqlProfile = "INSERT INTO profileImg (email, status)
VALUES ('$email', 1)";
}
}
I'm pretty sure that in your database the email column of profileImg table is a varchar, although you are inserting it as an int $email = $row['id'];
Replace that line by the this $email = $row['email'];
Code after changes:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$email = $row['email'];
$sqlProfile = "INSERT INTO profileImg (email, status)
VALUES ('$email', 1)";
mysqli_query($conn, $sqlProfile);
}
}
Update: add mysqli_query($conn, $sqlProfile); to execute the query

why doesn't it want to check and then insert

for school i have to make a portfolio with a working login and registration system, the login part kinda works but by the regestration part i kinda got stuck. so why doesn't want to insert the users data after it checks the database of the username and email already exists? (hope u dont mind, but i am still a student who recently started with coding)
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg .= '<p class="error">The email address you entered is not valid!</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
$query_username = "SELECT id
FROM members
Where username == '$username'
LIMIT 1";
$available_username = array();
if ($resultUsername = mysqli_query($mysqli, $query_username)) {
if (mysqli_num_rows($resultUsername) > 0) {
$error_msg .= '<p class="error">A user with this username already exists!</p>';
}
}
$query_email = "SELECT id
FROM members
Where email == '$email'
LIMIT 1";
$available_email = array();
if ($resultEmail = mysqli_query($mysqli, $query_email)) {
if (mysqli_num_rows($resultEmail) > 0) {
$error_msg .= '<p class="error">A user with this email adress already exists!</p>';
}
}
if (empty($error_msg)) {
$ipadress = $_SERVER['REMOTE_ADDR'];
$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
$password = hash('sha512', $password . $random_salt);
if (!$tableRowEmail = 1) {
$sqlinsert = "INSERT INTO members (username, email, ipadress, password, salt) VALUES ($username, $email, $ipadress, $password, $random_salt)";
if (!mysqli_query($mysqli, $sqlinsert)) {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
header('Location: ./register_success.php');
}
}
?>
Just a wild guess: You use == in your sql statements. I'm quite sure you should only use =
Field values are missing single quote '
all the fields are varchar datatype.Single quotes should be used for string values.
$sqlinsert = "INSERT INTO members (username, email, ipadress, password, salt) VALUES ('$username', '$email', '$ipadress', '$password', '$random_salt')";

null values submitted to mysql database

I am trying to make a user system for my website but having some trouble with submitting it. It always submit a 0 to the database for everything. I have read on w3schools about global and local variables and I think this may be my problem but I don't know for sure.
Heres my code
<?php
$con = mysql_connect(localhost, 262096, 9201999);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("262096", $con);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST['passwordconf'];
$email = $_POST['email'];
$securityq = $_POST['securityq'];
$qanswer = $_POST['qanswer'];
if(!isset($firstname) || !isset($lastname) || !isset($username) || !isset($password) || !isset($passwordconf) || !isset($email) || !isset($securityq) || !isset($qanswer))
{
echo "You did not fill out the required fields.";
}
$uname = "SELECT * FROM users WHERE username='{$username}'";
$unamequery = mysql_query($uname) or die(mysql_error());
if(mysql_num_rows($unamequery) > 0)
{
echo "The username you entered is already taken";
}
$emailfind = "SELECT * FROM users WHERE email='{$email}'";
$emailquery = mysql_query($emailfind) or die(mysql_error());
if(mysql_num_rows($emailquery) > 0)
{
echo "The email you entered is already registered";
}
if($password != $passwordconf)
{
echo "The passwords you entered do not match";
}
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}
else
{
$salt = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
$hpassword = crypt($password,$salt);
$insert = "INSERT INTO users (firstname, lastname, username, password, email, securityq, qanswer, salt)
VALUES ('$firstname','$lastname','$username','$hpassword','$email','$securityq','$qanswer','$salt')";
mysql_query($insert);
if(!mysql_query($insert))
{
die('Could not submit');
}
else
{
echo "Information was submited. Please check your email for confirmation";
}
}
?>
Let me try to answer.
First of all, I agree with advice to move to PDO. mysql_* functions are deprecated. But if you wish to use it, escape every variable directly before sql due to '-symbols in your sql:
$hpassword = mysql_real_escape_string($hpassword );
As for me, the following syntax is easier to view rather than insert ... values():
$insert = "INSERT INTO `users`
SET `firstname` = '$firstname',
SET `hpassword` = '$hpassword'..."
Actually, I am trying to forgot this kind of code. I use PDO or comfortable uniDB class for simple apps.
Is it correct behaviour that it inserts user no matter errors like matching password? You should fix conditions.
Your conditions logic is wrong. You submit after if(!preg_match($regex, $email)). So if email is correct, it submits. Fix it as follows using ELSEIF
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(mysql_num_rows($emailquery) > 0){
echo "The email you entered is already registered";
}elseif($password != $passwordconf){
echo "The passwords you entered do not match";
}elseif(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}else{
// insertion code HERE
}

What is wrong with this PHP/MySQL code?

if(!empty($username) && !empty($email) && !empty($password) && !empty($confirm_password)){
$username = htmlentities($username);
$username = stripslashes($username);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$username = preg_replace("[^A-Za-z0-9]", "", $username);
$email = htmlentities($email);
$email = stripslashes($email);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$email = preg_replace("[^A-Za-z0-9]", "", $email);
if(strstr($email, "#") && strstr($email, ".")) {
require("$baseURL/scripts/connect.php");
$checkemail = mysql_query("SELECT * FROM users WHERE email='$email'") or die(mysql_error());
$numrows_checkemail = mysql_num_rows($checkemail);
if($numrows_checkemail > 0) {
require("$baseURL/scripts/connect.php");
$checkusername = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
$numrows_checkusername = mysql_num_rows($checkusername);
if($numrows_checkusername > 0) {
if($password == $confirm_password) {
$hashpass = md5(md5($password));
//All set to insert into the db
require("$baseURL/scripts/connect.php");
mysql_query("INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$hashpass')") or die(mysql_error());
$this->noticeMsg = "You have been signed up successfully!";
} else {
$this->errorMsg = "Uh-oh, looks like your passwords do not match!";
}
} else {
$this->errorMsg = "Oops, looks like that username is already in use! Please pick a different username.";
}
} else {
$this->errorMsg = "That email is already in use, please sign up with another email.";
}
} else {
$this->errorMsg = "Please enter a valid email address!";
}
} else {
$this->errorMsg = "Please fill in all the fields!";
}
The error I keep getting is "That email is already in use, please sign up with another email." even though the right file is being "required" and is connected to the database properly. The problem is most likely at the $numrows_checkemail part because when I use if($numrows_checkemail == 0) it works just fine. Why won't the ">" symbol work?
Am I doing something wrong?
Thank you
if($numrows_checkemail > 0) will return true only if $numrows_checkemail is bigger than 0.
You need to check for $numrows_checkemail == 0 or empty($numrows_checkemail)
The > is reversing your logic;
$numrows_checkemail > 0 is true if at least one user with that email already exists in the database (ie if there is more than zero rows in the database with that email)
$numrows_checkemail == 0 is true if no user with that email already exists in the database (ie if there isn't any row in the database with that email)

function sending email twice

I have the following function sending an email twice (and I believe running if($result) twice).
it is called on a separate page :
<?php $User = new User();
$User->ValidReg();
$valid = $User->ValidReg();
if ($valid === false) {
Here is the function in its class:
public function ValidReg() {
if ( !empty($_POST['username'])
&& !empty($_POST['password'])
&& !empty($_POST['email'])
&& !empty($_POST['state'])) {
//valid ?
$valid = true;
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$email = mysql_real_escape_string($_POST['email']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$state = mysql_real_escape_string($_POST['state']);
$checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'");
if(mysql_num_rows($checkusername) == 1) {
echo "<div id='shopperlogin1'><p>Sorry, that username is taken.<br /> Please go back and try again.</p></div>";
}
else {
//test
$confirm_code=mysql_real_escape_string(md5(uniqid(rand())));
$sql="INSERT INTO temp_users (
confirm_code, Username, Password,
EmailAddress, FirstName, LastName, State)
VALUES (
'$confirm_code', '$username', '$password',
'$email', '$firstname', '$lastname', '$state')";
$result=mysql_query($sql)
or die ("Query failed: " . mysql_error() . " Actual query: " . $query);
// if suceesfully inserted data into database, send confirmation link to email
if ($result) {
// send e-mail to ...
$to=$email;
// Your subject
$subject="Your confirmation link here";
// From
$header="blahblah#blahbalh.com";
// Your message
$message="Your Comfirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.employeediscounted.com/secret/login.php?passkey=$confirm_code";
// send email
$sentmail = mail($to,$subject,$message,$header);
}
// if not found
else {
echo "<div id='emailmsg'>Not found your email in our database.</div>";
}
// if your email succesfully sent
if($sentmail){
echo "<div id='emailmsg'>Your Confirmation link Has Been Sent To Your Email Address.</div>";
}
else {
echo "<div id='emailmsg'>Cannot send Confirmation link to your e-mail address.</div>";
}
}
}
else {
$valid = false;
}
return $valid;
}
Either I'm missing something, or you're simply calling the function twice:
$User->ValidReg();
$valid = $User->ValidReg();
So, yes, you will send two emails!
(Were you expecting the second call to fail because the user already exists? It won't because you're using two different tables, users vs. temp_users.)

Categories