0

Got this error. Please can anyone help. I am a beginner at this.

Undefined variable: mysqli in C:\xampp\htdocs\final\register.php on line 20
Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\final\register.php:20 Stack trace: #0 {main}
thrown in C:\xampp\htdocs\final\register.php on line 20

What do we need to do in order to validate the html form with some validation and how can we put the submitted details into the database table ?

This is the code of

Register.php

<?php
 include "header.php";
// Include config file
require_once 'dbconfig.php';

// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

// Validate username
if(empty(trim($_POST["username"]))){
    $username_err = "Please enter a username.";
} else{
    // Prepare a select statement
    $sql = "SELECT id FROM signup WHERE username = ?";

    if($stmt = $mysqli->prepare($conn,$sql)){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("s", $param_username);

        // Set parameters
        $param_username = trim($_POST["username"]);

        // Attempt to execute the prepared statement
        if($stmt->execute()){
            // store result
            $stmt->store_result();

            if($stmt->num_rows == 1){
                $username_err = "This username is already taken.";
            } else{
                $username = trim($_POST["username"]);
            }
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }

    // Close statement
    $stmt->close();
}

// Validate password
if(empty(trim($_POST['password']))){
    $password_err = "Please enter a password.";     
} elseif(strlen(trim($_POST['password'])) < 6){
    $password_err = "Password must have atleast 6 characters.";
} else{
    $password = trim($_POST['password']);
}

// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
    $confirm_password_err = 'Please confirm password.';     
} else{
    $confirm_password = trim($_POST['confirm_password']);
    if($password != $confirm_password){
        $confirm_password_err = 'Password did not match.';
    }
}

// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){

    // Prepare an insert statement
    $sql = "INSERT INTO signup (username, password) VALUES (?, ?)";

    if($stmt = $mysqli->prepare($sql)){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("ss", $param_username, $param_password);

        // Set parameters
        $param_username = $username;
        $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash

        // Attempt to execute the prepared statement
        if($stmt->execute()){
            // Redirect to login page
            header("location: login.php");
        } else{
            echo "Something went wrong. Please try again later.";
        }
    }

    // Close statement
    $stmt->close();
}

// Close connection
$mysqli->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" 
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
    body{ font: 14px sans-serif; }
    .wrapper{ 
        width: 350px;
        padding: 20px;
       margin: 10px 10px 10px 10px; 
         }
</style>
</head>
<body>
<div class="jumbotron">
 <div class="wrapper">
    <h2>Sign Up</h2>
    <p>Please fill this form to create an account.</p>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
            <label>Username</label>
            <input type="text" name="username"class="form-control" value="<?php echo $username; ?>">
            <span class="help-block"><?php echo $username_err; ?></span>
        </div>    
        <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
            <label>Password</label>
            <input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
            <span class="help-block"><?php echo $password_err; ?></span>
        </div>
        <div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
            <label>Confirm Password</label>
            <input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
            <span class="help-block"><?php echo $confirm_password_err; ?></span>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Submit">
            <input type="reset" class="btn btn-default" value="Reset">
        </div>
        <p>Already have an account? <a href="login.php">Login here</a>.</p>
    </form>
</div>    
</div>

</body>
</html>


if($stmt = mysqli_prepare($conn, $sql)){}

This line shows error. What is binding and how to use it?

Login.php

<?php
include 'header.php';
// Include config file
require_once 'dbconfig.php';

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

// Check if username is empty
if(empty(trim($_POST["username"]))){
    $username_err = 'Please enter username.';
} else{
    $username = trim($_POST["username"]);
}

// Check if password is empty
if(empty(trim($_POST['password']))){
    $password_err = 'Please enter your password.';
} else{
    $password = trim($_POST['password']);
}

