Trying to send data through ajax to php - php

So I'm trying to create some code that checks if a username is taken. I'm kind of half there and having trouble. I'm new to it and trying to learn how to do it & the code will be messy.
the jquery:
$('#signusername').keyup(function()
{
var username=$('#signusername').val();
if(username != ''){
$.post('username_check.php', {signusername :username}, function(result)
{
if(result==''){
$('.error').text('Avaliable');
} else{
$('.error').text('Taken');
}
}
);
}else{
$('.error').text('???');//this is the the only thing that outputs correctly
}
the php:
function checkUsername($signusername, $conn) {
$stmt = $conn->prepare("SELECT * FROM user_info where username= '".$signusername."'");
$stmt->bindParam(1, $signusername);
$stmt->execute();
if($stmt->rowCount() == 1) {
return TRUE;
}
};
if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
$signusername= $_POST['signusername'];
checkUsername($signusername, $conn);
$result='';
if(checkUsername($signusername, $conn) == TRUE){
$result='';
}else{
$result='';
}
echo $result;
};
I use the same code to check if the username is taken when the form is submitted so I don't think that is the problem. I assume I'm doing something wrong with moving the username variable across? Hope you can help.

Check your console for syntex error }; remove semicolon after }
Also remove function calling two time and you sending result blank in both condition so send some response back to ajax in also fail condition
if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
$signusername= $_POST['signusername'];
$result='';
if(checkUsername($signusername, $conn) == TRUE){
$result='user found';
}else{
$result='user not found';
}
echo $result;
}

Try this code
function checkUsername($signusername, $conn) {
$stmt = $conn->prepare("SELECT * FROM user_info where username= '".$signusername."'");
$stmt->bindParam(1, $signusername);
$stmt->execute();
if($stmt->rowCount() == 1) {
return TRUE;
}
return false;
};
if(isset($_POST['signusername']) && !empty($_POST['signusername'])){
$signusername= $_POST['signusername'];
$result = checkUsername($signusername, $conn);
if($result != TRUE){
$result='';
}else{
}
echo $result;
};

Related

Weird PHP responses in subdomain

I am trying to make a website that echos out a number or a word based on some conditions. I connected it to my database, but it always echos out 2 (user not found), instead of yes100 (password and username correct).
The weird thing is, it works on my main domain, where it outputs yes100, but here it just can not do that for some reason.
I am sure my database details are correct, and I have uploaded the file where it should be.
This is my code (not secure at all, but it is for personal use only.)
$result = $link->query($sql);
if ($result->num_rows > 0) {
// Outputting the rows
while($row = $result->fetch_assoc())
{
$password = $row['password'];
$salt = $row['salt'];
$plain_pass = $_GET['password'];
$stored_pass = md5(md5($salt).md5($plain_pass));
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
if($stored_pass != $row['password'])
{
echo "BLAHAHAHAHAHAHAHAHA";
exit();
}
else
{
echo "yes"; // Correct pass
}
if (strlen($row['hwid']) > 1)
{
if ($hwid != $row['hwid'])
{
echo "0"; // Wrong
}
else
{
echo "100"; // Correct
}
}
else
{
$sql = "UPDATE ". $tables ." SET hwid='$hwid' WHERE username='$user'";
if(mysqli_query($link, $sql))
{
echo "rdy"; // HWID Set
exit();
}
else
{
echo "4"; // Else errors
exit();
}
}
}
}
else
{
echo "2"; // User doesn't exist
exit();
}
?>
I forgot to give the user the permissions. It works now. Thanks everyone.

SELECT returning wrong information

Alright so, I made this little account check using simple SQL & PHP but it seems to return false instead of true if account exists.
public function ifExists($name) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($name);
$result = $sql->query("SELECT ime FROM users WHERE ime='".$name."'");
if($result == false) {
if($result->num_rows != 0) {
$echo = 'account exists';
return true;
}
else {
return false;
}
}
}
And now here is the check
if($result->num_rows != 0) {
$echo = 'account exists';
return true;
}
else {
return false;
}
There is a row with ime='toma' in the sql
if($result == false)
query() only returns false on a syntax error. Also, this is backwards. You should only want to run the code if it's not false. Drop that if block out and it should work

get no results for query. its not true,not false and to null

i did some query to check username and password.
when i enter the right data its working ok,
if i put the right email and wrong password its working ok,
when i put a username that do not exist i get no results and white screen. now echo command jump. its looks like its stuck and there is no error.
any idears?
if (isset($email) && isset($password)) {
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE user_email = '{$email}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row["user_password"] == $password) {
echo json_encode($row);
} else {
echo ('{"user_id":"0","user_name":"","user_email":"","user_password":"","register_date":"2016-03-05","confirm":"0"}');
}
}
} else {
echo("error");
}
} else {
echo($result);
echo("Missing Vars");
}
I bet that "if ($result)" is true but it never enters the while loop since there are no rows to iterate over. This would lead to a blank screen. Try echoing out what is returned from the database and echoing out each nest to see what gets output. Like the following:
if ($result) {
echo("if $result must be true because I made it in");
while ($row = mysqli_fetch_assoc($result)) {
echo("I made it in the while loop if there are rows in my result");
if {
echo("I made it in while's if");
...
} else {
echo("I made it in while's else");
...
}
}
} else {
echo("if $result must be false because I didn't make it in");
echo("error");
}
I bet that using the above example you'll see:
if $result must be true because I made it in
And that is all you'll see

Displaying a message when resultset is empty

