Good day everyone:
I'm having trouble making a login page for my PHP application with a connection to an MS SQL Server database.
I can connect to the database using this code:
<?php
$serverName = "DESKTOP-FDJAOMJ\\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"sgo", "UID"=>"arm", "PWD"=>"arm123");
$con = sqlsrv_connect( $serverName, $connectionInfo);
if( $con ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
And then the connection is ok. But, I've only ever worked with a MySQL backend, and this project requires MS SQL, and I can't get the MS SQL login page to work. My code is below:
<!DOCTYPE html>
<html>
<body>
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
//$username = unpack($con,$username);
$password = stripslashes($_REQUEST['password']);
//$password = addslashes($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='$password'";
$params = array();
$result = sqlsrv_query($con,$query,$params) or die(sqlsrv_errors());
$rows = sqlsrv_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='registration.php'>Register Here</a></p>
</div>
<?php } ?>
</body>
</html>
When I type in the username and password I get an error:
Notice: Array to string conversion in C:\wamp\www\PHPwebpage\login.php on line 18. line 18 is ""$result = sqlsrv_query($con,$query,$params) or die(sqlsrv_errors());"".
users table variables: id int username varchar(50) email varchar(100) password varchar(50) trn_date datetime