mexabet 49 Good Learner

I've resolved the issue.

mexabet 49 Good Learner

I have a two-step login form. In the first step, I have "username" as "id" and "name" of the text input. I also have "password" as id and "name" of the second input field, where the user is prompted to enter username and password.

In the second step, I have "confirmusername" as "id" and "name" of the text input. I also have "confirmpassword" as "id" and "name" of the text input.

I want the the value of the "username" entered in the first step to become the value of "confirmusername".

Your help would be much appreciated. Thanks in advance.

The following is my code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
form#multiphase{ border:#000 1px solid; padding:24px; width:350px; }
form#multiphase > #show_all_data{ display:none; }
</style>
<script>
var username, password, confirmusername, confirmpassword;
function _(x){
    return document.getElementById(x);
}
function processPhase1(){
    username = _("username").value;
    password = _("password").value;
    if(username.length > 2){
        _("display_username").innerHTML = username;
        _("display_password").innerHTML = password;
        _("phase1").style.display = "none";
        _("show_all_data").style.display = "block";
    }
}
function submitForm(){        
    confirmusername = _("confirmusername").value;
    confirmpassword = _("confirmpassword").value;
    if(confirmpassword.length > 0){
        _("multiphase").method = "post";
        _("multiphase").action = "";
        _("multiphase").submit();
    }
}
</script>
</head>
<body>

<form id="multiphase" onsubmit="return false">
  <div id="phase1">
    Username: <input id="username" name="username"><br>
    Password: <input id="password" name="password"> <br>
    <button  id="next" onclick="processPhase1()">Next</button>
  </div>
  <div id="show_all_data">
    Username: <span id="display_username"></span> <br>
    Password: <span id="display_password"></span> <br>
    Confirm Username: <input id="confirmusername" name="confirmusername" value=""><br>
    Confirm Password: <input id="confirmpassword" name="confirmpassword"> <br>
    <button onclick="send()">Send</button>
  </div>
</form>


<script>
var input = document.getElementById("username");
var input = document.getElementById("password");
input.addEventListener("keypress", function(event) {
  if (event.key === "Enter") {
    event.preventDefault();
    document.getElementById("next").click();
  }
});
</script> …
mexabet 49 Good Learner

@Dani, thanks for your time and input. I'm creating a course registration form, whereby a registered user can select a course and register for it. I want to extract the course registrant's user_id, firstname, lastname, username,email from the users table and load them in the form fields via a foreach loop.

How do I include include items from the users table in that foreach loop? That's the challenge I'm having.

I want the logged in user's information to be printed in the same course registration form, where courses information is being printed like this $row["user_id"], $row["firstname"],$row["lastname"],$row["username"],$row["email"]`.

By doing so, when the user submits the form, both the registered course's details, as well as the particular user's details would be inserted into the third database table, course_registration.

mexabet 49 Good Learner

I have two MySQL tables, which I want to SELECT using a single PDO query and positional placeholders.

I've been going through similar questions here to find a solution, but none seems to match the issues I'm having.

The following code is the section of my script:

<?php
// query users table to retrieve its contents   
if (isset($_SESSION["user_id"]["0"]))
{               
    // select a particular user by user_id
    $user_id = isset($_POST["user_id"]) ? $_POST["user_id"] : '';

    $stmt = $pdo->prepare("SELECT * FROM users WHERE user_id=?",$_SESSION["user_id"]["0"]);
    $stmt->execute([$user_id]); 
    $user = $stmt->fetch(); # get user data

}

    // query courses table to retrieve its contents            
        $cid = $_POST["cid"] ?? NULL;
        if (is_null($cid))
    {
           $stmt = $pdo->query("SELECT * FROM courses");
        }
        else
    {
           $stmt = $pdo->prepare("SELECT * FROM courses WHERE cid = ?");
           $stmt->execute([$cid]);
    }

        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo '<option value="">'. "Select a course to proceed" .'</option>';

        foreach ($results as $row) {
        echo '<option value=" '. $row["cid"] .' ">'. $row["c_name"] .'</option>';                
    }

Apart from echoing $row["cid"] (course ID) and $row["c_name"] (course name) from the courses table, I also want to echo the following from the same courses table: $row["code"], $row["duration"], $row["start"]

In the users table, I have the logged in user's "user_id", "firstname", "lastname", "username", "email", which I also want to echo in the above foreach loop. That means the user must be logged in.

Thank you in advance for your time and help.

mexabet 49 Good Learner

@Dani, thanks for your time and input.

I can't seem to figure out what's causing the isssue. That's why I need help.

mexabet 49 Good Learner

@rproffitt,
During my quick research, I saw a recommendation of PBKDF2 and HMAC-SHA-256, but no programmatic example I can easily understand. Please, do you have an example code for that?

Coming back to my original post regarding redirection, can you please, take a look at my "config.php" file and help me to understand why the redirection is going into endless loops, until terminated by browser:

    // require authentication for most pages
    if (!preg_match("{(admin/login|logout|register)\.php$}", $_SERVER["PHP_SELF"]))
    {
       if (empty($_SESSION["aid"]))
        {
           header("Location: login.php");
        }
    }
    elseif (!preg_match("{(?:index|login|logout|register)\.php$}", $_SERVER["PHP_SELF"]))
    {
        if (empty($_SESSION["user_id"]))
        {
           header("Location: login.php");
        }
    }
rproffitt commented: There are numerous examples out there. Some what instant gratification, this takes more study. +15
mexabet 49 Good Learner

@rproffitt,
I've modified line 177 you pointed out to the following:

// insert form input into database          
$stmt=$pdo->prepare("INSERT INTO users (firstname, lastname, username, gender, password, email, birthday, phone, regdate, userimage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)");
$stmt->execute([$firstname, $lastname, $username, $gender, $new_password, $email, $birthday, $phone, $imagename]);
mexabet 49 Good Learner

I'm trying to redirect user to "userinfo.php" after successful registration, but the browser terminates the redirection because it goes into endless loops.