In the following code, if the resultset is empty, the code continues to process the result. What I want instead is to just display "Query failed." when there are no results.
$connInfo = array('UID'=>$user, 'PWD'=>$passwd, 'Database'=>$database);
$dbconn = sqlsrv_connect($server, $connInfo);
if($dbconn === false){
die("<br />Error connecting to the database.<br />");
}
//SQL Query
$query = "SELECT ... FROM somehwere";
//Run Query
$qresult = sqlsrv_query($dbconn, $query);
if($qresult === false) {
die('Query failed.');
}
?>
...more code...
$qresult will contain an empty result set if no rows are found, but it still won't evaluate to false.
Try this function instead:
http://www.php.net/manual/en/function.sqlsrv-num-rows.php
So:
if(!sqlsrv_num_rows($qresult)) {
die('Query failed.');
}
Instead of:
if($qresult === false) {
die('Query failed.');
}
It does not display "Query Failed" because the query has not failed. It just returns 0 rows. So, the solution will be to use:
$row_count = sqlsrv_num_rows( $qresult);
if ($row_count > 0){
// display stuff
}
else{
// throw exception
}
Thanks. I got it to work using sqlsrv_has_rows() function.
if($qresult !== NULL) {
$rows = sqlsrv_has_rows($qresult);
if($rows === true) {
//display success
} else {
//display error
}
}
For some reason I couldn't get the sqlsrv_num_rows() to work properly for me.

php error for registering a user

Im getting this error in a basic register script:
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/func/user.func.php on line 23
The part of the register.php that's giving me the error is:
<?php
include('init.php'); // user.func.php is included in this file
include('template/header.php');
?>
<h3>Register</h3>
<?php
// Typical $_POST stuff here, down the line the next line is where the error happenes. Also, $register_email below is equal to $_POST['register_email'];
if(user_exists($register_email)) { ***THIS FUNCTION IS WHERE THE PROBLEM IS. THE ACTUAL FUNCTION IS DEFINED BELOW***
$errors[] = 'That email has already been registered';
}
The function from user.func.php that's giving me the error is:
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
return (mysql_result($query, 0) == 1) ? true : false; // ***THIS LINE RIGHT HERE***
}
Any ideas on what might be causing this error. It's an annoying error. Not the first time I've gotten that one.
UPDATE
Thanks for the answers, I've tried each one and I'm getting the exact same error. Here's the full register.php so far:
<?php
include('init.php');
include('template/header.php');
?>
<h3>Register</h3>
<?php
if(isset($_POST['register_email'], $_POST['register_name'], $_POST['register_password'])) {
$register_email = $_POST['register_email'];
$register_name = $_POST['register_name'];
$register_password = $_POST['register_password'];
$errors = array();
if(empty($register_email) || empty($register_name) || empty($register_password)) {
$errors[] = 'All fields required';
} else {
echo 'OK';
}
if(filter_var($register_email, FILTER_VALIDATE_EMAIL) == false) {
$errors[] = 'Email address is not valid';
}
if(strlen($register_email) > 255 || strlen($register_name) > 35 || strlen($register_password) > 35) {
$errors[] = 'Ayo, quit tampering with the html';
}
if(user_exists($register_email)) {
$errors[] = 'That email has already been registered';
}
}
if(!empty($errors)) {
foreach($errors as $error) {
echo $error.'<br />';
}
} else {
}
?>
Now, I must say first that I'm not a mysql specialist and I normally use a DB class (so should you.) But if you are saying that return (mysql_result($query, 0) == 1) ? true : false; line is giving you an error. It means that the line above is not working. Meaning that it is not returning a resource.
You should first debug your function..
function user_exists ($email) {
$email = mysql_real_escape_string($email);
if (!mysql_select_db("users")) {
echo 'Could not select "users" DB.<br />Error: ' . mysql_error();
}
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'");
echo 'The count is currently: '$query['count'];
// return (mysql_result($query, 0) == 1) ? true : false;
}
If it says that it couldn't select the users DB. Then the problem is in your connections. As I said, I'm no pro. But you should probably connect it like this:
$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
Now you can try this:
function user_exists ($email) {
global $conn;
$email = mysql_real_escape_string($email);
if (!mysql_ping($conn)) {
echo 'Could not ping the mysql. Connection is lost probably :(';
}
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
echo 'The count is currently: ' . mysql_result($query, 0);
// return (mysql_result($query, 0) == 1) ? true : false;
}
If the code is been debugged and connection is AWESOME! Then:
function user_exists ($email) {
global $conn;
if ($email) {
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
if (mysql_result($query, 0)) {
return true;
}
}
return false;
}
Or:
function user_exists ($email) {
global $conn;
if ($email) {
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
if ($result = mysql_fetch_array($query)) {
if ($result['count'] == 0) {
return true;
}
}
}
return false;
}
If you look in the manual, mysql_query() can return a ressource (thats what you expect) OR FALSE if an error occur.
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
Change to:
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT email FROM users WHERE email = '$email'");
if (false === $query) return false;
return (mysql_num_rows($query) == 1);
}
use
function user_exists($email) {
if(isset($email){
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
$result = mysql_result($query,0);
if($result ===false) {
//error occur with the sql statement
//handel the error
}
else
return ($result == 1) ? true : false; // ***THIS LINE RIGHT HERE***
}
}
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
//return (mysql_result($query, 0) == 1) ? true : false; // ***THIS LINE RIGHT HERE***
if( $query ) return ( mysql_result($query, 0) != "" ) ? true : false;
}

Categories