PHP Register Script - check user exists not working - php

I've got a problem with my PHP Registration Script that firstly checks, if the user exists.
It always outputs "false".
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$database = #mysql_connect("***********", "********", "******") or die("Can't connect to the server. Error: ".mysql_error());
//$username = mysql_real_escape_string($username);
$passwort = hash("sha256", $passwort);
$numrows = mysql_query("SELECT * FROM *******.mikgames WHERE username='".$username."' LIMIT 1");
$checkuserexists = mysql_num_rows($numrows);
if($checkuserexists==0) {
$abfrage = mysql_query("INSERT INTO *******.mikgames (username,passwort) VALUES ('$username', '$passwort')");
echo'true';
}
else {
echo'false';
}
?>
Edit: Now I'am using MySQLi and I've changed the code into this:
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$con = mysqli_connect('************','******','******') or die(mysqli_error());
mysqli_select_db($con, "*******") or die("cannot select DB");
$passwort = hash("sha256", $passwort);
$query = mysqli_query($con,"SELECT * FROM *******.mikgames WHERE username='".$username."'");
$result = mysqli_num_rows($query);
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames (username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
echo 'true';
}
else {
echo 'false';
}
?>
And it works.

You could go one step better and take an OOP approach using the PDO driver; PDO invokes security by allowing secure parameter binding and uses the SQL preferred functions.
Inside your pdo_driver.php file:
namespace ProjectName\App\Drivers;
if(!defined('IN_PROJECTNAME'))
{
die('No Script Kiddies Please...');
}
interface EntityContainer
{
public function query($statement, array $values = array());
}
class Entity extends \PDO implements EntityContainer
{
public function __construct(
$dsn = 'mysql:host=XXXX;dbname=XXXX', $user = 'XXXX', $pass = 'XXXX'
) {
try {
parent::__construct($dsn,$user,$pass);
} catch (PDOException $ex) {
die('FATAL ERROR: ' . $ex->getMessage());
}
}
public function query(
$statement, array $values = array()
) {
$smpt = parent::Prepare($statement);
(empty($values)) ? $smpt->execute() : $smpt->execute($values);
return $smpt;
}
}
Inside any other php file:
define('IN_PROJECTNAME', 0);
require_once dirname(__FILE__) . '/path/to/pdo_driver.php';
$container = array();
$container['Connection'] = new ProjectName\App\Drivers\Entity();
$username = $_GET['username'];
$passwort = $_GET['passwort'];
if(empty($container['Connection']->query('SELECT passwort FROM ******.mikgames WHERE username = ?', [$username])->fetch()['passwort'])) {
$container['Connection']->query('INSERT INTO ******.mikgames (username,passwort) VALUES (?, ?)', [$username,$passwort]);
}

Two Factors:
Firt Factor
You need to add an error output for debugging purposes:
$query = mysqli_query($con,"SELECT * FROM <tablename> WHERE
username='".$username."'") or die(mysqli_error($con));
I can't see a clear error with the information you have displayed here so far so you should also check what the value of $username acutally is and how closely it fits the value in the DB. Also read and take on board what the error output tells you.
Second Factor:
Your problem is you're running/articulating a query twice, here:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
You see $abfrage is a MySQL result object and you're then plugging it back into a MySQL query call, with the variable declaration $result. So your result is querying a query. This is an error.
What you probably want to do is use MySQLi_affected_rows to count how many rows have been inserted and run the appropriate IF clause:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_affected_rows($con);
echo 'true';
}
else {
echo 'false';
}

Use #mysql_***** for your ptoject.
$sql="SELECT * FROM table_name";
$result=#mysql_query($sql, $conn);
while ($name = # mysql_fetch_array($result)){
echo $name ['username'];
}
You just used simple mysql_***

Related

Checking SQL Database for value

