PHP - Convert my deprecated MySQL to MySQLi - php

I'm a beginner here and i am learning the basic in converting from MySQL to MySQLi. I am currently working on this registration page which I would want to convert to the new MySQLi. Please advise me how to modify this script, I would prefer the procedural style.
UPDATE - The MySQLi coding is not working because it would insert into the database like the MySQL coding would, would appreciate if your can help me.
MYSQL
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysql_real_escape_string($_POST['name']);
$name2 = mysql_real_escape_string($_POST['name2']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email2 = mysql_real_escape_string($_POST['email2']);
$address = mysql_real_escape_string($_POST['address']);
$address2 = mysql_real_escape_string($_POST['address2']);
$address3 = mysql_real_escape_string($_POST['address3']);
$address4 = mysql_real_escape_string($_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysql_connect("localhost", "root", "Passw0rd") or die("Connection Error");
//select database
mysql_select_db("logindb") or die("Selection Error");
//namecheck
$namecheck = mysql_query("SELECT * FROM users WHERE email='{$email}'");
$count = mysql_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysql_query("INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysql_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
MYSQLI (NOT WORKING)
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysqli_real_escape_string($connect, $_POST['name']);
$name2 = mysqli_real_escape_string($connect, $_POST['name2']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$password2 = mysqli_real_escape_string($connect, $_POST['password2']);
$email2 = mysqli_real_escape_string($connect, $_POST['email2']);
$address = mysqli_real_escape_string($connect, $_POST['address']);
$address2 = mysqli_real_escape_string($connect, $_POST['address2']);
$address3 = mysqli_real_escape_string($connect, $_POST['address3']);
$address4 = mysqli_real_escape_string($connect, $_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysqli_connect("localhost", "root", "Passw0rd", "logindb") or die("Connection Error");
//namecheck
$namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'");
$count = mysqli_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysqli_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>

Converting to mysqli is not about adding i to the old library.
The main difference is that mysqli offers prepared statement feature.
This saves you from the tedious task of manually escaping values with mysqli_real_escape_string.
The proper way to do it is to prepare your query:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = mysqli_prepare($connect, $query)) {
mysqli_stmt_bind_param($stmt,'sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/*Count the rows*/
if( mysqli_stmt_num_rows($stmt) > 0){
echo"New Record has id = ".mysqli_stmt_insert_id($stmt);
}else{
printf("Errormessage: %s\n", mysqli_error($connect));
die();
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
In addition to prepared statement, another advantage is the coding style, mysqli introduces OOP style, here is the same code in that style:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = $connect->prepare($query)) {
$stmt->bind_param('sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute query */
$stmt->execute();
/*Count the rows*/
if($stmt->num_rows > 0){
echo"New Record has id = ".$connect->insert_id;
}else{
var_dump($connect->error);
die();
}
/* close statement */
$stmt->close();
}
/* close connection */
$connect->close();
Both would achive the same. Good luck

I noticed one error in your script (mysqli script):
Instead of
$count = mysql_num_rows($namecheck);
do
$count = mysqli_num_rows($namecheck);
You can also check for errors in your query, like this (from w3schools - http://www.w3schools.com/php/func_mysqli_error.asp):
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')"))
{
echo("Error description: " . mysqli_error($con));
}
Also try to do some debugging (echo some results) in your script to find errors.

Pass connection parameter inside
$lastid = mysqli_insert_id();
like
$lastid = mysqli_insert_id($connect);

Related

Why is this piece of code not writing anything into database?

I need a second pair of eyes to have a look at my code and tell me what I am missing, as I think I have identified the portion of code that doesn't work, I just don't know why.
Basically I am trying to register a user to a database, in a way that it prevents SQL injection. For the life of me however, it doesn't work. When I deconstruct the code and make it less secure, it works. Anyway, code is here:
//require_once 'sendEmails.php';
session_start();
$username = "";
$email = "";
$user_dob = "";
$user_fname = "";
$user_lname = "";
$user_telephone = "";
$errors = [];
$servername = '';
$login = '';
$password = '';
$DBname = '';
$rows = 0;
$query = "";
$conn = new mysqli($servername, $login, $password, $DBname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn) {
echo "Connected successfully";
}
// SIGN UP USER
if (isset($_POST['signup-btn'])) {
if (empty($_POST['username'])) {
$errors['username'] = 'Username required';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email required';
}
if (empty($_POST['password'])) {
$errors['password'] = 'Password required';
}
if (isset($_POST['password']) && $_POST['password'] !== $_POST['passwordConf']) {
$errors['passwordConf'] = 'The two passwords do not match';
}
if (empty($_POST['dob'])) {
$errors['dob'] = 'Date of birth required';
}
if (empty($_POST['fname'])) {
$errors['fname'] = 'First name required';
}
if (empty($_POST['lname'])) {
$errors['lname'] = 'Last name required';
}
if (empty($_POST['telephone'])) {
$errors['telephone'] = 'Telephone number required';
} //--checks input in browser
//I think it works untill this point...
$token = bin2hex(random_bytes(50)); // generate unique token
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT); //encrypt password
$user_dob = $_POST['dob'];
$user_fname = $_POST['fname'];
$user_lname = $_POST['lname'];
$user_telephone = $_POST['telephone'];
$email = $_POST['email'];
//Above assigns inputted values into variables declared at the start
//echo $token, $email; //-- this works
//nl2br() ; // -- line break in php
// Check if email already exists
//$result = $mysqli->query("SELECT * FROM User_tbl WHERE email='$email' LIMIT 1");
$sql = "SELECT * FROM User_tbl WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > $rows) {
$errors[] = $email;
echo "Email already exists";
}
$errorsInt = count($errors);
echo mysqli_num_rows($result);
echo count($errors);
echo $errorsInt;
if ($errorsInt === $rows) {
$query = "INSERT INTO User_tbl SET token=?, username=?, password=?, user_dob=?, user_fname=?, user_lname=?, user_telephone=?, email=?";
// "INSERT INTO User_tbl VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
echo $query;
//---------------------------------------------------------------------------
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();
echo $result;
if ($result) {
$user_id = $stmt->insert_id;
$stmt->close();
$_SESSION['id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['verified'] = false;
$_SESSION['message'] = 'You are logged in!';
$_SESSION['type'] = 'alert-success';
header('location: index.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not register user";
}
}
}
The problem I believe starts here:
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();

PHP choose another username

I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user

My PHP Registration form wont work

I am trying to create a registration form and passing in mysqli_real_escape_string and salt on my form. However for some reason my codes won't go on. Even if I will enter the right information on my form it won't just process it correctly. Basically I created a function that will do the verification.
Here's my codes:
<?php
session_start();
require("new-connection.php");
global $connection;
$first_name = mysqli_real_escape_string($connection, $_POST['first_name']);
$last_name = mysqli_real_escape_string($connection, $_POST['last_name']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$salt = bin2hex(openssl_random_pseudo_bytes(22));
$encrypted_password = md5($password . '' . $salt);
if(isset($_POST['action']) && ($_POST['action']) == 'register'){
//call to function
register_user($_POST); //use the ACTUAL POST
}
elseif(isset($_POST['action']) && ($_POST['action']) == 'login'){
login_user($_POST);
}else{
session_destroy();
header('Location: homepage.php');
die();
}
function register_user(){ //just a parameter called post
$_SESSION['errors'] = array();
if(empty($first_name)){
$_SESSION['errors'][] = "first name can't be blank!";
}
if(empty($last_name)){
$_SESSION['errors'][] = "last name can't be blank!";
}
if(empty($password)){
$_SESSION['errors'][] = "password is required!";
}
if($password != $post['confirm_password']){
$_SESSION['errors'][] = "passwords must match!";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$_SESSION['errors'][] = "please use a valid email address!";
}
//end of validation
//now count errors
if(count($_SESSION['errors']) > 0){
header('Location: homepage.php');
die();
}else{
$query = "INSERT INTO users(first_name, last_name, password, email, created_at, updated_at)
VALUES ('$first_name', '$last_name','$password', '$email', NOW(), NOW())";
$result = run_mysql_query($query);
$_SESSION['message'] = "user successfully added";
header('Location: homepage.php');
die();
}
}
function login_user($post){ //just a parameter called post
$query = "SELECT * FROM users WHERE users.password = '{$post['password']}'
AND users.email = '{$post['email']}'";
$user = fetch($query); //go and grab all users on above condition
if(count($user) > 0){
$_SESSION['user_id'] = $user[0]['id'];
$_SESSION['first_name'] = $user[0]['first_name'];
$_SESSION['logged_in'] = true;
header('Location: success-homepage.php');
die();
}else{
$_SESSION['errors'][] = "cant find users";
header('Location: homepage.php');
die();
}
}
?>
Any idea what went wrong???
NOTE: It wont insert the record + its giving the error on $_SESSION even the data entered is correct.
What is it the error ? If you have a White page, insert in the top of the page:
error_reporting (E_ALL);
ini_set('display_errors',1);
Please check this:
<?php
session_start();
require("new-connection.php");
global $connection;
$first_name = mysqli_real_escape_string($connection, $_POST['first_name']);
$last_name = mysqli_real_escape_string($connection, $_POST['last_name']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$salt = bin2hex(openssl_random_pseudo_bytes(22));
$encrypted_password = md5($password . '' . $salt);
if(isset($_POST['action']) && ($_POST['action']) == 'register'){
//call to function
register_user($firstname, $last_name, $email, $password, $salt, $encrypted_password); //use the ACTUAL POST // Cant only use post because isn't escaped
}
elseif(isset($_POST['action']) && ($_POST['action']) == 'login'){
login_user($email, $password);
}else{
session_destroy();
header('Location: homepage.php');
die();
}
function register_user($firstname, $last_name, $email, $password, $salt, $encrypted_password){ // Pass all escaped variables here becasue the $_POST isn't escaped
$_SESSION['errors'] = array();
if(empty($first_name)){
$_SESSION['errors'][] = "first name can't be blank!";
}
if(empty($last_name)){
$_SESSION['errors'][] = "last name can't be blank!";
}
if(empty($password)){
$_SESSION['errors'][] = "password is required!";
}
if($password != $post['confirm_password']){
$_SESSION['errors'][] = "passwords must match!";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$_SESSION['errors'][] = "please use a valid email address!";
}
//end of validation
//now count errors
if(count($_SESSION['errors']) > 0){
header('Location: homepage.php');
die();
}else{
// Add backticks around column and table names to prevent mysql reserved words error
$query = "INSERT INTO `users` (`first_name`, `last_name`, `password`, `email`, `created_at`, `updated_at`)
VALUES ('$first_name', '$last_name','$password', '$email', NOW(), NOW())";
$result = mysqli_query($connection, $query);
$_SESSION['message'] = "user successfully added";
header('Location: homepage.php');
die();
}
}
function login_user($email, $password){ //just a parameter called post
// No need to add table name
$query = "SELECT * FROM `users` WHERE `password` = '$password'
AND `email` = '$email'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) >= 1) {
$user = mysqli_fetch_assoc($result); //go and grab all users on above condition
// Check if there was atleast 1 user with the specified credentials
if(count($user) >= 1){
$_SESSION['user_id'] = $user['id'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['logged_in'] = true;
header('Location: success-homepage.php');
die();
}else{
$_SESSION['errors'][] = "cant find users";
header('Location: homepage.php');
die();
}
} else {
echo 'no user was found';
}
}
?>

PHP - mysqli_select_db not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am switching from MySQL to MySQLi and I am upon an error which i Google and was unable to solve. The problem is with the selection (mysqli_select_db) of the database which was okay prior to the transition where i was using (mysql_select_db). Hope your can help me solve this problem.
UPDATE - MY CURRENT CODE
<?php
$submit = $_POST['submit'];
//form data
$name = mysqli_real_escape_string($_POST['name']);
$name2 = mysqli_real_escape_string($_POST['name2']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$password2 = mysqli_real_escape_string($_POST['password2']);
$phone2 = mysqli_real_escape_string($_POST['phone2']);
$email2 = mysqli_real_escape_string($_POST['email2']);
$address = mysqli_real_escape_string($_POST['address']);
$address2 = mysqli_real_escape_string($_POST['address2']);
$address3 = mysqli_real_escape_string($_POST['address3']);
$address4 = mysqli_real_escape_string($_POST['address4']);
if ($submit) {
//connect database
$connect = mysqli_connect("localhost", "root", "Passw0rd", "logindb") or die ("Connection Error");
//namecheck
$namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'");
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$phone2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
echo "Password must be least 8 characters";
}
if(!preg_match("#[A-Z]+#",$password)) {
echo "Password must have at least 1 upper case characters";
}
if(!preg_match("#[0-9]+#",$password)) {
echo "Password must have at least 1 number";
}
if(!preg_match("#[\W]+#",$password)) {
echo "Password must have at least 1 symbol";
}
if($_POST['password'] != $_POST['password']) {
echo "Password does not match";
}
if($_POST['email2'] == $_POST['email']) {
echo "Secondary email must not be the same as Email";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
//generate random code
$random = rand(11111111,99999999);
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//register the user
$register = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$phone2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysqli_insert_id($connect);
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
pass connection ref in 1st param in mysqli_select_db() function, try this
mysqli_select_db($connect, "logindb") or die("Selection Error");
and also in mysqli_query($connect, "query here")
UPDATE all mysqli_* functions required connection ref except result functions
Quick complete solution
<?php
$submit = $_POST['submit'];
//connect database
$connect = mysqli_connect("localhost", "root", "Passw0rd") or die ("Connection Error");
//select database
mysqli_select_db($connect, "logindb") or die("Selection Error");
//form data
$name = mysqli_real_escape_string($connect, $_POST['name']);
$name2 = mysqli_real_escape_string($connect, $_POST['name2']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$password2 = mysqli_real_escape_string($connect, $_POST['password2']);
$phone2 = mysqli_real_escape_string($connect, $_POST['phone2']);
$email2 = mysqli_real_escape_string($connect, $_POST['email2']);
$address = mysqli_real_escape_string($connect, $_POST['address']);
$address2 = mysqli_real_escape_string($connect, $_POST['address2']);
$address3 = mysqli_real_escape_string($connect, $_POST['address3']);
$address4 = mysqli_real_escape_string($connect, $_POST['address4']);
if ($submit) {
//namecheck
$namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'");
$count = mysqli_num_rows($namecheck);
if(strlen($email)<5) {
echo "Email must have at least 5 characters";
}
else
{
if($count==0) {
}
else
{
if($count==1) {
echo "User already Exists";
}
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$phone2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
echo "Password must be least 8 characters";
}
if(!preg_match("#[A-Z]+#",$password)) {
echo "Password must have at least 1 upper case characters";
}
if(!preg_match("#[0-9]+#",$password)) {
echo "Password must have at least 1 number";
}
if(!preg_match("#[\W]+#",$password)) {
echo "Password must have at least 1 symbol";
}
if($_POST['password'] != $_POST['password']) {
echo "Password does not match";
}
if($_POST['email2'] == $_POST['email']) {
echo "Secondary email must not be the same as Email";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
//generate random code
$random = rand(11111111,99999999);
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//register the user
$register = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$phone2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysqli_insert_id($connect);
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
You also have to write fields after table name on line 70 $register = mysqli_query($connect, "INSERT INTO users and before values VALUES ( like example below.
INSERT INTO users(username,userpass,name,email,userrole,joined,userstatus) VALUES('$username','$userpass','$name','$email','$userrole','$joined','$userstatus')
Replace you line #70 with the following one
$register = mysqli_query($connect, "INSERT INTO users(name,name2,email,password,password2,phone2,email2,address,address2,address3,address4,random,active) VALUES ('$name','$name2','$email','$password','$password2','$phone2','$email2','$address','$address2','$address3','$address4','$random','0')");

I need to check my db to see if a username or email is already in use

I've started a thread or two so far but nothing has got resolved. I'm not able to use the mysqlnd because i'm using a shared hosting account with godaddy.
All i need to do is check if my email address and/or username is in use; if they are in use throw and error, if not.. all is well.
Here is my code:
$input_errors = array();
if (!empty($_POST['username'])) {
$user = $_POST['username'];
} else {
$input_errors['username'] = "Must fill out username";
}
$email = filter_input(INPUT_POST, 'usermail', FILTER_VALIDATE_EMAIL);
if (false === $email) {
$input_errors['usermail'] = "Not a valid email address";
}
if(count($input_errors) > 0) {
print_r($input_errors); die();
}
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = ?
OR email = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ss", $user, $email);
$stmt->execute();
$results = $stmt->get_result();
$data = mysqli_fetch_assoc($results);
if ($data['amount'] > 0)
{
print "User already exists";
}
}
else {
$stmt = $mysqli->stmt_init();
if (!$stmt) {
echo "Init failed";
} else {
$cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
if ($stmt->prepare($cmd)) {
$stmt->bind_param('ss', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . " row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
mysqli_close($mysqli);
}
}
bind_result() does not work.
Change your sql statement to the following:
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = '".mysqli_real_escape_string($_POST['username'])."' OR email = '".mysqli_real_escape_string($email)."'";

Categories