Here is my code:
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
}
//try to register the user
$result = query("INSERT INTO login (username, pass) VALUES('%s','%s')", $user, $pass);
if (! $result['error']) {
//success
login($user, $pass);
} else {
//error
//errorJson('Registration failed');
errorJson($result['error']);
}
}
function login($user, $pass) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
//authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
print json_encode($result);
} else {
//not authorized
errorJson('Authorization failed');
}
}
I call register with username and password and both fields in the DB are empty. The insertion takes place normally because the primary key which is auto incremented is being increased- just the fields are empty.
This is how I created my username.
CREATE TABLE `login` (
`IdUser` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`pass` varchar(45) NOT NULL,
PRIMARY KEY (`IdUser`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
and this is my query function:
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysql_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysql_query($sql, $link);
if (mysql_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysql_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
I have cheked that the $user, and $pass contain the correct value before executing the INSERT INTO.