I am trying to use php to check my database to see if a value exists. My main goal is to use this value
$_GET['UDID']
and if it is equal to any value that is in the database it will return
echo 'FOUND';
I am using this code:
<?php
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "*****";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("CONNECTION FAILED: " . $connect->connect_error);
}
$udid = $_GET['UDID'];
$id = mysqli_real_escape_string($connect, $udid);
$result = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '$id'");
if($result === FALSE) {
die("ERROR: " . mysqli_error($result));
}
else {
while ($row = mysqli_fetch_array($result)) {
if($row['udid'] == $udid) {
$results = 'Your device is already registered on our servers.';
$results2 = 'Please click the install button below.';
$button = 'Install';
$buttonlink = 'https://**link here**';
}
else {
$results = 'Your device is not registered on our servers';
$results2 = 'Please click the request access button below.';
$button = 'Request Access';
$buttonlink = 'https://**link here**';
}
}
}
?>
But for some reason it is not working, I am sure I am over looking something. your help is greatly appreciated.
Try this:
$sql = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '" .$udid. "'");
And also, make sure to set the value from 'GET' to $udid. Should be like this:
$udid = $_GET['UDID'];
We can use mysqli_fetch_array() instead to get the result row. I also include error handling. Now your code must look like this :
$udid = $_GET['UDID'];
$id = mysqli_real_escape_string($connect, $udid);
$result = mysqli_query($connect, "SELECT `udid` FROM `wmaystec_WMT-SS`.`data` = '$id'");
if($result === FALSE) {
die(mysqli_error("error message for the user")); //error handling
}
else {
while ($row = mysqli_fetch_array($result)) {
echo "FOUND :" .$row['thefieldnameofUDIDfromyourDB'];
}
}
I would suggest you to first escape the string, using the mysqli_real_escape_string function, and then call the SQL query.
$udid = mysqli_real_escape_string($connect, $udid);
$sql = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '$udid'");

mysqli statement does not work under php

