PHP - mysqli_select_db not working [closed] - php

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')");

Related

Wrong Username/Password Message though the record exists in the database

I just started off with PHP and attempted to make a simple login and sign-up page. The sign-up module works perfectly with the records being successfully being inserted into the database. But, whenever I try to log in, it always throws me a wrong password/username combination.
I am really new to web development so I am not looking for advice on SQL injections and other security-related issues. Could someone just tell me how I could make this work using PHP and MySQL only.
I am using the XAMPP server with phpMyAdmin.
Here is my Config.php file which I use to validate the data I accept through the forms.
<?php
session_start();
//variable declaration
$email = "";
$name = "";
$batch = "";
$password = "";
$errors = array();
$_SESSION['success'] = "";
//connect to database
$conn = mysqli_connect('localhost', 'root', '', 'timetable');
//Register User
if(isset($_POST['reg_user']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$batch = mysqli_real_escape_string($conn, $_POST['batch']);
$password_1 = mysqli_real_escape_string($conn, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($conn, $_POST['password_2']);
//form validation
if($batch != 2016 || $batch != 2017 || batch != 2018 || batch != 2019)
{
array_push($errors, "Batch should be one of 2016/2017/2018/2019.");
}
if($password_1 != $password_2)
{
array_push($errors, "The two passwords do not match.");
}
if(count($errors) == 0)
{
$password = hash('sha512', $password);
$query = "INSERT INTO chairperson(email, name, batch, password)
VALUES('$email', '$name', '$batch', '$password')";
mysqli_query($conn, $query);
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in.";
header('location: index.php');
}
}
//Login user
if(isset($_POST['login_user']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if(count($errors) == 0)
{
$password = hash('sha512', $password);
$query = "SELECT * FROM chairperson WHERE email='$email' AND password='$password'";
$results = mysqli_query($conn, $query);
if(mysqli_num_rows($results) == 1)
{
$_SESSION['success'] = "You are now logged in.";
$_SESSION['email'] = $email;
header('location: index.php');
}
else
{
array_push($errors, "Wrong username/password combination.");
}
}
}
?>
<?php
session_start();
//variable declaration
$email = "";
$name = "";
$batch = "";
$password = "";
$errors = array();
$_SESSION['success'] = "";
//connect to database
$conn = mysqli_connect('localhost', 'root', '', 'timetable');
//Register User
if(isset($_POST['reg_user']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$batch = mysqli_real_escape_string($conn, $_POST['batch']);
$password_1 = mysqli_real_escape_string($conn, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($conn, $_POST['password_2']);
//form validation
if(($batch != 2016) && ($batch != 2017) && ($batch != 2018) && ($batch != 2019))
{
array_push($errors, "Batch should be one of 2016/2017/2018/2019.");
}
if($password_1 != $password_2)
{
array_push($errors, "The two passwords do not match.");
}
if(count($errors) == 0)
{
$password = password_hash($password,PASSWORD_BCRYPT);
$query = "INSERT INTO chairperson(email, name, batch, password)
VALUES('$email', '$name', '$batch', '$password')";
mysqli_query($conn, $query);
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in.";
header('location: index.php');
}
}
//Login user
if(isset($_POST['login_user']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if(count($errors) == 0)
{
$query = "SELECT * FROM chairperson WHERE email='$email' ";
$results = mysqli_query($conn, $query);
if(mysqli_num_rows($results) == 1)
{
$row=mysqli_fetch_assoc($results);
if(password_verify($password, $row['password']))
{
$_SESSION['success'] = "You are now logged in.";
$_SESSION['email'] = $email;
header('location: index.php');
}
else
{
array_push($errors, "Wrong username/password combination.");
}
}
else
{
array_push($errors, "Wrong username/password combination.");
}
}
}
?>

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

PHP Login System Error Not appearing on page

I'm using notepad++ and Godaddy's phpMyAdmin to host the server. The file does not display anything when posted and whenever I put it in a PHP code checker it tells me this:
Error: There is 1 more opening parenthesis '(' found This count is unaware if parenthesis are inside of a string)
and
Error: There is 1 more opening curly braces '{' found
This count is unaware if curly braces are inside of a string
Any help would be much appreciated.`
//Declaring them as variables
$username = $_POST["username"];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
//error handling
if((!$username) || (!$fname) || ($lname) || ($email) || ($pass1) || ($pass2))
{
$message = "please insert all fields in theform below!";
}
else
{
if($pass1 != $pass2)
{
$message = "Passwords do not match!"
}
}
else
//gathering the data
{
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
$pass1 = sha1(#pass1);
$email = mysql_real_escape_string($email);
//check for dublicates
$user_query = mysql_query("SELECT username FROM members WHERE username ='$username' LIMIT 1") or die("Could not check username");
$count_username = mysql_num_rows($user_query);
$user_query = mysql_query("SELECT email FROM members WHERE username ='$email' LIMIT 1") or die("Could not check email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0)
{
$message = "Your username is alread in use";
}
else if($count_email > 0)
{
$message = " Your email is alread in use";
}
else
//insert the memebers to database
{
$ip_address = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("INSERT INTO members(username, firstname, lastname,email,password,ip_adress,sign_up_date)VALUES('$username','$fname','$lname','$email', '$pass1','$ip_address',now()")or die("could not insert");
$member_id = mysql_insert_id();
mkdir(,"users/$member_id",0755);
$message = "You have now been registered";
}
}
The issue is that your else statement was misplaced. I moved it after the if statement where you check that the passwords match.
//Declaring them as variables
$username = $_POST["username"];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
//error handling
if((!$username) || (!$fname) || ($lname) || ($email) || ($pass1) || ($pass2))
{
$message = "please insert all fields in theform below!";
}
else
{
if($pass1 != $pass2)
{
$message = "Passwords do not match!"
}
else
{
//All required fields are filled
//Paswords match
//gathering the data
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
$pass1 = sha1(#pass1);
$email = mysql_real_escape_string($email);
//check for dublicates
$user_query = mysql_query("SELECT username FROM members WHERE username ='$username' LIMIT 1") or die("Could not check username");
$count_username = mysql_num_rows($user_query);
$user_query = mysql_query("SELECT email FROM members WHERE username ='$email' LIMIT 1") or die("Could not check email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0)
{
$message = "Your username is alread in use";
}
else if($count_email > 0)
{
$message = " Your email is alread in use";
}
else
//insert the memebers to database
{
$ip_address = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("INSERT INTO members(username, firstname, lastname,email,password,ip_adress,sign_up_date)VALUES('$username','$fname','$lname','$email', '$pass1','$ip_address',now()")or die("could not insert");
$member_id = mysql_insert_id();
mkdir(,"users/$member_id",0755);
$message = "You have now been registered";
}
}
}

why won't this page redirect?

I'm having a problem with redirecting a page in php.
<?php
include '../include/dbfunctions.php';
$email = $password = "";
$err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['login']) && !empty($_POST['password'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$link = get_db_connection();
if (mysqli_connect_errno()) {
die(" Something went wrong ! ");
}
$user_email = mysqli_real_escape_string($link, $email);
$user_password = mysqli_real_escape_string($link, $password);
$query = "SELECT username FROM user WHERE user_email = '$user_email' AND user_password = SHA1('$user_password') AND user_active = '1';";
$data = mysqli_query($link, $query);
if (mysqli_num_rows($data) == 1) {
$row = mysqli_fetch_array($data);
$username = $row['username'];
mysqli_close($link);
if (!empty($username)) {
header('location:http://www.xxxxxxxxxxxxxx.be/login/dashboard.php');
exit();
}
} else {
$err = "Invalid combination of e-mail and password";
echo $err;
}
} else {
}
}
?>
I can't figure it out. If i fill in an invalid password or email, i get the error message. But when they are correct, nothing happens.
if (!empty($username)) {
header('location:http://www.yoursite.be/login/dashboard.php?error=error in login please try agine');
exit();
}
if (!empty($username)) {
header('location:http://www.xxxxxxxxxxxxxx.be/login/dashboard.php');
exit();}
$username might be empty.

Catchable fatal error: Object of class mysqli could not be converted to string

I was trying to create a Registration form for my project but unfortunately i got this error while i could not find any error in the code!Please help me to get ride from this Issue !
my code
<?php
// this file is connected with regform.php
$firstname= $_POST['firstname'];
$lastname =$_POST['lastname'];
$email =$_POST['email'];
$password =$_POST['password'];
$confirmpassword =$_POST['confirmpassword'];
$address =$_POST['address'];
$balance =$_POST['balance'];
$password_hash = md5($password);
$bookConn = mysqli_connect("localhost", "root","", "bookstore") OR die("wrong execution");
$queryS = "SELECT Email FROM customer";
$resultSQ = mysqli_query($bookConn , $queryS);
$flag=0;
while($row=mysqli_fetch_array($resultSQ))
{
if($email == $row['Email'])
{
$flag=1;
}
}
if($flag==0)
{
if($password == $confirmpassword)
{
$query = "INSERT INTO user (firstName , LastName ,Email , Password , Address , Balance )values('".$firstname."', '".$lastname."' ,'".$email."' , '".$password_hash."', '".$address."' , '".$balance."')";
$result = mysqli_query($bookConn , $query) OR die($bookConn);
if ($result)
{
echo "successfuly Registered";
}
else {
echo "something went wrong!";
}
}
else{
echo "Passowrd does not match!";
}
}
else{
echo "Email is already existed in the Database!";
}
mysqli_close($dbc);
?>
There are two error seems in your code:-
mysqli_close($dbc). You never created $dbc in your code. It must be mysqli_close($bookConn).
You need to modified your last mysqli_query like this:-
$result = mysqli_query($bookConn , $query) OR die(mysqli_error($bookConn));
Note:- I hope by doing these changes you will get rid of your proble. Thanks.

Categories