Link to home
Start Free TrialLog in
Avatar of K Feening
K FeeningFlag for Australia

asked on

Connecting to database

HI  I am using bootstrap 5 and css html etc 

I would like to connect to my database from my web page login screen to check if password exists using php, I have the connection  in my web.config file in the <connectionStrings>

section can I use this string from web.config in the php connection instead of 

  <? php
   $conn=mysqli_connect("localhoast","root","","databasename") 
  ?>

Open in new window

Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey there,

Technically you probably could, but you seem to be mixing different languages. The web.config file is part of ADO.NET, and has nothing to do with PHP / HTML etc. I say you technically could, because you can manually read and parse the web.config file (it's just an XML file), but it does seem like a lot of extra, unneccessary work.
Standard practice is to put your DB connection code in its own script and included that where needed. This in turn would usually involve storing your connection parameters (username, database, password) in some secure way that is not accessible from the outside (there are various ways of doing this).

From your client code you have basically two options in terms of validating the login input data.
a) Post back to the server, validate and then re-render the login screen on fail
b) AJAX the request to the server and handle the response in the browser.

Option b has become the de facto standard for doing this - it is the simplest to implement and has the least moving parts.

Your submission could be as simple as
<form name="loginForm" action="authenticate.php">
    <input type="text" name="username">
    <input type="password" name="password">
   <button type="submit">Login</button>
</form>

Open in new window

JavaScript
(function() {
  window.addEventListener('load', init);

  function init() {
    // Bind to the submit event on the named form
    document.forms.loginForm.addEventListener('submit', (e) => {
      // Disable the default submit behaviour
      e.preventDefault()

      // Get our form and from there create a FormData object to get the data from the form
      const frm = e.target
      const body = new FormData(frm)

      // AJAX back to the server
      fetch(frm.action, {method: "POST", body})
        .then(resp => resp.json())
        .then(resp => {
          if (resp.status) {
            window.location = resp.url
          } else {
            // handle error here: message on form, next to field etc
          }
      })
    })
  }
})();

Open in new window

Here is a skeleton server side script to validate the login. You will need to adapt it to your specific requirements.
It assumes the existence of a dbconnection.php script that setups up the PDO db connection in the $conn variable.
<?php
// Include our DB connection code (assumes PDO)
require_once('dbconnection.php');

// Setup our response object
$resp = [
   'status' => false
];

// Extract posted data and bug out if not found
$username = $_POST['username'] ?? false;
$password = $_POST['password'] ?? false;

if ($username && $password) {
   // Get the user record
   $query = <<< EOT
SELECT * FROM tbl_users WHERE username = :username
EOT;
   $stmt = $conn->prepare($query);

   // Check the user exists and password is good
   if ($stmt->execute(['username' => $username]) && $stmt->rowCount() > 0){
     $row = $stmt->fetch(PDO::FETCH_OBJ);

     // Assuming you have used password_hash to hash the password in the DB
     if (password_verify($password, $row->password)) {
        // All good - send back pass result to browser
        $resp->status = true;
        $resp->url = "securepage.php";
     } 
   }
}

header('Content-type: application/json');
die(json_encode($resp));

Open in new window

Avatar of K Feening

ASKER