There's a bit problem for mysqli select statement as I did a select statement which actually counts the number of results. But it does not return the value I want but instead it returns none. Need help guys. I did this select statement as a function using mysqli and php
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
echo "string</br>";
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['userssss']."asdasd</br>";
die("userssss");
$return = $row['user'];
return $return;
}
result
string
asdasd
userssss
It should show the result before asdasd
add global $con;
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as user from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['user'][0]."asdasd";
die();
$return = $row['user'][0];
return $return;
}
I found it. Silly of me.
Instead of using assoc, one must use array
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$return = $row['user'];
return $return;
}
You need to count everything meaning rows matched where clause. Also try to adopt prepared statements. Bellow code works.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function count_result($data){
$user = 'username';
$password = 'password';
$db = 'database';
$host = 'hostname';
$port = 3306;
/* Attempt MySQL server connection. Assuming you are running MySQL server */
$link = mysqli_connect($host, $user, $password, $db);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if($stmt = $link -> prepare("SELECT COUNT(*) FROM test WHERE ID= ?"))
{
/* Bind parameters, s - string, b - blob, i - int, etc */
$stmt -> bind_param("i", $data);
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($testfield1);
/* Fetch the value */
$stmt -> fetch();
$numberofrows = $stmt->num_rows;
} else{
echo "ERROR: Could not able to execute SQL. " . mysqli_error($link);
}
/* Close statement */
$stmt -> close();
echo '# rows: '. $numberofrows . PHP_EOL;
echo 'Count = '. $testfield1 ;
}
count_result(24);
?>
A silly mistake in your code :
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
echo "string</br>";
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['user']."asdasd</br>"; // did changes on this line
die("userssss");
$return = $row['user'];
return $return;
}

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
i'm getting the following error
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php
everything else work fine... except for this !
Here's my query :
<?php
$inputuser = $_POST["user"];
$inputpass = $_POST["pass"];
$user = "root";
$password = "";
$database = "share";
$connect = mysql_connect("localhost:3306",$user,$password);
#mysql_select_db($database) or ("Database not found");
$query = "SELECT * FROM 'users' WHERE 'username'= '$inputuser'";
$querypass = "SELECT * FROM 'users' WHERE 'password'= '$inputpass'";
$result = mysql_query($query);
$resultpass = mysql_query($querypass);
$row = mysql_fetch_array($result);
$rowpass = mysql_fetch_array($resultpass);
$serveruser = $row['user'];
$serverpass = $row['password'];
if ($serveruser && $serverpass) {
if (!$result) {
die ("Invalid Username/Password");
}
header('Location: Fail.php');
mysql_close();
if ($inputpass == $serverpass) {
header('Location: Home.php');
} else {
}
}
?>
Do not use mysql_* functions. They are deprecated.
You have an error in your SQL Syntax. Change your queries to this:
SELECT * FROM `users` WHERE `username`= '$inputuser';
SELECT * FROM `users` WHERE `password`= '$inputpass';
You must use backticks, ` and not ' quotes.
And please try to combine them like this:
SELECT * FROM `users` WHERE `username`= '$inputuser' AND `password`= '$inputpass';
What if there are two users with the same password? You cannot expect all the users to use different passwords right?
Other things. You are passing the user input directly to the SQL. This is very bad and leads to SQL Injection. So you need to sanitize the inputs before you can send it to the Database server:
$inputuser = mysql_real_escape_string($_POST["user"]);
$inputpass = mysql_real_escape_string($_POST["pass"]);
Again, do not use mysql_* functions.
Update the Code
Use the following code.
// single query
$query = "SELECT * FROM `users` WHERE `username`='$inputuser' AND `password`='$inputpass'";
// your original query
$query = "SELECT * FROM `users` WHERE `username`= '$inputuser'";
Final Code
<?php
$inputuser = mysql_real_escape_string($_POST["user"]);
$inputpass = mysql_real_escape_string($_POST["password"]);
$user = "root";
$password = "";
$database = "share";
$connect = mysql_connect("localhost", $user, $password);
#mysql_select_db($database) or ("Database not found");
$query = "SELECT * FROM `users` WHERE `username`= '$inputuser' AND `password`= '$inputpass'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
header('Location: Home.php');
die();
}
else {
header('Location: Fail.php');
die ("Invalid Username/Password");
}
?>

PHP registered user check

I have PHP + AS3 user login&register modul.I want to check registered user by username.But can't do it because I'm new at PHP.If you can help it will helpfull thx.(result_message part is my AS3 info text box.)
<?php
include_once("connect.php");
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";
mysql_query($sql) or exit("result_message=Error");
exit("result_message=success.");
?>
Use MySQLi as your PHP function. Start there, it's safer.
Connect your DB -
$host = "////";
$user = "////";
$pass = "////";
$dbName = "////";
$db = new mysqli($host, $user, $pass, $dbName);
if($db->connect_errno){
echo "Failed to connect to MySQL: " .
$db->connect_errno . "<br>";
}
If you are getting the information from the form -
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
you can query the DB and check the username and password -
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $db->query($query);
If you get something back -
if($result) {
//CHECK PASSWORD TO VERIFY
} else {
echo "No user found.";
}
then verify the password. You could also attempt to verify the username and password at the same time in your MySQL query like so -
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password';
#Brad is right, though. You should take a little more precaution when writing this as it is easily susceptible to hacks. This is a pretty good starter guide - http://codular.com/php-mysqli
Using PDO is a good start, your connect.php should include something like the following:
try {
$db = new PDO('mysql:host=host','dbname=name','mysql_username','mysql_password');
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your insert would go something like:
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES (?, ?, ?)";
$std = $db->prepare($sql);
$std = execute(array($username, $password, $userbio));
To find a user you could query similarly setting your $username manually of from $_POST:
$query = "SELECT * FROM users WHERE username = ?";
$std = $db->prepare($query)
$std = execute($username);
$result = $std->fetchAll();
if($result) {
foreach ($result as $user) { print_r($user); }
} else { echo "No Users found."; }
It is important to bind your values, yet another guide for reference, since I do not have enough rep yet to link for each PDO command directly from the manual, this guide and website has helped me out a lot with PHP and PDO.

PHP mysql_real_escape_string(); whats the correct method using mysqli?

its a little difficult to explain. I've build the mysql function which works fine and with the depreciation of mysql I will need to change this function to use mysqli rather than the mysql method.
I current have:
$con = mysql_connect("host", "username", "pass");
mysql_select_db("db", $con);
$Username = mysql_real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$Query = mysql_query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'") or die(mysql_error());
$Query_Res = mysql_fetch_array($Query, MYSQL_NUM);
if($Query_Res[0] === '1')
{
//add session
header('Location: newpage.php');
}
else {
echo 'failed login';
}
Now I've applied mysqli to this and it's not returning any data or errors but the function still complies.
$log = new mysqli("host", "user", "pass");
$log->select_db("db");
$Username = $log->real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$qu = $log->query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'");
$res = $qu->fetch_array();
if($res[0] === '1'){
//add session
header('Location: newpage.php');
}
else {
$Error = 'Failed login';
sleep(0.5);
}
echo $res['username'].' hello';
}
But I'm unsure on why this is wrong. I know it's probably a simply answer
Just to have it as an answer:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
e.g.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
You may check if the connection is establishing before using real_escape_string()
if ($log->connect_errno) {
echo "Failed to connect to MySQL: (".$log->connect_errno.")".$log->connect_error;
}
afaik, there's no problem with $log->real_escape_string($_POST['user']);

Categories