my registration form details are not getting in the database (phpmyadmin) - php

Whenever I try any new registration it creates the user but no information is fed into the database
database name is chatbox
and table name is users
<?php
if (isset($_POST['submit'])){
$con = mysql_connect('localhost','root','');
mysql_select_db('chatbox',$con);
$uname = $_POST['username'];
$pword = $_POST['password'];
$pword2 = $_POST['password2'];
if($pword != $pword2){
echo "Passwords do not match. <br>";
}
else {
$checkexist = mysql_query("SELECT username FROM users WHERE username='$uname'");
if (mysql_num_rows($checkexist)){
echo "<center>";
echo "Username already exists, Please select different username<br>";
echo "</center>";
}
else {
mysql_query("INSERT INTO users ('username','password') VALUES ('$uname','$pword')");
echo "<center>";
echo "You have successfully registered. Click <a href='index.php'>here</a> to go start chat<br>";
echo "</center>";
}
}
}

Firstly, you should have a look at mysqli http://php.net/manual/en/book.mysqli.php it's the 'improved' version of mysql, and mysql is now deprecated as of php 5.5
Anyway, to help diagnose, you can use 'or die', to output a message if your script was unsuccessful.
$con = mysql_connect('localhost','root','') or die("could not connect");
mysql_select_db('chatbox',$con) or die("could not select db");
if you're saving users' passwords in a database, you should definitely look into encrypting them, see: http://php.net/manual/en/faq.passwords.php to begin with.
Janaka is right, in your insert statement, either use backticks for the fields `` or don't use any kind of quotes at all (username, password)

There is a little unfamiliarity with your sql query. Try this.
INSERT INTO users (`username`,`password`) VALUES ('$uname','$pword')

Related

How to echo an item from a database

