MrMik MrMik - 5 months ago 9
PHP Question

PHP Register Script - check user exists not working

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.

Answer

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';
}