I've been programming this server / database in Microsoft Azure. And I've created this PHP to control everything. The main goal is to create a website where you are able to register and log in, for this I need a database and server which handles all these values.
In my code hoewever, the database doesn't seem to be storing anything, everything does what's expected, expect for the connection between database and PHP document. Therefore I turned to you guys, heard u'd be the best haha!
Just FYI, first post, be nice :)
Here's my PHP doc.
<?php
if (isset($_POST['submits']))
{
if (empty($_POST['usernames']))
{
$error = "Fill in all the boxes";
}
elseif (empty($_POST['passwords']))
{
$error = "Fill in all the boxes";
}
elseif (empty($_POST['emails']))
{
$error = "Fill in all the boxes";
}
elseif(strpos($_POST['emails'], "#") === false)
{
$error = "Wrong syntax: example#.com";
}
else
{
$username=$_POST['usernames'];
$password=$_POST['passwords'];
$email=$_POST['emails'];
$connectionInfo = array("UID" => "MY_SERVER_EMAIL", "pwd" => " MY_PASSWORD", "Database" => "MY_DATABASE", "LoginTimeout" => 30, "Encrypt" => 1);
$serverName = "(MY_DATABASE";
$conn = sqlsrv_connect($serverName, $connectionInfo);
$sql = "SELECT username, email FROM dbo.Login";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$usertrue=TRUE;
if($usertrue===TRUE)
{
$error = "Account added";
$hashedpassword = md5(md5(sha1(sha1(md5($password)))));
$query = "INSERT INTO dbo.Login (username, password, email) VALUES ('$username', '$hashedpassword', '$email' )";
$result = sqlsrv_query($conn, $query );
if($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected succesfully";
}
sqlsrv_free_stmt( $stmt);
sqlsrv_close($conn); // Closing Connection
}
}
?>
The form is named POST and the inputs are named usernames, passwords, emails and submits.
Grateful for answers!
Anton
Looking at the code, I am assuming that you have replace the values with some place-holder.
Nevertheless, there might be some typo. There $ServerName has a "(". and I believe the Insert statement is not formatted correctly (i.e., all $username, $password, $email) is not getting evaluated because it is treated as string.
Also, why are you checking for connection error after executing the insert query. It should be checked first and re-connected if it is not connected before executing the insert query.
Related
While I was on w3schools learning about MySQL and PHP, I came across this when on the page about inserting data.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When checking the query was successful, why do we check if both are the same type and equal? Wouldn't it be fine if it was just this?
if ($conn->query($sql) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli::query() returns false on failure, another result will be always not false. You can write without equaling with true if you don't need to use special logic for mysqli_result. docs
if ($conn->query($sql))
{
//
} else
{
//
}
Php supports truthyness do if the function returned 1 then it would be true. It's explicitly checking that the result is the Boolean TRUE.
You do NOT need to check type in THIS case and could just have:
if ($conn->query($sql) == TRUE) {
The author is probably using a defensive programming technique which is to validate exactly what you are expecting.
According to: http://php.net/manual/en/mysqli.query.php
If this is a "SELECT, SHOW, DESCRIBE or EXPLAIN" then you would get an object back. If somebody updated the query to something unexpected, they would hit the error condition and know they had done something wrong. This particular scenario is a little off because it's sample code. In reality you would probably have a test to do the real validation.
When ever I use php to connect to my database I get a sudden error saying "database connection failed" is there anyway to fix this its for a login and register screen. Thanks to anyone who help...
<?php
$connection = mysqli_connect('localhost', 'root','','test');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
<?php
//
require('database.php');
$connection = mysqli_connect('localhost', 'root','','test');
// If the values are posted, insert them into the database.
if (isset($_POST['Register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
//echo $query;
$result=mysqli_query($connection,$query);
if($result){
$smsg = "User Created Successfully.";
}else{
$fmsg ="User Registration Failed";
}
}
?>
Connection to a database with php requires 4 parameters (host, data base user, password, data base name, passwd), it's better nowadays to use db object instead of procedural "old" behaviour:
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli("localhost", $dbUser, $passwd, $dbName);
if (!$mysqli->set_charset("utf8")) $msg = "error charset mySQLi"; else $msg = "Set UTF-8 ok";
return $mysqli;
}
catch (Exception $mysqlin){
echo "Error stablishing connection with database ".$mysqlin->getMessage();
}
}
then you can connect easily as follows:
$sql = "SELECT * FROM users;";
if(!$result = connection()->query($sql)) echo "db query error"; else "query ok";
$rs = mysqli_fetch_assoc($result);
//do whatever and, to get next line of results:
if($rs!=''){
$rs = mysqli_fetch_assoc($result);
}
So you get a row of the results on $rs[] array.
EDIT: You'll need to apply security, this is a simple connection without regarding on it. Check mysqli bind params on php official webpage for it:
http://php.net/manual/en/mysqli-stmt.bind-param.php
Hope it helps
I am trying to make my website protected from sql injections. So I decided to change my code and replace it with prepared statements. I think I made a minor misstake in the code below.
<?php
session_start();
$host= 'localhost';
$user='root';
$pass='';
$db='gameforum';
$conn= mysqli_connect($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
$rpassword = $_POST['rpassword'];
$email = $_POST['email'];
if ($password!==$rpassword) {
$_SESSION['err']="Passwords did not match, please try again!";
header("Location: index.php");
$conn->close();
}
else {
$stmt = $conn->prepare("INSERT INTO users (username, password, rpassword, email) VALUES (?, ?, ?, ?)");
if(!$stmt){
echo "false";
}else {
$stmt->bind_param("ssss", $username, $password, $rpassword, $email);
if ($stmt->execute === TRUE) {
$redirectUrl = 'index.php';
$_SESSION['registrationsuccessful']="Your account was successfully created! You may now log in to your account.";
header("Location: index.php");
}else{
$_SESSION['alreadyexists']="Username or email already exists!";
header("Location: index.php");
$stmt->close();
$conn->close();
}
$stmt->close();
$conn->close();
}
}
The problem I am facing now is that I get the message "user already exists" when I try to create an account that do not actually exist. Thanks!
You have already executed the execute statement. Remove one of them. Alternatively check for success on only one of the execute statement
I believe the reason for the problem was the second usage of $stmt->execute() - but a few other modifications could be made to the code.
Create the db connection IF the initial logic if ( $password!==$rpassword ) test succeeds ~ seems pointless otherwise. I would use one session variable for this rather than 3 - it makes it easier to check the values later on other pages perhaps.
Assign the result of the first $stmt->execute() to a variable and use that vaiable in further logic tests if needed.
As for error messages - it is fine ( and indeed preferable ) to display verbose error messages for development but never in production - hence removed $conn->connect_error.
One other thing, mixing of procedural and object orientated code is probably not considered good practise - better to stick to one or other ( OO is easier I think )
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$rpassword = $_POST['rpassword'];
$email = $_POST['email'];
$_SESSION['registration_status']="";
if ( $password!==$rpassword ) {
$_SESSION['registration_status']="Passwords did not match, please try again!";
exit( header( "Location: index.php" ) );
} else {
$host= 'localhost';
$user='root';
$pass='';
$db='gameforum';
$conn= mysqli_connect($host, $user, $pass, $db);
if( $conn->connect_error ) die( "Connection failed" );
$stmt = $conn->prepare("INSERT INTO users (`username`, `password`, `rpassword`, `email`) VALUES (?, ?, ?, ?)");
if( $stmt ){
$stmt->bind_param("ssss", $username, $password, $rpassword, $email);
$result = $stmt->execute();
/* use the return value from stmt->execute() */
$_SESSION['registration_status'] = $result ? "Your account was successfully created! You may now log in to your account." : "Username or email already exists!";
$stmt->close();
}
$conn->close();
exit( header( "Location: index.php" ) );
}
}
?>
You can try this,
<?php
// if session not start, start now
!session_id() ? session_start() : null;
$mysql_server = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_db = "gameforum";
// connect db connection
$conn = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
// chck if connection has error
if ($conn->connect_errno) {
printf("Connection failed: %s \n", $conn->connect_error);
exit();
}
// db encoding
$conn->set_charset("utf8");
// when POST happen
if (isset($_POST) && !empty($_POST)) {
// convert POST array key as PHP variable
extract($_POST);
// if password matched with confirm password
if ($password === $rpassword) {
// create insert query with prepare
$stmt = $conn->prepare("INSERT INTO users (username, password, rpassword, email) VALUES (?, ?, ?, ?)");
// if prepare fine, there is no query or mysql error
if ($stmt) {
// bind real values
$stmt->bind_param("ssss", $username, $password, $rpassword, $email);
// if query executed
if ($stmt->execute()) {
// success message & redirect
$_SESSION['registrationsuccessful'] = "Your account was successfully created! You may now log in to your account.";
header("Location: index.php");
exit();
} else {
// query error & redirect
$_SESSION['alreadyexists'] = "There was an error or Username/Email already exists!";
header("Location: index.php");
exit();
}
}
} else {
// password matched failed
$_SESSION['err'] = "Passwords did not match, please try again!";
header("Location: index.php");
exit();
}
}
I am not closing connection because, PHP will close all open files and connections at the end of the script.
What I'm trying to do is make a username (just username) get sent to a MySQL database, if it isn't already there.
Basically, I'm getting the input, checking it against all other rows in my username column, and, if the input is not the same as any of them, then add the input to the database. Here is my code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset( $_POST["submit"] ) ) {
$sql="INSERT INTO users (username)
VALUES('$_POST[username]')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["username"] == $_POST[username]) {
die("Username is already in use!");
}
}
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
}
$conn->close();
No error is reported, but it simply creates the data twice, and doesn't check the input. I can't see how. This is how I've tried. It looks logical that is should work, but it's not. Why?
I'm using MySqli Object-Orientated
Try this code...
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset( $_POST["submit"] ) ) {
$sql="INSERT IGNORE INTO users (username)
VALUES('$_POST[username]')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["username"] == $_POST[username]) {
die("Username is already in use!");
}
}
echo "New record created successfully";
}else {
die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
}
$conn->close();
You are executing the $conn->query($sql) twice. The first one is in $result = $conn->query($sql); and the second if ($conn->query($sql) === TRUE). That is why you get 2 entries in the for one request.
First check for the user you are prepering to insert and if it returns 0 statements then go with the second if you have wrote.
Edit 2:
Try use PDO:
The code will look something like this:
if( isset( $_POST["submit"] ) ) {
$stmt = $pdo->prepare("SELECT username FROM users WHERE username LIKE ?");
$stmt->execute( array( $_POST["username"] ) );
$_results = $stmt->get_result();
if( count( $_results ) > 0 ) {
die("Error, please consult an admin!");
} else {
$stmt = $pdo->prepare('INSERT INTO users (username) VALUES( ? )' );
$stmt->bindParam( 1, $_POST['username'] );
if( $stmt->execute() ) {
echo 'Success';
} else {
echo 'Whoops, you have an error mate!';
}
}
}
Hope it helps
Hello i am having some trouble getting a script to run, i keep getting an error message saying it expects two parameters and i have no idea how to fix it, heres the script:
<?php
session_start ();
if(isset($_SESSION['user'])){
$username = $_SESSION['username'];
if(isset($_POST['submit'])){
$oldpassword = $_POST['oldpassword'];
$newpassword = $_POST['newpassword'];
$serverName = "server";
$connectionInfo = array("Database"=>"database","UID"=>"id", "PWD"=>"pass");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false){
echo "Error in connection.\n";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "SELECT userPass FROM customers WHERE userName='$username'";
$stmt = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => 'static' ));
if ( !$stmt ){
die( print_r( sqlsrv_errors(), true));
}
$rows = sqlsrv_num_rows($stmt);
if($rows === false){
die( print_r( sqlsrv_errors(), true));
}elseif($rows == 0){
echo "No rows returned.";
exit();
}else{
$querychange = sqlsrv_query("UPDATE customers SET userPass='$newpassword' WHERE userName='$username'");
session_destroy();
die ("Your password has been changed. <a href='index.php'>Return</a> to the main page and login with your new password.");
}
}
}
?>
I keep getting this error
PHP Warning: sqlsrv_query() expects at least 2 parameters, 1 given in file_name.php on line 27
Line 27 is where i update customers. If anyone can spot an error in the script can you let me know, also yes I've not done SQL injection, at this stage I'm simply trying to get it working before I implement that.
Thanks for all the help, it's much appreciated
Try passing connection to sqlsrv_query
something like:
$querychange = sqlsrv_query($conn, "UPDATE customers SET userPass='$newpassword' WHERE userName='$username'");