I am still in the process of learning PHP so forgive me for the poor code.
I am attempting to get the users first name to output once they have logged in, however nothing is returning, please may I have some help.
<?php
session_start();
$DATABASE_HOST="localhost";
$DATABASE_USER="root";
$DATABASE_PWORD="";
$DATABASE_NAME="registration";
$connection=mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PWORD, $DATABASE_NAME);
if (mysqli_connect_errno()){
//if there is an issue with connecting to the database, ends code and displays the error
die("failed to connect to server: " .mysqli_connect_error()); //kills program
}
if (!isset($_POST['email'], $_POST['pswd'])){ //checking if both fields were inputted into on the form, isset()checks if data exists
//unable to get data
die("please fill in both email and password"); //kills program
}
$email = mysqli_real_escape_string($connection, $_POST['email']); //saves input as string, preventing misinterpretation
$password = mysqli_real_escape_string($connection, $_POST['pswd']);//saves input as string, preventing misinterpretation
$SQLstatement = "SELECT * FROM users WHERE email='$email' and password='$password'"; //querys the database for match
$Queryresult = mysqli_query($connection, $SQLstatement) or die(mysqli_error($connection)); //runs the query
$rowsQueryResult = mysqli_num_rows($Queryresult);//number of 'emails' in database where the emails match
$dbFirstName=$rowsQueryResult ['firstName'];
if ($rowsQueryResult==1){//if the number of emails where a match is made, is 1
echo "Welcome $dbFirstName <br/> ";
echo "successful login. <a href='accountPage.php'>Click</a> here to access the accounts page"; //successful login, links to accounts page
$_SESSION['firstName']=$dbFirstName;
}else{ //if matches are 0 or >=2
die ('unsuccessful login'); //kills program
}
?>
Thank you for your time and help
This problem can be solved by using the mysqli_fetch_assoc() function in place of mysqli_num_rows(). However, I would recommend you to use PDO since it's easier to implement and more readable.
The mysqli_num_rows() function returns the number of rows in a result set.
$rowsQueryResult = mysqli_num_rows($Queryresult);`
will give number of 'emails' in database where the emails match.
You need to use mysqli_fetch_assoc() as
$row = mysqli_fetch_assoc($Queryresult);
$dbFirstName=$row['firstName'];

mysql_query() Is Returning Error "No Database Selected"?

I'm writing a script that let's users update their passwords. It does this by first locating the entered email address of the user, then updates the password to whatever they create. However, I'm getting a "no database selected" error from mysql_query(). The email address I'm testing is valid and is in the database, and my query syntax looks good. I don't know what could be causing this. Any advice would be appreciated, thank you all in advance.
Furthermore, my form that is posting these values is ok, as I've looked over that many times.
<?php
mysql_connect('localhost','calsheet_project','UUx[#]MoF4?F') or die("couldn't connect!");
$eml = $_POST['data'];
$newPassword = $_POST['data1'];
$cnewPassword = $_POST['data2'];
$query = mysql_query("SELECT * FROM accounts WHERE email = $eml") or die(mysql_error());
$fetch = mysql_fetch_array($query);
var_dump($fetch);
echo mysql_error();
if($fetch > 0) {
mysql_query("UPDATE accounts SET password=$cnewPassword WHERE
email=$eml");
echo "Password Reset!";
} else {
echo "email address cannot be found.";
};
?>
If working correctly, it should update the password field for the associated email address of the user. But, it's showing the error "no database selected."
You should use the following code before you executemysql_query
// select the query database
mysql_select_db("db_name");
and the PHP official said mysql_connect() is not good anymore for security reasons.
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, > the MySQLi or PDO_MySQL extension should be used.
for more details see http://php.net/manual/en/function.mysql-connect.php

When I go to Localhost and try the username and the password it tells me that is an error?

When I go to Localhost and try the username and the password it tells me that is an error? why?
1) Use password_hash docs
while registration use password_hash() to hash the password and store it in database and while login use password_verify() to verify the password like this .
2) user prepared statement to avoid sql injection
<?php
session_start();
if(isset($_SESSION["user_id"])){
header("location: /web/home.php");
}
if(isset($_POST["s"])){
$username = $_POST["un"];
$password = $_POST["ps"];
$conn = mysqli_connect("localhost","root","","my_db") or die("Connection failed: " . mysqli_connect_error());
$stmt = $conn->prepare("SELECT * FROM table_name WHERE username=?");
$stmt->bind_param('s',$username);
$stmt->execute();
$get_result =$stmt->get_result();
$row_count= $get_result->num_rows;
if($row_count>0)
{
$record = $get_result->fetch_assoc();
if(password_verify($password,$record['password']))
{
$_SESSION["user_id"]= $record["user_id"];
header("location: /web/home.php");
}
else
{
echo "<h3 style = 'color:red'>Error in username or password</h3>";
}
}else{
echo "<h3 style = 'color:red'>Error in username or password</h3>";
}
}
?>
It looks entered username/password or both are not matching with the database table my_db.
Reasons :
Localhost means the db is getting refereed in local. So in your local database under my_db table there is no user exists with the given username and password.
May be that data is valid in remote database server.
Solution :
1. Take a dump from remote database and put in your localhost so that your local db and remote db are replica
2. For simple solution, just insert the required details in my_db table.
Hope that helps

Values are not being added to the database

I am very new to PHP and Mysql. I have made a registeration form but the values being inputted are not being saved in my database. I don't know why. I am connected to the database. Could anyone give me some insight? By the way, I know you are going to say "Mysql" is deprecated. But I am just starting out and learning how all of this works. As soon as I have a thorough understanding of the processes I am going to change my code to Mysqli...
<?php
//form data
$submit = strip_tags($_POST['submit']);
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$usernamereg = strip_tags($_POST['usernamereg']);
$passwordreg = strip_tags($_POST['passwordreg']);
$email = strip_tags($_POST['email']);
$emailcheck = strip_tags($_POST['emailcheck']);
$date = date("Y-m-d");
if($submit)
{
//check for existence
if($fname&&$lname&&$usernamereg&&$passwordreg&&$email&&$emailcheck)
{
//encrypt password
$password = md5($passwordreg);
if(strlen($usernamereg)>25)
{
echo "Username must be 25 characters or less.";
}
else
{
//checks password length
if(strlen($passwordreg)<6)
{
echo "Passwords must be atleast 6 characters long";
}
else
{
if($email!=$emailcheck)
{
echo "emails to not match";
}
else
{
//open database
$connect = mysql_connect("localhost","root","clandestine");
mysql_select_db("user_db"); //selects database
$queryreg = mysql_query("INSERT INTO users VALUES('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
echo "You have been registered!";
}
}
}
}
else
echo "Please fill in <b>all</b> fields!";
Try assigning the columns in the INSERT query.
$queryreg = mysql_query("INSERT INTO users (`randomField`, `date`, `first_name`, `last_name`, `username`, `password`, `email`, `email_check`) VALUES ('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
What is the first column supposed to be?
Have you done any sanity checking? (ie, printing test data to the screen at certain points in the code to make sure your IF statements are evaluating to true?
Additionally, try saving your INSERT query as a variable string:
$query = "INSERT INTO.............";
and then printing it to the screen. Copy and paste that query into PHPMyAdmin (if you have access to it) and see if there are any errors with your statement. PMA will tell you what errors there are, if any.
EDIT: Also, please don't ever MD5 a password or other highly sensitive data. Use a secure algorithm and salt the password. If you're unsure of what this all means:
refer to this link
What do you get if you do:
$query = "INSERT INTO users
(date, first_name, last_name, username, password, email, email_check)
VALUES
('$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck')";
mysql_query($query)or die('Error: <br />'.$query.'<br />'.mysql_error());
Note the removal of the backticks was just to simplify the code. It's correct to leave them in but with no spaces etc in your column names it should work anyway. Oh, and this is NOT good practice for production, of course. Just really clear debug.

mysql_query with PHP variables

This should be easy but I'm can't make it work.
The idea is to look for an email adress posted from a form. If it exists echo something and if not echo something else.
My code is:
<?php
//MySQL Database Connect
mysql_connect("localhost", "********", "**********")
or die("Unable to connect to MySQL");
//get data from form
$email=$_POST['email'];
//ask the database for coincidences
$result = mysql_query("SELECT email FROM pressmails WHERE email='.$email.'");
$num_rows = mysql_num_rows($result);
if($num_rows < 0){
echo "The user is registered";
} else {
echo "The user is not registered";
}
//Close database connection
mysql_close();
?>
You are not concatenating string properly.
$result = mysql_query("SELECT email FROM pressmails WHERE email='.$email.'");
should be
$result = mysql_query("SELECT email FROM pressmails WHERE email='".$email."'");
You should end the string by using a closing quote (if you started the string with " you must end the string with " too, same for ').
And do not forget to use mysql_real_escape_string, otherwise the script is not safe.
The script will become something like this:
// save the query in a variable, so we can echo it to debug when it doesn't work as expected
$sql = "SELECT email FROM pressmails WHERE email='".mysql_real_escape_string($email)."'";
$result = mysql_query($sql);
You do not need the concatenation identifiers, since wrapping a literal in " will automatically parse variables into the string:
$result = mysql_query("SELECT email FROM pressmails WHERE email='$email'");
You should watch out, mind you. Doing the above represents a significant SQL injection vulnerability. You should consider sanitizing $email as a minimum. Also see my comment about the mysql_* functions in PHP.
From the Docs:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_close() PDO: Assign the value of NULL to the PDO object
(assuming you get your syntax errors corrected) isn't the logic of this backwards?
if($num_rows < 0){
echo "The user is registered";
} else {
echo "The user is not registered";
}
if the user is registered their email is in the database and the query returns one or more rows
try
if($num_rows){
echo "The user is registered";
} else {
echo "The user is not registered";
}

Categories