Thanks guys  (I hope this makes sence I am trying to convert vb.net webforms to work on different screen resolutions and with option for iPhone on 1 product only, using Bootstrap i havn't uses php before but with the bootstrap tutorials and examples I am getting there)  is there a video youtube creating
a bootstrap login form connecting to sql server 2014 database table with the password encrypted and
how to create the $Connection conn file for the server path name password etc and load it in to the php
<?php
$Connect = mysqli_connect();
session_start();
if(isset($_   etc

Table is 

CREATE TABLE [dbo].[UserLogin](
   [Id] [int] NOT NULL,
   [UserName] [nchar](50) NOT NULL,
   [Password] [nchar](100) NULL,
   [MasterUser] [Bit] NULL,
   [Maintenance] [Bit] NULL,
   [Careers] [Bit] NULL
) ON [PRIMARY]

Open in new window

In VB.net I create the usernames and passwords (encrypted)

I have crearted a bootstrap login screen but need to check if user name and encrypted password exists and depending on the user goto different webpages
Imports System.Security.Cryptography

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 connString = ConfigurationManager.ConnectionStrings("DataName").ConnectionString

        If Not IsPostBack Then
            Dim con1 As New SqlConnection(connString)
            con1.Open()
         end if 
end Sub

'------------------------------------------------------
I Use Encpassword to encrypt after the user enters into textboxes username and password encript the password and check table fields exists for them
        
        EncPassword = Savpw
        bEncrypt_Click(sender, New System.EventArgs())
'-------------------------------------------------------

Private Sub bEncrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        key = System.Text.Encoding.UTF8.GetBytes(Strings.Left(EncryptionKey, 8))
        Dim des As New DESCryptoServiceProvider
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(EncPassword)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        EncPassword = Convert.ToBase64String(ms.ToArray())

    End Sub

    Private Sub bDecrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Dim inputByteArray(EncPassword.Length) As Byte
            key = System.Text.Encoding.UTF8.GetBytes(Strings.Left(EncryptionKey, 8))
            Dim des As New DESCryptoServiceProvider
            inputByteArray = Convert.FromBase64String(EncPassword)
            Dim ms As New MemoryStream
            Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
            EncPassword = encoding.GetString(ms.ToArray())
        Catch ex As Exception
            'oops - add your exception logic
        End Try

    End Sub

Open in new window



Firstly, Bootstrap is just the theme - it has no bearing on the functionality in terms of connecting to the database
Secondly, if at all possible use PDO over MySQLi - you will thank yourself down the line.

I have crearted a bootstrap login screen but need to check if user name and encrypted password exists and depending on the user goto different webpages 
I believe the sample I provided does exactly what you want to do. The field names might need tweaking and you might need to change the way you check passwords if you are dealing with a database of users that already exists (the solution above assumes the passwords were hashed with the php password_hash() function).

Apart from that the code is good to go.

From the client it makes an AJAX call (on form submit) to the PHP script to validate the username and password.

An object is sent back that includes
a) A status (true / false) informing the client on the status of the authentication request
b) A URL to redirect to if the status is true
c) You can optionally include an error message or object to provide a custom error message if not handled specifically in the client (on the else branches of the authentication set the resp['message'] value to the message and then use in the client)

Not sure what else you need from here?

Help is what I need at 65 I think is too late to relearn (rubbish its fun) i'm used to 20years of desktop apps and I created cloud based / webforms to help my son with his job (and it got bigger than ben hur) and found the screen didn't fit correctly on his laptop (different resolution to mine)  and he wanted to use 1 app on mobile phones
.
I can understand connecting to servers using vb.net using a connection string from the web.config file
connString = ConfigurationManager.ConnectionStrings("SiteName").ConnectionString
there can be multiple connections/databases and I use a replace option in vb Page_load event to get the correct database depending on the username I Replace the word School in the connstring with Schoolname1 or SchoolName2

Where in your code (much appreciated) is there a file or connection string that uses the database / server / username etc ? basically how do you connect and as before asked run different modules depending on the users access rights from the Userlogoin table $Connect = mysqli_connect(WHAT DO YOU PUT HERE); 
 
NB I use have done css, java script, html courses on line and I like to see videos / examples to learn

1.. How do you load the $Connect from a external file stored on the web server
2.. How do you replace the string in the $Connect depending on user as you can in VB and pass it to another form
3.. Can you pass variables between forms to reflect which connection is used and have the variables accessible in the page_load event in the .aspx.vb file selected.        Like connectionstring password schoolname other variables etc
4.. Run different modules depending on the users access rights from the Userlogoin table  
all these options currently work on the Webform version (Beta Testing not released yet)

its for schools and there are 2 diferent schools involved and 3 different products Student access, teachers access and Master User again depending on login

I don't have a problem going back and learning PHP or other connection options videos or tutorials are good.

Or it there a way to add the bootstrapscreen resolution resizing options to my VB.aspx VB.aspx.vb code without converting the <asp:Label textboxes, radiobuttons gridviews to be    
<input class="form-check-input" type="radio" name="exampleForm" id="radioExample2" />          
<label class="form-check-label" for="radioExample2">

I use 2014 Sql Server
VS2019
VB.net
PHP 8.0.11 is loaded

Thanks again for your time
  
You would need a database or a table that would have a list of usernames  and connection strings then do a lookup on the username and then connect to the database using the corresponding connection string.