// Validate credentials
if(empty($username_err) && empty($password_err)){
    // Prepare a select statement
    $sql = "SELECT Username, Password FROM login WHERE Username = ?";

    if($stmt = mysqli_prepare($conn, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "a", $param_username);

        // Set parameters
        $param_username = $username;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            // Store result
            mysqli_stmt_store_result($stmt);

            // Check if username exists, if yes then verify password
            if(mysqli_stmt_num_rows($stmt) == 1){                    
                // Bind result variables
                mysqli_stmt_bind_result($stmt, $username, $hashed_password);
                if(mysqli_stmt_fetch($stmt)){
                    if(password_verify($password, $hashed_password)){
                        /* Password is correct, so start a new session and
                        save the username to the session */
                        session_start();
                        $_SESSION['username'] = $username;      
                        header("location: welcome.php");
                    } else{
                        // Display an error message if password is not valid
                        $password_err = 'The password you entered was not valid.';
                    }
                }
            } else{
                // Display an error message if username doesn't exist
                $username_err = 'No account found with that username.';
            }
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
    body{ font: 14px sans-serif; }
    .wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
    <h2>Login</h2>
    <p>Please fill in your credentials to login.</p>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
            <label>Username</label>
            <input type="text" name="username"class="form-control" value="<?php echo $username; ?>">
            <span class="help-block"><?php echo $username_err; ?></span>
        </div>    
        <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
            <label>Password</label>
            <input type="password" name="password" class="form-control">
            <span class="help-block"><?php echo $password_err; ?></span>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Login">
        </div>
        <p>Don't have an account? <a href="register.php">Sign up now</a>.</p>
    </form>
</div>    
</body>
</html>

register_val.php

<?php

require_once('dbconfig.php');

// function for email validation
function is_valid_email($email)
{
 if (empty($email)) {
     echo "Email is required.";
     return false;
 } else {
     $email = test_input($email);
     // check if e-mail address is well-formed
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       echo "Invalid email format."; 
       return false;
 } 
 // now check if the mail is already registered
 $slquery = "SELECT 2 FROM signup WHERE Email = '$email'";
 $selectresult = mysql_query($slquery);
 if(mysql_num_rows($selectresult)>0) {
   echo 'This email already exists.';
   return false;
 }
 // now returns the true- means you can proceed with this mail
 return true;
}

// function for password verification
function is_valid_passwords($password,$confirm_password) 
{
 // Your validation code.
 if (empty($password)) {
     echo "Password is required.";
     return false;
 } 
 else if ($password != $confirm_password) {
     // error matching passwords
     echo 'Your passwords do not match. Please type carefully.';
     return false;
 }
 // passwords match
 return true;
}

// function for creating user
function create_user($email, $password, $confirm_passwordpassword) 
{
  $query = "INSERT INTO `singup` (email, password, confirmpassword) VALUES ('$email', '$password', '$cpassword')";
  $result = mysql_query($query);
  if($result){
      return true; // Success
  }else{
      return false; // Error somewhere
  }
}

// Code execution starts here when submit
if (isset($_POST['email']) && isset($_POST['password'])){

// Reading form values
$email = $_POST['email'];
$password = $_POST['password'];
$confirm_password = $_POST['confirmpassword'];

if (is_valid_email($email) && is_valid_passwords($password,$confirm_password))
{
    if (create_user($email, $password, $cpassword)) {
          echo 'New User Registered Successfully.';
    }else{
      echo 'Error Registering User!';
    }
}
// You don't need to write another 'else' since this is the end of PHP code 
?>

dbconfig.php

<?php
$servername = "localhost";
$username = "root";
$password = "";

try {
$conn = new PDO("mysql:host=$servername; dbname = 'car sale' ", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Why are you using `mysql_` (which is either deprecated or removed depending on your PHP version) in some places and `mysqli_` in others, yet setting up your database connection with `new PDO`? Use either MySQLi or PDO, and stick to just the **one** API; you **cannot combine MySQL APIs**. – Obsidian Age Mar 27 '18 at 02:32
  • Possible duplicate of [Can I mix MySQL APIs in PHP?](https://stackoverflow.com/questions/17498216/can-i-mix-mysql-apis-in-php) – Obsidian Age Mar 27 '18 at 02:32
  • Do i need to change the dbconfig.php to connect via mysqli_ ? –  Mar 27 '18 at 02:37
  • If you opt for MySQLi over PDO, yes. You would need to replace the connection in `dbconfig.php`, and also change every single one of your `mysql_*` methods to use MySQLi as well. – Obsidian Age Mar 27 '18 at 02:39
  • Mysqli, is junk when compared to PDO, just saying. – ArtisticPhoenix Mar 27 '18 at 02:40

3 Answers3

0

Have you created object $mysqli?

$mysqli = new Mysqli("host","db user","db password","db name");

Put it on Register.php before you call $mysqli

0

Honestly this is a mess, you have

$conn = new PDO("mysql:host=$servername; dbname = 'car sale' ", $username, $password);

Then

 $mysqli->prepare($conn,$sql)

Then (deprecated and removed in PHP7+)

 $result = mysql_query($query);

And

$query = "INSERT INTO `singup` (email, password, confirmpassword) VALUES ('$email', '$password', '$cpassword')";

And

$slquery = "SELECT 2 FROM signup WHERE Email = '$email'";

SQLInjection issues. 3 different databases drivers. Um Start over?....

I would start by getting rid of all that DB junk, and use only one of them (Preferably PDO. :-) ).

Hey it does look like you go the login done fairly well, not querying the password, using a secure hash compare function. Checking for 1 and only one result. That's all good. The rest ... not so much.

It needs a lot of cleanup done, this is all simple stuff, but it's beyond the scope of one question.

Once you clean up the DB stuff you may find that this error evaporates... Because you are confused as to how you are connecting to the DB.

To be frank, it looks like a lot of Copy and pasted code. There is nothing wrong with that, but you have to understand what the code does on some level. Code is like handwriting, you can tell how well someone knows the language by how they write the code. I see maybe 4 different levels of coders at work here.

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • Can u please edit the line of code? Couldn't understand. I need to show it within an hour. –  Mar 27 '18 at 03:24
0

mysqli and PDO are different. Please refer https://www.w3schools.com/php/php_mysql_connect.asp

Your dbconfig.php will look like

<?
$host="127.0.0.1";
$port=3306;
$socket="";
$user="user";
$password="password";
$dbname="dbname";

$mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket)
    or die ('Could not connect to the database server' . mysqli_connect_error());
if($mysqli!=null){
    //echo "Mysql connected. Yeah!<br/>";
$mysqli->close();
}
?>
Shusen Yi
  • 779
  • 7
  • 6