Query not inserting string data into table - php

I am trying to insert some data into a MySQL database using PHP. The code I have works fine on localhost, but when I try it on my server the reg_user_id, reg_user_access_level and reg_user_status are inserted while all the other fields are not.
Please help, I've already wasted a day trying to sort this out.
everything up to here is fine
The PHP is:
else {
//sort the data
$reg_user_name = mysql_real_escape_string($_POST['reg_user_name']);
//create a salt for the password before encryption, use the same when retrieving the password!
$salt = 'mysalt';//not actually this
//first encryption
$reg_user_password = sha1($_POST['reg_user_password']);
//second encryption with salt
$reg_user_password = sha1($salt.$reg_user_password);
$reg_user_password = mysql_real_escape_string($reg_user_password);
/*** strip injection chars from email ***/
$reg_user_email = preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i','',$_POST['reg_user_email']);
$reg_user_email = mysql_real_escape_string($reg_user_email);
//connect to the db
include '../-useful_scripts/php/mysqli_connect_dsnydesign.php';
//check the connection
if($dbc) {
/*** check for existing username and email ***/
$query = "SELECT reg_user_name, reg_user_email FROM reg_users WHERE reg_user_name = '{$reg_user_name}' OR reg_user_email = '{$reg_user_email}';";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_row($result);
if (sizeof($row) > 0) {
foreach($row as $value) {
echo $value.'<br>';
}
if($row[0] == $reg_user_name) {
$errors[] = 'Sorry, the username is already in use';
}
elseif($row[1] == $reg_user_email) {
$errors[] = 'This Email address is already subscribed';
}
mysqli_free_result($result);
}
else {
/*** create a verification code ***/
$verification_code = uniqid();
//set the query
$query = "INSERT INTO reg_users(reg_user_id, reg_user_name, reg_user_password, reg_user_email, reg_user_access_level, reg_user_status) VALUES (NULL, '$reg_user_name', '$reg_user_password', '$reg_user_email', '1', '$verification_code');";
//run the query
if(mysqli_query($dbc, $query)) {
just goes on to notify of submission after this.

Check that you are using the same PHP version number on your server and your localhost. mysql_real_escape_string has been deprecated in the latest version of PHP.

Related

Notice: Undefined variable: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16

When signing into to the app with username, the email is not used hence the following error is throw and vice versa "Notice: Undefined index: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16"
I've tried putting the lines that were generating the error in conditions but those efforts proved futile
Login.php file(parts relevant to the error)
// STEP 1. Receive data / info paassed to current file
if ((empty($_REQUEST['username']) || empty($_REQUEST['password'])) && (empty($_REQUEST['email']) || empty($_REQUEST['password']))) {
$return['status'] = '400';
$return['message'] = 'Missing requird information';
echo json_encode($return);
return;
}
// securing received info / data from hackers or injections
$email = htmlentities($_REQUEST['email']);
$username = htmlentities($_REQUEST['username']);
$password = htmlentities($_REQUEST['password']);
// STEP 2. Establish connection with the server
require('secure/access.php');
$access = new access('localhost' , 'root', '' , 'menthor');
$access->connect();
// STEP 3. Check existence of the user. Try to fetch the user with the same email address
// STEP 3. Check availability of the login/user information
$username_aval = $access->selectUser_Username($username);
$email_aval = $access->selectUser_Email($email);
//$return = array();
// user is found
if ($username_aval) {
// Get encrypted password and salt from the server for validation
$encryptedPassword = $username_aval['password'];
$salt = $username_aval['salt'];
if ($encryptedPassword == sha1($password . $salt)) {
$return['status'] = '200';
$return['message'] = 'Successfully Logged In';
$return['id'] = $username_aval['id'];
$return['username'] = $username_aval['username'];
$return['email'] = $username_aval['email'];
$return['fullName'] = $username_aval['fullName'];
$return['lastName'] = $username_aval['lastName'];
$return['birthday'] = $username_aval['birthday'];
$return['gender'] = $username_aval['gender'];
$return['cover'] = $username_aval['cover'];
$return['ava'] = $username_aval['ava'];
$return['bio'] = $username_aval['bio'];
$return['allow_follow'] = $username_aval['allow_follow'];
} else {
// In event that encrypted password and salt does not match
$return['status'] = '201';
$return['message'] = 'Password do not match';
}
} else if ($email_aval) {
// Get encrypted password and salt from the server for validation
$encryptedPassword = $email_aval['password'];
$salt = $email_aval['salt'];
if ($encryptedPassword == sha1($password . $salt)) {
$return['status'] = '200';
$return['message'] = 'Successfully Logged In';
$return['id'] = $email_aval['id'];
$return['username'] = $email_aval['username'];
$return['email'] = $email_aval['email'];
$return['fullName'] = $email_aval['fullName'];
$return['lastName'] = $email_aval['lastName'];
$return['birthday'] = $email_aval['birthday'];
$return['gender'] = $email_aval['gender'];
$return['cover'] = $email_aval['cover'];
$return['ava'] = $email_aval['ava'];
$return['bio'] = $email_aval['bio'];
$return['allow_follow'] = $email_aval['allow_follow'];
} else {
// In event that encrypted password and salt does not match
$return['status'] = '202';
$return['message'] = 'Password do not match';
}
}else {
// In event that user is not found
$return['status'] = '403';
$return['message'] = 'User was not found';
}
// stop connection with server
$access->disconnect();
// pass info as JSON
echo json_encode($return);
Access.php file(parts relevant to error)
Will try to select any value in the database based on received Email
public function selectUser_Email($email) {
// array to store full user related information with the logic: key=>Value
$returnArray = array();
// SQL Language / Commande to be sent to the server
// SELECT * FROM users WHERE email='rondell#gmail.com'
$sql = "SELECT * FROM users WHERE email='" . $email . "'";
// executing query via already established connection with the server
$result = $this->conn->query($sql);
// result isn't zero and it has least 1 row / value / result
if ($result != null && (mysqli_num_rows($result)) >= 1) {
// converting to JSON
$row = $result->fetch_array(MYSQLI_ASSOC);
// assign fetched row to ReturnArray
if (!empty($row)) {
$returnArray = $row;
}
}
// throw back returnArray
return $returnArray;
}
// Will try to select any value in the database based on received Email
public function selectUser_Username($username) {
// array to store full user related information with the logic: key=>Value
$returnArray = array();
// SQL Language / Commande to be sent to the server
// SELECT * FROM users WHERE username='rondell'
$sql = "SELECT * FROM users WHERE username='" . $username . "'";
// executing query via already established connection with the server
$result = $this->conn->query($sql);
// result isn't zero and it has least 1 row / value / result
if ($result != null && (mysqli_num_rows($result)) >= 1) {
// converting to JSON
$row = $result->fetch_array(MYSQLI_ASSOC);
// assign fetched row to ReturnArray
if (!empty($row)) {
$returnArray = $row;
}
}
// throw back returnArray
return $returnArray;
}
Current results when logging in via web server
Notice: Undefined index: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16
{"status":"200","message":"Successfully Logged In","id":"44","username":"rondell","email":"rondell#gmail.com","fullName":"rondell","lastName":"","birthday":"","gender":"","cover":"","ava":"","bio":"","allow_follow":"1"}
Expected Results
{"status":"200","message":"Successfully Logged In","id":"44","username":"rondell","email":"rondell#gmail.com","fullName":"rondell","lastName":"","birthday":"","gender":"","cover":"","ava":"","bio":"","allow_follow":"1"}
use email as object or you can dump the request and see what is happening
Turns out the solution was pretty simple came to be after a bit of hard think... I just needed to simply create two login.php files... One dedicated to the users signing in with username and password and the other for users signing in with email and password...Cheers

Checked the query, database, table names, column names, etc. Still have no idea why this error occurred

The error that I occurred:
Fatal error: Call to a member function bind_param() on boolean in C:\wamp64\www\APU\SDP\reg-list-function.php on line 82
I'm writing a php script where the Admins are able to approve the registration of the user. I've checked through the formats of my database, column names, and even query, and still I've no idea why this error pops out. Any help or suggestions will be appreciated!
<?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
// Begin of the function: Registration List's Verification Form: Registration //
// First we check the form has submitted or not //
if (isset($_POST['submit-list-reg'])) {
// If it is, then we will retreive data from the input forms //
$regid = $_POST["regid"];
$reg_acccode = mysqli_real_escape_string($con, $_POST['reg-acccode']);
$reg_pw = mysqli_real_escape_string($con, $_POST['reg-pw']);
// Taking the current time //
date_default_timezone_set("Etc/GMT-8");
$now = date("Y-m-d H:i:s");
// Variable to store Error Message //
$error = '';
// Alphanumeric Generator //
function random_strings($length_of_string) {
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shufle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// Sorting out the query related to the function //
// Verify the user is an admin or not //
$VERFYADMIN = "SELECT * FROM user
WHERE status = 2 AND active = 1 AND account_code = '".md5($reg_acccode)."' AND password = '".md5($reg_pw)."'";
$VERFYADMINQ = mysqli_query($con, $VERFYADMIN);
//***BEGIN OF PROCESS***//
if (mysqli_num_rows($VERFYADMINQ) < 1) {
// if the admin is not verified, then inform the user and send him back to admin panel //
echo "<script>alert('ALERT: Information unable to be verified. Please try again.');";
echo "window.location.href='admin_panel.html';</script>";
exit(0);
} else {
// begin the process of registration //
while (list($key,$val) = #each ($regid)) {
// Now to verify the user's legitimacy //
// Take the user's vercode into variable first //
$USERVERCODE = "SELECT * FROM registration_list
WHERE registration_id = $val AND verified = 0";
$USERVERCODEQ = mysqli_query($con, $USERVERCODE);
if (mysqli_num_rows($USERVERCODEQ) < 1) {
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the data. Please try again.');";
echo "</script>";
} else {
while ($row = mysqli_fetch_array($USERVERCODEQ)) {
$vercode = $row["verification_code"];
}
// since we got the value of the vercode then we start to define the query //
$VERCODE = "SELECT * FROM verification_code WHERE verification_code = $vercode AND code_active = 1";
$VERCODEQ = mysqli_query($con, $VERCODE);
if (mysqli_num_rows($VERCODEQ) < 1) {
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the info of VERCODE. Please try again.');";
echo "</script>";
} else {
while ($row = mysqli_fetch_array($VERCODEQ)) {
$status = $row["code_status"];
}
// we will first insert the user main information into the database: i.e. password, username, etc. //
$account_code = random_strings(8);
$APPROVE = "INSERT INTO user (username, password, email, account_id, account_code, active, status, registered_date, verification_code)
SELECT username, password, email, account_id, '".md5($account_code)."', 1, $status, $now, verification_code
FROM registration_list
WHERE registration_id = ?";
$stmt = $con->prepare($APPROVE);
$stmt->bind_param("i", $val); // Problem around here //
$stmt->execute();
if (($stmt->error) == FALSE) {
I expect the process will be no issue at all as I've checked everything and nothing seems wrong to me.
Reformatting your code to make it more legible and easier to understand, we now have:
<?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
// Begin of the function: Registration List's Verification Form: Registration //
// First we check the form has submitted or not //
if (isset($_POST['submit-list-reg']))
{
// If it is, then we will retreive data from the input forms //
$regid = $_POST["regid"];
$reg_acccode = mysqli_real_escape_string($con, $_POST['reg-acccode']);
$reg_pw = mysqli_real_escape_string($con, $_POST['reg-pw']);
// Taking the current time //
date_default_timezone_set("Etc/GMT-8");
$now = date("Y-m-d H:i:s");
// Variable to store Error Message //
$error = '';
// Alphanumeric Generator //
function random_strings($length_of_string)
{
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shufle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// Sorting out the query related to the function //
// Verify the user is an admin or not //
$VERFYADMIN = "SELECT * FROM user
WHERE status = 2 AND active = 1 AND account_code = '".md5($reg_acccode)."' AND password = '".md5($reg_pw)."'";
$VERFYADMINQ = mysqli_query($con, $VERFYADMIN);
//***BEGIN OF PROCESS***//
if (mysqli_num_rows($VERFYADMINQ) < 1)
{
// if the admin is not verified, then inform the user and send him back to admin panel //
echo "<script>alert('ALERT: Information unable to be verified. Please try again.');";
echo "window.location.href='admin_panel.html';</script>";
exit(0);
}
else
{
// begin the process of registration //
while(list($key,$val) = #each ($regid))
{
// Now to verify the user's legitimacy //
// Take the user's vercode into variable first //
$USERVERCODE = "SELECT * FROM registration_list WHERE registration_id = $val AND verified = 0";
$USERVERCODEQ = mysqli_query($con, $USERVERCODE);
if (mysqli_num_rows($USERVERCODEQ) < 1)
{
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the data. Please try again.');";
echo "</script>";
}
else
{
while ($row = mysqli_fetch_array($USERVERCODEQ))
{
$vercode = $row["verification_code"];
}
// since we got the value of the vercode then we start to define the query //
$VERCODE = "SELECT * FROM verification_code WHERE verification_code = $vercode AND code_active = 1";
$VERCODEQ = mysqli_query($con, $VERCODE);
if (mysqli_num_rows($VERCODEQ) < 1)
{
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the info of VERCODE. Please try again.');";
echo "</script>";
}
else
{
while ($row = mysqli_fetch_array($VERCODEQ))
{
$status = $row["code_status"];
}
// we will first insert the user main information into the database: i.e. password, username, etc. //
$account_code = random_strings(8);
$APPROVE = "INSERT INTO user (username, password, email, account_id, account_code, active, status, registered_date, verification_code)
SELECT username, password, email, account_id, '".md5($account_code)."', 1, $status, $now, verification_code
FROM registration_list
WHERE registration_id = ?";
$stmt = $con->prepare($APPROVE);
$stmt->bind_param("i", $val); // Problem around here //
$stmt->execute();
if (($stmt->error) == FALSE)
{
In here are several things that I wouldn't personally do. As has been mentioned, using variables supplied by user input, even MD5 ones, directly in SQL queries should be best avoided.
The line "while(list($key,$val) = #each ($regid))", which sets the $val variable has an ampersand to suppress any error messages, this in turn could be causing you issues further down. It's best not to suppress these messages, but to find out why they are occurring, this could be the cause of a non numeric value being passed to your "bind_param" function. I'd also use single quotes instead of double quotes with the function as well.
Solved after I changed the variables that contained string value with this format -> ' " . $variable . " ' .

need help inserting a default text value into mysql

end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}

php mysql connecting to database, reading but not inserting

Hi I am trying to create a little email subscriber script for adding email addresses to my database. I was able to get it working fine using deprecated functions like mysql_connect but am making it better using mysqli instead. However for some reason I am no longer able to insert the email addresses into the database yet I can connect to the database fine and check the email address doesn't already exist. I would like to know why my INSERT doesn't seem to be working. I don't have much experience with PHP thanks.
if (!$link) {
echo "save_failed cannot connect"; //if cant connect show error
return;
}
mysqli_select_db($link,$mydb);
// Clean variables before performing insert
$clean_email = mysqli_real_escape_string($link,$_POST['email']);
$clean_subscriber = mysqli_real_escape_string($link,$_POST['firstname']);
$clean_date = mysqli_real_escape_string($link,$_POST['date']);
$query = "SELECT * FROM EmailList WHERE email = '{$email}'";//check if already in list
$result = mysqli_query($link,$query);
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 0) {
// Perform insert if not in list
$sql = "INSERT INTO EmailList (Email,Name,Date) VALUES
('$clean_email','$clean_subscriber','$clean_date')";
echo "Thank you for Subscribing to my blog!";
} else {
echo "You have subscribed already. Thank you for subscribing";
}
Looks like you're missing the line that runs the query:
mysqli_query($link,$sql);
You need to execute the query with
mysqli_query()
like so:
if (!$link) {
echo "save_failed cannot connect"; //if cant connect show error
return;
}
mysqli_select_db($link,$mydb);
// Clean variables before performing insert
$clean_email = mysqli_real_escape_string($link,$_POST['email']);
$clean_subscriber = mysqli_real_escape_string($link,$_POST['firstname']);
$clean_date = mysqli_real_escape_string($link,$_POST['date']);
$query = "SELECT * FROM EmailList WHERE email = '{$email}'";//check if already in list
$result = mysqli_query($link,$query);
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 0) {
// Perform insert if not in list
$sql = "INSERT INTO EmailList (Email,Name,Date) VALUES
('$clean_email','$clean_subscriber','$clean_date')";
mysqli_query($link,$sql)
echo "Thank you for Subscribing to my blog!";
} else {
echo "You have subscribed already. Thank you for subscribing";
}

PHP MySql - Check if column B matches GET input [duplicate]

This question already has an answer here:
PHP MySql - Check if value exists
(1 answer)
Closed 8 years ago.
I've got a database table with two columns:
EMAIL_ADDRESS and ACTIVATION_CODE
I need to make the script check if the Activation Code the user has submitted in the URL, matches the Email Address in the table. So far this isn't working.
$email = mysql_real_escape_string($_GET['email']);
$acticode = mysql_real_escape_string($_GET['code']);
$result = mysql_query("SELECT * FROM xActivate WHERE EMAIL_ADDRESS='$email',1");
if ($result = '$acticode') {
echo 'Code is valid';
} else {
echo 'Code is NOT valid';
}
check row with mysql_num_row
if(mysql_num_rows($result)>0){...}
and check valid code with
if(mysql_error())
You need to know the column in the database where the code is stored, also, you need to actually get the data
$email = mysql_real_escape_string($_GET['email']);
$acticode = mysql_real_escape_string($_GET['code']);
$code_found = false;
$result = mysql_query("SELECT * FROM xActivate WHERE EMAIL_ADDRESS='$email',1");
if($result) {
$row = mysql_fetch_assoc($result);
if($row) {
if ($row['codefield'] == $acticode) {
$code_found = true;
}
}
}
if($code_found) {
echo 'Code is valid';
} else {
echo 'Code is NOT valid';
}

Categories