Connection strings can be in a web.config or a file or in code.
You are not limited to putting the connection string on the on_load event
Apologies - was under the impression you already had the connection script
Here is a standard PDO connection script (named the same as the script I used above)
dbconnection.php
<?php
// Included in this script but would typically be stored in a
// config file outside of the webroot.
$host     = 'localhost';
$database = 'db_name';
$username = 'username';
$password = 'password';

$dsn = "mysql:dbname={$database};host={$host}";

try {
    $conn = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

Open in new window

Now when you do your
<?php
require_once('dbconnection.php');

Open in new window

The $conn variable will be available for you to use.

In answer to your questions
1.. How do you load the $Connect from a external file stored on the web server
As above - it is a global variable. More advanced implementations might include wrapping the connection in a class - but this will do for simple situations.

2.. How do you replace the string in the $Connect depending on user as you can in VB and pass it to another form
Not sure why you would want to? Your connection should be based on credentials specifically created for your application - not sure why you would switch users. The above demonstrates how to parameterize your connection details though if that is what you are asking.

3.. Can you pass variables between forms to reflect which connection is used and have the variables accessible in the page_load event in the .aspx.vb file selected.        Like connectionstring password schoolname other variables etc

Pages are autonomous isolated scripts that run in the browser. Anything you want to share has to be put in a persistent store where other scripts can find them.

i) When communicating from form to server you will have to pass data either as part of the POST body or in the header.
ii) If you want variables to be available between form submissions you will need to save these on the server using some sort of session - accessed either with a COOKIE or a token that is passed in the header or part of the submission.
iii) To "pass data" between forms in a browser you can save data in localStorage or sessionStorage - locations in the browser specifically available for scripts to persist data. Local storage persists until it is cleared, session storage persists only as long as the browser is open.

With respect to your last sentence - not sure why you would want to be dealing with connection strings at the browser level - that is not a good idea.

Not sure if that answers your question.

4.. Run different modules depending on the users access rights from the Userlogoin table  
all these options currently work on the Webform version (Beta Testing not released yet)

its for schools and there are 2 diferent schools involved and 3 different products Student access, teachers access and Master User again depending on login

This is a function of your code - you seem to have made provision for roles in your table - it would be a simple case of testing for those roles and then including the specific module based on role.

Sidebar: PHP allows you to include scripts inside other scripts using the require()  / require_once()  / include() / include_once()

This allows you to do something like this (assume you have retrieved your user into the variable $user
<?php
...
$user = getUser($userId);
if ($user['MasterUser']) {
   require_once('modules/master_user.php');
} else if ($user['Maintenance']) {
   require_once('modules/maintenance_user.php');
} else if ($user['Careers']) {
   require_once('modules/careers_user.php');
} else {
   require_once('modules/default_user.php');
}

Open in new window


Note this is just a sample - I am not suggesting you do it this way just demonstrating how you would include different functionality based on a user field value.
Thanks David
I Have a table with information needed and I know how to connect in the on_load event as I said in the previous comment
and it runs correctly
 
The previous comment from me (it seems not worded correctly) was how to do it in (I still dont know how to phrase it)
PHP Bootstrap html or what ever, to use the bootstrap option for screen resolution resizing.

I want to run the product to run multiple resolutions and as its in VB.net webpages do I need to re-create all my pages to use Bootstrap (CORRECT ?) and not use VB.net if so HOW

or can I convert all my current vb.net webforms some how to bootstrap option so I can run other webpages from the new bootstrap login screen is built

Option convert all pages to use php and bootstrap so
1.. How do you connect to the 2014 sql Server using $Connect and a filename
2.. How Check the users in the database file and what previliges they have
3..  Run a web page depending on their privileges
4.. Pass variables from the login screen to the new aps. aspx.vb page
 
We need to split this up into focus areas
Bootstrap - this is just CSS - it is browser only and deals with your layout - it has nothing to do with VB or PHP - neither of those come into play.

The setup of your browser content for different resolutions is one task
The setup of your database for accessing user data is a second and completely separate task.

Converting to Bootstrap just means changing your HTML layout to use Bootstrap classes and constructs. It is server script agnostic.

On re-reading your post it seems you want to make a different connection to the database based on the user logged in - my first question would be why? This seems unnecessarily complicated. However if that is how you are working then you would need to store the connection details in a master store (table or config file) that you could then access (as Dave suggested)

I have answered your other questions in my previous post.
HI
I'm Lost sorry
1.. Does PHP have to be installed/loaded into VS2019
** I went into extensions > Manage Extensions > Online and searched for PHP PHP Tools doesn't show
I looked up PHP Tools and downloaded PHP.VS.1.56.14601.2019.vsix and got install failed
2.. I have included the code  dbConnect.php
         a) $Host is it localhost or the actual Server name
         b) $database actual database name
         c) $password Im using Windows Authentication so no password or is it better to use SQL Server authentication