Moreover, I need your insight on if the script is secure or not.

I need your help, please. Thanks.

The following is the "register.php" script:

<?php

    // include configuration file
    require ("includes/config.php");

    //Class import for image uploading
    //classes is the map where the class file is stored (one above the root)
    include ("classes/upload/upload_class.php");

       // define variables and set to empty values
       $firstnameErr = $lastnameErr = $usernameErr = $genderErr = $passwordErr = $confirmationErr = $emailErr = $birthdayErr = $phoneErr = "";
      $firstname = $lastname = $username = $gender = $password = $confirmation = $email = $birthday = $phone = "";

    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {       
        $firstname = student_input($_POST["firstname"]);
        $lastname = student_input($_POST["lastname"]);
        $username = student_input($_POST["username"]);
        $gender = student_input($_POST["gender"]);
        $password = student_input($_POST["password"]);
        $confirmation = student_input($_POST["confirmation"]);
        $email = student_input($_POST["email"]);
        $birthday = student_input($_POST["birthday"]);
        $phone = student_input($_POST["phone"]);

            //This is the directory where images will be saved 
            $max_size = 160*170; // the max. size for uploading

            $my_upload = new file_upload;

            $my_upload->upload_dir = "images/user/"; // "files" is the folder for the uploaded files (you have to create this folder)
            $my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here
            // $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
            $my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
            $my_upload->rename_file = false;

            $my_upload->the_temp_file = $_FILES['userimage']['tmp_name']; …
mexabet 49 Good Learner

@rproffitt,
Thanks for your continued interest and input. Well, I don't expect you to write the code for me, but I desperately need someone to closely look at my code and explain to me why the queries don't execute.

Below is a rewrite of register.php, whic now displays errors if certain, predefined conditions are not met. However, it doesn't display any error, when the insert or select query fail.

<?php

    // include configuration file
    require ("includes/config.php");

    //Class import for image uploading
    //classes is the map where the class file is stored (one above the root)
    include ("classes/upload/upload_class.php");

       // define variables and set to empty values
       $firstnameErr = $lastnameErr = $usernameErr = $genderErr = $passwordErr = $confirmationErr = $emailErr = $birthdayErr = $phoneErr = "";
      $firstname = $lastname = $username = $gender = $password = $confirmation = $email = $birthday = $phone = "";

    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {

        $firstname = student_input($_POST["firstname"]);
        $lastname = student_input($_POST["lastname"]);
        $username = student_input($_POST["username"]);
        $gender = student_input($_POST["gender"]);
        $password = student_input($_POST["password"]);
        $confirmation = student_input($_POST["confirmation"]);
        $email = student_input($_POST["email"]);
        $birthday = student_input($_POST["birthday"]);
        $phone = student_input($_POST["phone"]);

        // validate submission
        if (empty($_POST["firstname"]))
        {
            $firstnameErr = "First name is required.";
        }
        else
        {
               $firstname = student_input($_POST["firstname"]);
        }
        if(empty($_POST["lastname"]))
        {
            $lastnameErr = "Last name is required.";
        }
        else
        {
               $lastname = student_input($_POST["lastname"]);
        }
        if(empty($_POST["username"]))
        {
            $usernameErr = "Username is required.";
        }
        else if(!empty($_POST["username"]))
        { 
            // validate username
            if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
            {
                $usernameErr = "Username must contain only letters and numbers.";
            }
            if (strlen($username) < 4 || strlen($username) > 10) …
mexabet 49 Good Learner

@rproffit,
I just modified insert query in the register.php file, but still the queries don't execute.

Is the modified approach the best secure way of storing password?

<?php

    // include configuration file
    require ("includes/config.php");

    //Class import for image uploading
    //classes is the map where the class file is stored (one above the root)
    include ("classes/upload/upload_class.php");

    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {

        $firstname = student_input($_POST["firstname"]);
        $lastname = student_input($_POST["lastname"]);
        $username = student_input($_POST["username"]);
        $gender = student_input($_POST["gender"]);
        $password = student_input($_POST["password"]);
        $email = student_input($_POST["email"]);
        $birthday = student_input($_POST["birthday"]);
        $phone = student_input($_POST["phone"]);

        // validate submission
        if (empty($_POST["firstname"]))
        {
            $errorMsg[] = "First name is required.";
        }
        else if(empty($_POST["lastname"]))
        {
            $errorMsg[] = "Last name is required.";
        }
        else if(empty($_POST["username"]))
        {
            $errorMsg[] = "Username is required.";
        }
        else if(!empty($_POST["username"]))
        { 
            // validate username
            if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
            {
                $errorMsg[] = "Username must contain only letters and numbers.";
            }
            if (strlen($username) < 4 || strlen($username) > 10)
            {
                $errorMsg[] = "Username must be from 4 to 10 characters.";
            }
        }
        else if(empty($_POST["gender"]))
        {
            $errorMsg[] = "Gender is required.";
        }
        else if(empty($_POST["password"]))
        {
            $errorMsg[] = "Enter a password.";
        }
        else if(!empty($_POST["password"]))
        { 
            // validate username
            if (!preg_match("/^[a-zA-Z0-9]*$/", $password))
            {
                $errorMsg[] = "Password must contain letters, numbers and special characters.";
            }
            if (strlen($password) < 8 || strlen($password) > 15)
            {
                $errorMsg[] = "Password must be from 8 to 15 characters.";
            }
        }
        else if (empty($_POST["confirmation"]))
        {
            $errorMsg[] = "Confirm your password.";
        }
        else if ($_POST["password"] != $_POST["confirmation"])
        {
            $errorMsg[] = "Password and confirmation don't match.";
        }
        else if(empty($_POST["email"]))
        {
            $errorMsg[] …
mexabet 49 Good Learner

I'm struggling to build a PHP registration script using PDO prepared statements with positional placeholders. But the MySQL queries don't execute.
var_dump(); doesn't display any error.

Please, I need your help to fix this. Your time and input are much appreciated in advance. Thanks.

register.php:

<?php

    // include configuration file
    require ("includes/config.php");

    //Class import for image uploading
    //classes is the map where the class file is stored (one above the root)
    include ("classes/upload/upload_class.php");

    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {

        $firstname = student_input($_POST["firstname"]);
        $lastname = student_input($_POST["lastname"]);
        $username = student_input($_POST["username"]);
        $gender = student_input($_POST["gender"]);
        $password = student_input($_POST["password"]);
        $email = student_input($_POST["email"]);
        $birthday = student_input($_POST["birthday"]);
        $phone = student_input($_POST["phone"]);

        // validate submission
        if (empty($_POST["firstname"]))
        {
            $errorMsg[] = "First name is required.";
        }
        else if(empty($_POST["lastname"]))
        {
            $errorMsg[] = "Last name is required.";
        }
        else if(empty($_POST["username"]))
        {
            $errorMsg[] = "Username is required.";
        }
        else if(!empty($_POST["username"]))
        { 
            // validate username
            if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
            {
                $errorMsg[] = "Username must contain only letters and numbers.";
            }
            if (strlen($username) < 4 || strlen($username) > 10)
            {
                $errorMsg[] = "Username must be from 4 to 10 characters.";
            }
        }
        else if(empty($_POST["gender"]))
        {
            $errorMsg[] = "Gender is required.";
        }
        else if(empty($_POST["password"]))
        {
            $errorMsg[] = "Enter a password.";
        }
        else if(!empty($_POST["password"]))
        { 
            // validate username
            if (!preg_match("/^[a-zA-Z0-9]*$/", $password))
            {
                $errorMsg[] = "Password must contain letters, numbers and special characters.";
            }
            if (strlen($password) < 8 || strlen($password) > 15)
            {
                $errorMsg[] = "Password must be from 8 to 15 characters.";
            }
        }
        else if (empty($_POST["confirmation"]))
        {
            $errorMsg[] = "Confirm your password.";
        } …
mexabet 49 Good Learner

@AndreRet,
Thanks for your input.

There's already session_start() call in the config.php file:

<?php

    // display errors, warnings, and notices
    ini_set("display_errors", true);
    error_reporting(E_ALL);

    // requirements
    require("constants.php");
    require("functions.php");

    // enable sessions
    session_start();

    // require authentication for most pages
    if (!preg_match("{(admin/login|logout|register)\.php$}", $_SERVER["PHP_SELF"]))
    {
       if (empty($_SESSION["aid"]))
        {
           header("Location: login.php");
        }
    }
    }

?>

With the code in the config.php, is it proper to have the following in another file, add-course.php?

    // query users table to retrieve current admin's profile
    if(isset($_POST['aid'])) {

    // select a particular admin by id
    $stmt = $pdo->prepare("SELECT * FROM admin WHERE aid=?", $_SESSION["aid"]);
    $stmt->execute([$aid]); 
    $admin = $stmt->fetch(); # get admin data
AndreRet commented: You MUST HAVE session_start at the top of teh page i.e first line of code is session_start then other code follows. Then to your question, if you are +14
mexabet 49 Good Learner

I'm struggling to add a course to a MySQL database table using PDO prepared query with positional placeholders. When the form is submitted, the database table is not updated, as expected and no error is displayed.

Please, where exactly do I place var_dump() to display the error? And how can I get it to work?

Another thing; I would appreciate pointing out security flaws in the code.

Thanks in advance.

add-course.php:

 <?php   // configuration
require("../includes/config.php");

// query users table to retrieve current admin's profile
if(isset($_GET['aid'])) {

// select a particular admin by id
$stmt = $pdo->prepare("SELECT * FROM admin WHERE aid=?", $_SESSION["aid"]);
$stmt->execute([$aid]); 
$admin = $stmt->fetch(); # get admin data

//Class import for image uploading
//classes is the map where the class file is stored (one above the root)
include ("../classes/upload/upload_class.php");

// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{         
    //This gets all the other information from the form
    $coursename = htmlspecialchars($_POST["c_name"]);
    $course_title = htmlspecialchars($_POST["c_title"]);
    $meta_keywords = htmlspecialchars($_POST["meta_keywords"]);
    $meta_description = htmlspecialchars($_POST["meta_description"]);
    $short_desc = htmlspecialchars($_POST["short_desc"]);
    $coursedesc = htmlspecialchars($_POST["desc"]);
    //$course_image = ($_FILES["image"]["name"]);
    $courseduration = htmlspecialchars($_POST["duration"]);
    $coursecode = htmlspecialchars($_POST["code"]);
    $fees = htmlspecialchars($_POST["fees"]);
    $course_image = htmlspecialchars($row['image']);

    // validate submission
    if (empty(htmlspecialchars($_POST["c_name"])))
    {
        echo "Provide the course name.";
    }
    if (empty(htmlspecialchars($_POST["duration"])))
    {
         echo "Provide the course duration.";
    }
    if (empty(htmlspecialchars($_POST["code"])))
    {
         echo "Provide the course code.";
    }

    //This is the directory where images will be saved 
    $max_size = 1024*250; // the max. size for uploading

    $my_upload = new file_upload;

    $my_upload->upload_dir = "../images/courses/"; // "files" is the folder for the uploaded files (you have …
mexabet 49 Good Learner

@AndreRet , Thanks, I've managed to fix the issue.

AndreRet commented: Awesome, please share your answer with us if possible and mark this as solved, thanks. +14
mexabet 49 Good Learner

I'm struggling to create a two-paged form using $_SESSION. What I want to achieve is the first page (page1.php) requires the user to enter his/her email address. And the second page (page2.php) requires the user to enter his/her password.

When the user submits page1.php, it takes you to page2.php, where the email address submitted will be printed. But unfortunately, the email address is not printed, as intended.

Please, note I've tried to adopt related resolved threads, but I'm still missing something.

The following is my code:
page1.php

<?php
session_start();
?>
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<!doctype html>
<html><head>
<meta charset="utf-8">
<title>2 Step Login - Page 1</title>
<link href="page1.css" rel="stylesheet">
</head>

<body>

<div id="formwrap">
<div id="form_inner">
    <div id="logo">
      <img src="" alt="logo">
    </div>
    <div id="email">

    </div>
  <div id="pwd">
      Sign in
  </div>
  <div id="form">
    <form action="page2.php" method="post" enctype="multipart/form-data" name="form">

<?php

    //On page 1
    $_SESSION['username'] = $var_value;
?>
      <input id="username" name="username" type="text" placeholder="Email" autofocus required>

    <div id="forgot">No Yet A Member, Register Here</a></div>
    <input type="hidden" name="username" value="var_value">
    <input id="send" name="submit" type="submit" value="Next">
    </form>
  </div>
  </div>
</div>
</body>
</html>

page2.php

<?php
session_start();
?>
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>2 Step Login - Page 2</title>
<link href="page2.css" rel="stylesheet">
</head>

<body>

<div id="formwrap">
<div id="form_inner">
    <div id="logo">
      <img src="" alt="logo">
    </div>
    <div id="email">
<?php
    //On age 2
    $var_value = $_SESSION['username'];
    echo $_SESSION['username'];
?>
    </div>
  <div id="pwd">
      Enter password
  </div>
  <div id="form">
    <form action="login.php" method="post" enctype="multipart/form-data" name="form">
      <input id="password" name="password" type="password" placeholder="Password" autofocus>
      <div id="chkbx">
<div id="inptch">
  <input id="keep_signed_in" name="keep_signed_in" type="checkbox" …
mexabet 49 Good Learner

Thanks for your insight. No error message is displayed. I opened php.ini to ascertain that error_reporting is set to E_ALL, set display_errors to ON, and output_buffering is set to OFF, and those are the settings I found there. I've checked the database table row manuanally and the update didn't take place.

Sorry, I don't understand what you meant by saying:

They log the SQL submission string for the change then try it by hand if they don't see a syntax error.
mexabet 49 Good Learner

I have a script that populates a form from MySQL database table row for editing. I'm performing MySQL SELECT and UPDATE via PDO. After editing a particular table row and clicking on the submit button, the table row doesn't update.

The following is "modify-course.php":

<?php

    // configuration
    require("../includes/config.php");

    // query admin table to retrieve current admin's profile    
    //select a particular admin by id

    // query users table to retrieve current admin's profile
    if (array_key_exists('aid', $_GET)) {

    // select a particular admin by id
    $stmt = $pdo->prepare("SELECT * FROM admin WHERE aid=?");
    $stmt->execute([$_GET["aid"]]); 
    $admin = $stmt->fetch(); # get admin data

    if (!$admin)
    {
       header("Location: login.php");
    }

    // query users table to retrieve admin homepage's contents
    // $users = query("SELECT * FROM users WHERE id = ?");

    //Class import for image uploading
    //classes is the map where the class file is stored (one above the root)
    include ("../classes/upload/upload_class.php");         

    //select a particular course by id
    if (array_key_exists('cid', $_GET)) {

    // select a particular course by id
    $stmt = $pdo->prepare("SELECT * FROM courses WHERE cid=?");
    $stmt->execute([$_GET["cid"]]); 
    $course = $stmt->fetch(); # get course data

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {

        // validate submission
        if (empty($_POST["c_name"]))
        {
             echo "Provide the course name.";
        }
        if (empty($_POST["duration"]))
        {
            echo "Provide the course duration.";
        }
        if (empty($_POST["code"]))
        {
            echo "Provide the course code.";
        }
        if (empty($_POST["fees"]))
        {
            echo "Enter total fees for the course.";
        }

            // validate course name         
            if(isset($_POST['c_name'])){
                $name = ($_POST["c_name"]);

            if (!preg_match("/^[a-zA-Z0-9]*$/", $name))
            {
                echo "A course name must contain only letters and/or numbers.";
            }
            if (strlen($_POST["c_name"]) …
mexabet 49 Good Learner

I'm doing both SELECT and UPDATE queries using named placeholders. But course data from the database doesn't populate form, as expected. The database table row records don't populate, each time I try to edit a course in the browser. I connect to the database usining PDO. And I do SELECT and UPDATE queries using named placeholders. The following is my "modify-course.php":

 <?php

    // configuration
    require("../includes/config.php");       

    //select a particular admin by id
    $admin_id = isset($_GET["admin_id"]) ? $_GET["admin_id"] : ''; 

    $stmt = $pdo->prepare("SELECT * FROM admin WHERE admin_id=:admin_id");
    $stmt->execute(['admin_id' => $admin_id]); 
    $admin = $stmt->fetch(); # get admin data

    if (!$admin)
    {
        header("Location: login.php");
    }

    //Class import for image uploading
    //classes is the map where the class file is stored (one above the root)
    include ("../classes/upload/upload_class.php");         

    //select a particular course by id
    $course_id = isset($_GET["course_id"]) ? $_GET["course_id"] : ''; 

    $stmt = $pdo->prepare("SELECT * FROM courses WHERE course_id=:course_id");
    $stmt->execute(['course_id' => $course_id]); 
    $course = $stmt->fetch(); # get course data

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {

        // validate submission
        if (empty($_POST["coursename"]))
        {
             echo "Provide the course name.";
        }
        if (empty($_POST["courseduration"]))
        {
            echo "Provide the course duration.";
        }
        if (empty($_POST["coursecode"]))
        {
            echo "Provide the course code.";
        }
        if (empty($_POST["fees"]))
        {
            echo "Enter total fees for the course.";
        }

            // validate coursename
            //$coursename = ($_POST["coursename"]);
            //if (!preg_match("/^[a-zA-Z0-9]*$/", $coursename))
           // {
             //   echo "A course name must contain only letters and numbers.";
           // }
            if (strlen($_POST["coursename"]) < 20 || strlen($_POST["coursename"]) > 50)
            {
                echo "A course name must be from 20 to 50 characters.";
            }
            // validate course duration …
mexabet 49 Good Learner

@alan.davies,
Thanks for your time and insight.

Yes, "query()" is a custom function located in "functions.php". That's my attempt on using PDO for database connection and queries with prepared statements.

<?php

    /**
     * functions.php
     *
     * FlamyTech Computer School
     *
     * Helper functions.
     */

    require_once("constants.php");

    /**
     * Apologizes to user with message.
     */
    function apologize($message)
    {
        render("apology.php", ["message" => $message]);
        exit;
    }

    /**
     * Apologizes to admin with message.
     */
    function adminapologize($message)
    {
        adminrender("apology.php", ["message" => $message]);
        exit;
    }

    /**
     * Facilitates debugging by dumping contents of variable
     * to browser.
     */
    function dump($variable)
    {
        require("../templates/dump.php");
        exit;
    }

    /**
     * Logs out current user, if any.  Based on Example #1 at
     * http://us.php.net/manual/en/function.session-destroy.php.
     */
    function logout()
    {
        // unset any session variables
        $_SESSION = [];

        // expire cookie
        if (!empty($_COOKIE[session_name()]))
        {
            setcookie(session_name(), "", time() - 42000);
        }

        // destroy session
        session_destroy();
    }

    /**
     * Executes SQL statement, possibly with parameters, returning
     * an array of all rows in result set or false on (non-fatal) error.
     */
    function query(/* $sql [, ... ] */)
    {
        // SQL statement
        $sql = func_get_arg(0);

        // parameters, if any
        $parameters = array_slice(func_get_args(), 1);

        // try to connect to database
        static $handle;
        if (!isset($handle))
        {
            try
            {
                // connect to database
                $handle = new PDO("mysql:dbname=" . DB_NAME . ";host=" . DB_SERVER, DB_USERNAME, DB_PASSWORD);

                // ensure that PDO::prepare returns false when passed invalid SQL
                $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
            }
            catch (Exception $e)
            {
                // trigger (big, orange) error
                trigger_error($e->getMessage(), E_USER_ERROR);
                exit;
            }
        }

        // prepare SQL statement
        $statement …
mexabet 49 Good Learner

I'm trying to upgrade my script from PHP 5.5 to PHP 7.2. And that came with the script not able to modify a selected table row as before. The records don't even populate whenever I try to edit a course in the browser. Please, note that I'm connecting to the database via PDO.

The following is my script:

 <?php

    // configuration
    require("../includes/config.php");

    // query admin table to retrieve current admin's profile
    $admin = query("SELECT * FROM admin WHERE admin_id = ?", $_SESSION["admin_id"]);

    if (!$admin)
    {
        redirect("login.php");
    }

    // query users table to retrieve admin homepage's contents
    // $users = query("SELECT * FROM users WHERE id = ?");

    //Class import for image uploading
    //classes is the map where the class file is stored (one above the root)
    include ("../classes/upload/upload_class.php");         

    $course_id = isset($_POST["course_id"]) ? $_POST["course_id"] : ''; 

    //$course_id = $_GET["course_id"];
    $courses = query("SELECT * FROM courses WHERE course_id = '$course_id'");

    // if form was submitted, modify user
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {

        // validate submission
        if (empty($_POST["coursename"]))
        {
            adminapologize("Provide the course name.");
        }
        if (empty($_POST["courseduration"]))
        {
            adminapologize("Provide the course duration.");
        }
        if (empty($_POST["coursecode"]))
        {
            adminapologize("Provide the course code.");
        }
        if (empty($_POST["fees"]))
        {
            adminapologize("Enter total fees for the course.");
        }

        //This is the directory where images will be saved 
        $max_size = 1024*250; // the max. size for uploading

        $my_upload = new file_upload;

        $my_upload->upload_dir = "../images/courses/"; // "files" is the folder for the uploaded files (you have to create this folder)
        $my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here …
mexabet 49 Good Learner

@broj1, thanks for your input and insight. I've already renamed the table colunm names to user_id, course_id and courseware_id. I've also made the users table to only hold unique/one-time user information and no longer hold any registration/course information. In effect, I created another table for course registration.

mexabet 49 Good Learner

@rproffitt,
Thanks for your input.

I was able to resolve the issue by deleting some data inserted into the DB tables.

mexabet 49 Good Learner

I got a syntax error flag in my "users" database table, but can't figure the issue out. Please, I need your help.

The following is the error message:

Error
SQL query:

--------------------------------------------------------- --
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS  `users` (

 `user_id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
 `username` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL ,
 `firstname` VARCHAR( 32 ) COLLATE utf8_unicode_ci NOT NULL ,
 `lastname` VARCHAR( 32 ) COLLATE utf8_unicode_ci NOT NULL ,
 `email` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL ,
 `phone` VARCHAR( 30 ) COLLATE utf8_unicode_ci NOT NULL ,
 `birthday` DATE NOT NULL ,
 `hash` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL ,
 `usersex` VARCHAR( 10 ) COLLATE utf8_unicode_ci NOT NULL ,
 `userimage` VARCHAR( 64 ) COLLATE utf8_unicode_ci NOT NULL ,
PRIMARY KEY (  `user_id` ) ,
UNIQUE KEY  `username` (  `username` ,  `email` ,  `userimage` ,  `phone` )
) ENGINE = INNODB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci AUTO_INCREMENT =4;

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-----------------------------------------------------------

--
-- Table structu' at line 1

And this is my "users" table:

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `firstname` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `lastname` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(30) COLLATE utf8_unicode_ci …
mexabet 49 Good Learner

I'm trying to create an online learning courseware and connecting to MySQL database via PDO. What I'm trying to achieve is: if a user is logged in after registering for a particular course, the courseware should display the registered course, as well as its course weeks. I want each course added by the admin to have weeks of learning. For example, the course "Digital Marketing" will have “Week 0”, "Week 1", "Week 2", "Week 3", etc in the courseware, depending of the number of weeks the admin has added to that very course. But what I've done so far causes id mix-up that is making the course weeks to be improperly displayed.
The following is what I've done: I created a MySQL table for students and named it "users" and another for courses and named it "courses". Moreover, I created another table called "courseware", so that whenever a student registers for a course, the student would gain a restricted access to that particular course alone. The following are the MySQL tables:
The "users" table:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `firstname` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `lastname` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `birthday` date NOT NULL,
  `hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `usersex` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `userimage` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `reg_course` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `regdate` timestamp NOT …
mexabet 49 Good Learner

It would have been better for you to post your code, so we can see where the error is coming from. Show some effort.

That said, let's assume that I have a MySQL table named "users" and I want to be able to delete any user I choose. I achieve that by creating a delete-user.php file like the following:

<?php

    $id = $_REQUEST["id"];
    $users = query("DELETE FROM users WHERE id = '$id'");

?>

Then, I have another file named list-users.php where I list all the users, with the following code:

  <?php

      // query users' table to retrieve users' contents
      $users = query("SELECT * FROM users");
      foreach ($users as $row)
      {
      printf("<table>");
      printf("<tr>");
      printf("<td>" . $row["id"] . "</td>");
      printf("<td>" . $row["username"] . "</td>");
      printf("<td>" . $row["firstname"] . "</td>");
      printf("<td>" . $row["lastname"] . "</td>");
      printf("<td>" . $row["usersex"] . "</td>");
      printf("<td><a href='delete-user.php?id=%d'>Delete</a></td>", $row['id']);
      printf("</tr>");
      }
      printf("</table>");
  ?>

Be advised that I used a custom function, "query". So, replace it with your own DB query function.

mexabet 49 Good Learner

I just thought I should make more clarifications, to see if I would get the much needed help.

I noticed that id mix-up might be causing the issue, but I'm confused.

If a student named Ben has an id "1" in the "users" DB table and registered for "Digital Branding" course, which has an id "1" in the "courses" DB table, the student can only access the first week named "Week 1" in the courseware. Interestingly, the URL bears "id=1" like this http://script/courseware/week.php?id=1.

No other week added by the admin for the same course can be accessed, as the script is currently.

Even when another student named Ken with an id "2" who registered for a different course (Social Media Marketing) logs in, the courseware still displays the "Week 1" content for "Digital Branding" course. But, the URL bears id=2 like this http://script/courseware/week.php?id=2 Coincidentally, Ken has an id "2" in the users table and the course (Social Media Marketing) he registered for has an id "2" as well.

The "users", "courses" and "courseware" tables all have columns named "id". So, which "id" exactly appears in the URL? Any idea how to fix the issue?

Thanks in advance for your time and help.

mexabet 49 Good Learner

You can simply use HTML bookmarking to redirect visitors to a certain location on a web page. You first need to create an id bookmark like this:

<a id="faqs">Read our FAQs</a>

And then, create a link pointing to the bookmark like this:

<a href="#faqs">FAQs</a>
mexabet 49 Good Learner

If you want members to successfully assist you, you have to post your code. Otherwise, it would be pure guessing and time-consuming.

I can only guess that you did was use a code like $row[0]["id"]; to attempt to access each user. If that is your case, try using $row["id"];

Below is an example usage:

printf("<td><a href='../profile.php?id=%d'>Michael</a></td>", $row['id']);
mexabet 49 Good Learner

@benanamen, Thanks for stopping by and for pointing out the end of life issue.

I'm aware of the discontinuation of PHP 5.5. Actually I started developing this script in 2014 and then abandoned it halfway. So, as I resumed work on it, I decided to upgrade everything to PHP 7 or 7.2, when I get a fully working script. That would be easier for me to upgrade then.

Do you have any idea how I can get the courseware to display weeks like week 1, week 2, week 3, etc, for each of the user's registered course.

mexabet 49 Good Learner

I'm assuming that you simply want to display the details of all the users of your own script.

Lets assume you have a table named "users" that have "id", "userimage", "username", "firstname", "lastname" and "usersex" columns. You can use the "foreach" loop to display the details of each user like this:

  <?php

      // query users' table to retrieve all the users' contents
      $users = query("SELECT * FROM users");
      foreach ($users as $row)
      {
      printf("<tr>");
      printf("<td>" . $row["id"] . "</td>");        
      printf("<td><img src='../images/user/" . $row['userimage']."' width='100' height='159'/></td>");
      printf("<td>" . $row["username"] . "</td>");
      printf("<td>" . $row["firstname"] . "</td>");
      printf("<td>" . $row["lastname"] . "</td>");
      printf("<td>" . $row["usersex"] . "</td>");

  ?>
mexabet 49 Good Learner

I'm creating an online learning courseware using PHP 5.5 and connecting via PDO. But I'm confused as to how to get the courseware to work, as I want. This is what I've done: I created a table for students and named it "users" and another for courses and named it "courses". Moreover, I created another table called "courseware", so that whenever a student registers for a course, the student would gain a restricted access to that particular course alone. The following are the MySQL tables:

The "users" table:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `firstname` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `lastname` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `birthday` date NOT NULL,
  `hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `usersex` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `userimage` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `reg_course` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `regdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `courseduration` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `fees` decimal(65,4) unsigned NOT NULL,
  `advance` decimal(65,4) unsigned NOT NULL,
  `balance` decimal(65,4) unsigned NOT NULL,
  `status` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `start` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`,`email`,`userimage`,`phone`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;

The "courses" table:

CREATE TABLE IF NOT EXISTS `courses` (
  `id` int(10) unsigned NOT NULL,
  `coursename` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `course_title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `meta_keywords` text COLLATE utf8_unicode_ci NOT NULL,
  `meta_description` text COLLATE utf8_unicode_ci NOT NULL,
  `short_desc` …
mexabet 49 Good Learner

Thanks, I'll try it and see if I can integrate it successfully into my script.

mexabet 49 Good Learner

The directory, category, exists in script-directory/products/images/category.

mexabet 49 Good Learner

Line 385 has this code:

imagejpeg($dest,$destFile, $quality);
mexabet 49 Good Learner

I still don't get it. can you please tell me the exact file to edit and which line and a replacement code. Thanks in advance.

mexabet 49 Good Learner

@diafol, thanks for your contribution.

Which file do you suggest I edit and which line? add-category.php or functions.php or config.php? Sorry, I'm just a learner.

mexabet 49 Good Learner

@cereal, Thanks for the insight.

I updated the select query on add-category.php to this:

$query = "INSERT INTO admin (username, hash, email, phone) VALUES (:username, :hash, :email, :phone)";
$params = array(':username' => $username, 'hash' => $hash, ':email' => $email, ':phone' => $phone);

$result = query($query, $params);
$affected_rows = $result->rowCount();

Now all the data are inserted into the database, but the image upload and move to upload directory still fails. Any idea?

mexabet 49 Good Learner

The mysql query I originally had on add-category.php was this:

$query = "INSERT INTO prod_cat (cat_name, cat_metatitle, cat_metakeywords, cat_metadescription, cat_description, cat_image, cat_date) 
        VALUES ('$categoryName', '$categoryMtitle', '$categoryMkey', '$categoryMdes', '$categoryDesc', '$newName', NOW())";
mysql_query($query) or die('Error, add product category failed : ' . mysql_error());

Please, bear with me; I'm still struggling to get a handle on PDO prepared statement and this was my attempt at converting the above code:

if(!$query = "INSERT INTO prod_cat (cat_name, cat_metatitle, cat_metakeywords, cat_metadescription, cat_description, cat_image, cat_date) 
    VALUES (:categoryName, :categoryMtitle, :categoryMkey, :categoryMdes, :categoryDesc, :newName, NOW())")
{
    adminapologize("Error, adding product category failed.");         
}

$params = array(':categoryName' => $categoryName, ':categoryMtitle' => $categoryMtitle, ':categoryMkey' => $categoryMkey, ':categoryMdes' => $categoryMdes, ':categoryDesc' => $categoryDesc, ':newName' => $newName);

Can you please help?

mexabet 49 Good Learner

I have a form on "add-category.php" that enables the admin to create a category and doing so includes uploading an image to a folder and inserts its file name and relevant text into the database. The script worked well with mysql_, but now it stopped working after I upgraded my "functions.php" to PDO. The issue is that the image cannot upload.

Warning: imagejpeg(/home/ script-directory/products/images/category/ec27a92192042fdc049e54477649fb30.jpg): failed to open stream: No such file or directory in /home/script-directory/includes/functions.php on line 385

This is my "add-category.php":

<?php

require_once '../../includes/config.php';

if(isset($_POST['txtName']))

{

    $categoryName = $_POST['txtName'];

    $categoryMtitle = $_POST['metaTitle'];

    $categoryMkey = $_POST['metaKey'];

    $categoryMdes = $_POST['metaDesc']; 

    $categoryDesc = $_POST['mtxDesc'];

    $imgName   = $_FILES['fleImage']['name'];

    $tmpName   = $_FILES['fleImage']['tmp_name'];

    // we need to rename the image name just to avoid

    // duplicate file names

    // first get the file extension

    $ext = strrchr($imgName, ".");

    // then create a new random name

    $newName = md5(rand() * time()) . $ext;

    // the category image will be saved here

    $imgPath = ALBUM_IMG_DIR . $newName;

    // resize all category image

    $result = createThumbnail($tmpName, $imgPath, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);

    if (!$result) {
        echo "Error uploading file";
        exit;

    }
    if(!$query = "INSERT INTO prod_cat (cat_name, cat_metatitle, cat_metakeywords, cat_metadescription, cat_description, cat_image, cat_date) 

              VALUES (:categoryName, :categoryMtitle, :categoryMkey, :categoryMdes, :categoryDesc, :newName, NOW())")
    {
        adminapologize("Error, adding product category failed.");         
    }

    $params = array(':categoryName' => $categoryName, ':categoryMtitle' => $categoryMtitle, ':categoryMkey' => $categoryMkey, ':categoryMdes' => $categoryMdes, ':categoryDesc' => $categoryDesc, ':newName' => $newName);

        var_dump($params);
        exit;

    // the category is saved, go to the category list 

    echo "<script>window.location.href='index.php?page=list-category';</script>";

    exit;

}

    // include add category template
    include("templates/add-category_template.php"); …
mexabet 49 Good Learner

@Ryantroop,
Thanks for your lengthy explanation. Yes, I didn't initially write the query() function with PDO. I became interested in PDO because of its handling of security regarding SQL injection, but I'm yet to grasp how to effectively apply it.

I know what scope means, but got confused with using someones function. My script worked well, until I introduced PDO. I like to keep my original function because, like you said, it has some wonderful benefits - including error handling. But I "need to understand how the middle bit works, and how to pass parameters to be bound to a stored procedure / prepared statement." That's my challenge now. I'm struggling to learn it. Thanks for the hashphp link.

mexabet 49 Good Learner

@ryantroop, thanks for your lengthy explanations. I'm still struggling to make sense of what you said.

How can I make the query() function to return an associative array, instead of the PDO object?

You talked about removing the static/PDO object from the custom query function and placing it outside. Do you mean remove the whole of this code and place it somewhere in the same file (functions.php)?:

    static $pdo; // define the var as static so that it will persist between function calls



    try

    {

        // if no db connection, make one

        if (!isset($pdo))

        {

            // connect to database



            // you should set the character encoding for the connection



            $pdo = new PDO("mysql:dbname=" . DB_NAME . ";host=" . DB_SERVER, DB_USERNAME, DB_PASSWORD);

            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error mode to exceptions

            $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); // turn emulated prepares off

            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); // set default fetch mode to assoc so that you don't have to explicitly list the fetch mode every place

        }



        if(empty($parameters)){

            // no bound inputs

            $stmt = $pdo->query($sql);

        } else {

            // has bound inputs

            $stmt = $pdo->prepare($sql);



             // you should use explicit bindValue() statements to bind any inputs, instead of supplying them as a parameter to the ->execute() method. the comments posted in your thread lists the reasons why.



            $stmt->execute($parameters);

        }



    }

I've made some modifications to the login.php file and I placed a check to test the query, and now it tells me that "No admin yet", when I know there is an admin:

<?php

    // configuration
    require("../../includes/config.php"); …
mexabet 49 Good Learner

@nyantroop,
Thanks for your time and insight. This is the result of var_dump() after I tried to log in with the username, "admin":

object(PDOStatement)[2]
  public 'queryString' => string 'SELECT * FROM admin WHERE username = 'admin'' (length=44)

Any idea what the bug is and how to fix it?

You said something that is of interest to me: "allow multiple admins with the same username". I actually do not want to allow multiple admins with the same username. Please, how do I correct that?

mexabet 49 Good Learner

@cereal,
The "illegal string offset" error message has stopped displaying. But down the line I'm getting another type of error, "Invalid username and/or password", when I know the supplied credentials are correct.

Here is the full code of the login.php:

<?php

    // configuration
    require("../../includes/config.php"); 

    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        // validate submission
        if (empty($_POST["username"]))
        {
            adminapologize("You must provide your username.");
        }
        else if (empty($_POST["password"]))
        {
           adminapologize("You must provide your password.");
        }

        $username = $_POST["username"];

        // query database for user
        $sql = "SELECT * FROM admin WHERE username = '$username'";

        $rows = query($sql);

        // if we found user, check password
        if(is_array($rows) && count($rows) == 1)
        {
            // first (and only) row
            $row = $rows[0];

            // compare hash of user's input against hash that's in database
            if ($_POST["username"] == $row["username"] && crypt($_POST["password"], $row["hash"]) == $row["hash"])                    
            {
                // remember that user is now logged in by storing user's ID in session
                $_SESSION["admin_id"] = $row["admin_id"];

                // redirect to admin home
                redirect("index.php");
            }
        }
        else
        {
            // else apologize
            adminapologize("Invalid username and/or password.");
        }
    }
    else
    {
        // else render form
        adminrender("login_form.php", ["title" => "Admin Log In"]);
    }

?>

Your help is always appreciated. And thanks in advance for your continued support.

mexabet 49 Good Learner

@cereal, I forgot to say that functions.php is included in config.php.

mexabet 49 Good Learner

@cereal, thanks once again for your insight.

This is what I tried, but it still generates "illegal string offset 'username' error message:

$rows = "SELECT * FROM admin WHERE username = '$username'";

        $row = query($rows);

        // if we found user, check password
        if (count($rows) == 1)
        {
            // first (and only) row
            $row = $rows[0];

            // compare hash of user's input against hash that's in database
            if ($_POST["username"] == $row["username"] && crypt($_POST["password"], $row["hash"]) == $row["hash"])
mexabet 49 Good Learner

@cereal, thanks for your insight.

I honestly don't know how to submit the query to the function and return the result set and then execute the remaining code. However, if you can tell me the PDO equivalent of the following code, I'll try to make the script to work:

$row = mysql_fetch_array($rows);

Thanks in advance.

mexabet 49 Good Learner

@cereal,
execute() is in the functions.php file:

function query($sql, $parameters = null)

    {

    static $pdo; // define the var as static so that it will persist between function calls



    try

    {

        // if no db connection, make one

        if (!isset($pdo))

        {

            // connect to database



            // you should set the character encoding for the connection



            $pdo = new PDO("mysql:dbname=" . DB_NAME . ";host=" . DB_SERVER, DB_USERNAME, DB_PASSWORD);

            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error mode to exceptions

            $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); // turn emulated prepares off

            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); // set default fetch mode to assoc so that you don't have to explicitly list the fetch mode every place

        }



        if(empty($parameters)){

            // no bound inputs

            $stmt = $pdo->query($sql);

        } else {

            // has bound inputs

            $stmt = $pdo->prepare($sql);



             // you should use explicit bindValue() statements to bind any inputs, instead of supplying them as a parameter to the ->execute() method. the comments posted in your thread lists the reasons why.



            $stmt->execute($parameters);

        }



    }

    catch (Exception $e)

    {

        // all errors with the connection, query, prepare, and execute will be handled here



        // you should also use the line, file, and backtrace information to produce a detailed error message

        // if the error is due to a query, you should also include the $sql statement as part of the error message

        // if $pdo ($handle in your code) is set, it means that the connection was successful and the error is due to a query. you can use this to include the $sql in the error …
mexabet 49 Good Learner

I can see that on hover the background color changes to grey and font color changes to black. What exactly do you want to achieve that is now working?

mexabet 49 Good Learner

Please, be advised that I'm using PDO in my functions.php file to connect, query, prepare, and execute.

mexabet 49 Good Learner

My login script is displaying the following error message:

Warning: Illegal string offset 'hash' on line 30.

Here is the code that generates the error:

<?php
    // configuration
    require("../../includes/config.php"); 

    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        // validate submission
        if (empty($_POST["username"]))
        {
            adminapologize("You must provide your username.");
        }
        else if (empty($_POST["password"]))
        {
           adminapologize("You must provide your password.");
        }

        $username = $_POST["username"];

        // query database for user
        $rows = "SELECT * FROM admin WHERE username = '$username'";

        // if we found user, check password
        if (count($rows) == 1)
        {
            // first (and only) row
            $row = $rows[0];

            // compare hash of user's input against hash that's in database
            if (crypt($_POST["password"], $row["hash"]) == $row["hash"])
            {
                // remember that user's now logged in by storing user's ID in session
                $_SESSION["admin_id"] = $row["admin_id"];

                // redirect to admin home
                redirect("index.php");
            }
        }

        // else apologize
        adminapologize("Invalid username and/or password.");
    }
    else
    {
        // else render form
        adminrender("login_form.php", ["title" => "Admin Log In"]);
    }

?>

The error seems to be coming from this line:

if (crypt($_POST["password"], $row["hash"]) == $row["hash"])