<?php
$host     = 'localhost';
$database = 'SchoolName';
$username = 'sa';
$password = '#######';

$dsn = "mysql:dbname={$database};host={$host}";

try {
    $conn = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}   

Open in new window

Copy of code
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="FacultyLogin.aspx.vb" Inherits="School.FacultyLogin" %>

<?php
require_once('dbconnection.php');
  ?>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login</title>
    <script>
        (function () {
            window.addEventListener('load', init);

            function init() {
                // Bind to the submit event on the named form
                document.forms.loginForm.addEventListener('submit', (e) => {
                    // Disable the default submit behaviour
                    e.preventDefault()

                    // Get our form and from there create a FormData object to get the data from the form
                    const frm = e.target
                    const body = new FormData(frm)

                    // AJAX back to the server
                    fetch(frm.action, { method: "POST", body })
                        .then(resp => resp.json())
                        .then(resp => {
                            if (resp.status) {
                                window.location = resp.url
                            } else {
                                // handle error here: message on form, next to field etc
                            }
                        })
                })
            }
        })();
    </script>
</head>
<body>
     <form id="login-form" class="form" action="#" method="post"> 
        <div class="form-group">
           <label for="username" class='<%#Eval("textDesc")%>'>Username:</label>
           <input type="text" name="username" id="username" class="form-control" required="required" />
        </div>
        <div class="form-group">
           <label for="password" class='<%#Eval("textDesc")%>' >Password:</label>
           <input type="text" name="password" id="password" class="form-control" required="required" />
        </div>
        <div class="form-group">
            <input type="submit" name="login" class="btn btn-info btn-md" value="Login" />
        </div>
        </form>  
</body>
</html>

<?php
$resp = [
   'status' => false;
];

// Setup our response object
$resp = [
   'status' => false
];

// Extract posted data and bug out if not found
$username = $_POST['username'] ?? false;
$password = $_POST['password'] ?? false;

if ($username && $password) {
   // Get the user record
   $query = <<< EOT
SELECT * FROM SchoolLogin WHERE username = :username
EOT;
   $stmt = $conn->prepare($query);

   // Check the user exists and password is good
   if ($stmt->execute(['username' => $username]) && $stmt->rowCount() > 0){
     $row = $stmt->fetch(PDO::FETCH_OBJ);

     // Assuming you have used password_hash to hash the password in the DB
     if (password_verify($password, $row->password)) {
        // All good - send back pass result to browser
        $resp->status = true;
        $resp->url = "securepage.php";
     } 
   }
}
header('Content-type: application/json');
die(json_encode($resp));
?>

Open in new window





The reason for different connections is there are currently 2 schools I am using for my testing they currently have a standalone desktop version and would like it to be cloud based (learning as I go) , so the databases are setup depending on the  school name
e.g,   BabalonHighSchool, MethuselahPrimary or for students StudentCareer
the students have a career database for surveys so they cannot see any information stored by the teachers
Basically they login and there is a Database called Schoolname containing a table that depending on the user / password replaces the schoolname in  the connString - ConfigurationManager.ConnectionStrings("SchoolName").ConnectionString

<add name="SchoolName" connectionString="Data Source=########\####DATASQL;initial Catalog=SchoolName;Integrated Security=SSPI;Max Pool Size=300;Max Pool Size=300" providerName="System.Data.SqlClient" />

Open in new window

I did it this way so users can only see the relevant tables / data for their school or students

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for all you support (excellant)
I am self taught in delphi, vb.net css bootstrap java (basic) ) all from online products/videos/tutorials  and learning slowly cloud based I have been told I have no logic but wrote a desktop payroll program that run in 60 + clubs for 10 years
my emai address is kevinfeening@hhotmail.com there must be a vidio / tutorial to do what i need I don't know the terminaoigy you are using sorry, but I cannot be told that it cannot be done  maybe I dont explain what I need correctly
I Dont care how many hours I takes learning web base / cloud tecnology /i enjoy a challenge
You are most welcome and good luck.