I have a problem with using jQuery validate remote function with php. I try to check the user id with query whether the user id is exist or not. But it alway show user is in used.
Here is my jQuery validate code:
userID: {
required: true,
minlength: 5,
remote : {
url: "checkUserId.php",
type: "post"
}
},
Here is my php checking code:
<?php
include "session.php";
include 'dbConnect.php';
global $conn;
$requestedID = $_POST['userID'];
$query = "SELECT * FROM Users WHERE _userID = '$requestedID'";
$result = sqlsrv_query($conn,$query);
$row_count = sqlsrv_num_rows($result);
if($row_count === false){
echo 'false';
}
else if($row_count >=0){
echo 'true';
}
?>
Anything I did wrong in my query?
Change your if else condition.
if($row_count == 0){
echo 'true';
}else{
echo 'false';
}
true = not exist, false = exist
I had successfully solved it with this code. Thanks for all the support.
Here is my updated code:
<?php
include "session.php";
include 'dbConnect.php';
global $conn;
$requestedID = $_REQUEST['userID'];
$query = "SELECT * FROM Users WHERE _userID = '$requestedID'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query($conn,$query , $params, $options);
$row_count = sqlsrv_num_rows($result);
if($row_count >= 1){
echo 'false';
}
else{
echo 'true';
}
?>
Related
I have a very simple use case where I am checking if a certain value is present in the table and it always seems to fail.This is my php code.
<?php
include "config.php";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$device_id = $_POST["device_id"];
$check = "SELECT magazine_id FROM registered_buyers WHERE device_id = $device_id";
$rs = mysqli_query($con,$check);
if(mysqli_num_rows($con,$rs) == 0)
{
$jsonarray = $_POST["jsonarray"];
echo "This will be inserted".$jsonarray;
}else
{
echo "User already registered";
}
?>
Can anyone please point out my mistake.Any help or suggestion is welcome.Thank you.
You can try to follow this code.
<?php
include "config.php";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con){
echo "Connection Error".mysqli_connect_error();
}
$device_id = $_POST["device_id"];
$check = "SELECT magazine_id FROM registered_buyers WHERE device_id = ".$device_id;
$rs = mysqli_query($con, $check);
if(mysqli_num_rows($rs) == 0){
$jsonarray = $_POST["jsonarray"];
echo "This will be inserted".$jsonarray;
}else{
echo "User already registered";
}
?>
since i dont have enough rep to add a comment, i will consider the device_id is string, if so try something like this:
"SELECT magazine_id FROM registered_buyers WHERE device_id = '$device_id'";
add '
I have the following code to check if a row exists in MySQL:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT 1 FROM files WHERE id='$code' LIMIT 1");
if (mysql_fetch_row($result)) {
echo 'Exists';
} else {
echo 'Does not exist';
}
}
?>
This works fine. But I need to change it a bit. I have the following fields:
id, title, url, type. When someone uses the code above ^ to check if a row exists, I need a variable to get the url from the same row, so I can redirect the user to there.
Do you have any idea how I can do that?
Thanks in advance! :)
Try this:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT * FROM files WHERE id=" . $code . " LIMIT 1");
if (mysql_num_rows($result) > 0) {
while($rows = mysql_fetch_array($result)) {
echo 'Exists';
$url = $rows['url'];
}
} else {
echo 'Does not exist';
}
}
?>
It is quite simple. I think you don't show any effort to find the solution by yourself.
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT url FROM files WHERE id='$code' LIMIT 1");
if ($result) {
$url = mysql_fetch_row($resultado);
} else {
echo 'Does not exist';
}
}
<?php
$sql_query = "SELECT * FROM test WHERE userid ='$userid'";
$result1 =mysql_query($sql_query);
if(mysql_num_rows($result1)>0){
while($post = mysql_fetch_array($result1))
{
$url = $post['url'];
}
}
?>
If mysql_num_rows($result1)>0 it means row is existed fir the given user id
I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */
I'm trying to make it easy for me to request json output using jquery from php/mysql. Right now I'm using the below. Can anyone recommend a better way??
/do.php?username=bob
<?php
$str = $_SERVER['QUERY_STRING'];
if($str != ''){
if(preg_match("/username/",$str)){
parse_str($str);
$json = json_encode(checkUserName($username));
echo $json;
}
}
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
$countUser = mysql_fetch_row($findUsername);
if($countUser[0] < 1){
return array('username' => 'false');
}else{
return array('username' => 'true');
}
$db->disconnectDB();
}
?>
I get back a clean {'username':'false'} or {'username':'true'} which works for what I need; but is there a better way in PHP to do this?
Wow - amazing answers! I dumped my old db class and replaced it with:
<?php
function db_connect(){
$dbh = new PDO("mysql:host=localhost;dbname=thisdb", "dbuser", "dbpass");
return ($dbh);
}
?>
Then in my do.php script I made this change:
<?php
if(isset($_GET['username'])){
header('content-type: application/json; charset=UTF-8');
echo json_encode(checkUserName($_GET['username']));
}
function checkUserName($v){
$dbh = db_connect();
$sql = sprintf("SELECT COUNT(*) FROM user WHERE username = '%s'", addslashes($v));
if($count = $dbh->query($sql)){
if($count->fetchColumn() > 0){
return array('username'=>true);
}else{
return array('username'=>false);
}
}
}
?>
and my jquery is:
function checkUserName(str){
$.getJSON('actions/do.php?username=' + str, function(data){
var json = data;
if(json.username == true){
// allowed to save username
}else{
// not allowed to save username
}
});
}
$str = $_SERVER['QUERY_STRING'];
if($str != ''){
if(preg_match("/username/",$str)){
parse_str($str);
$json = json_encode(checkUserName($username));
echo $json;
}
}
This can be written so much easier by using $_GET superglobal:
if (isset($_GET['username'])) {
echo json_encode(checkUserName($_GET['username']));
}
Inside checkUserName():
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
You should escape $v properly:
$sql = sprintf("SELECT COUNT(*) FROM user WHERE username = '%s'", mysql_real_escape_string($v));
$findUsername = mysql_query($sql);
Better yet, learn PDO / mysqli and use prepared statements.
$db->disconnectDB();
Unless you're using persistent connections, you don't need this statements. If you do, you should keep the return value inside a variable first and only return after the disconnect.
I don't know what's your DB class, but this looks prettier.
<?php
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
$countUser = mysql_fetch_row($findUsername);
$db->disconnectDB(); // no code after "return" will do effect
return ($countUser[0] != 0); // returning a BOOL true is better than a string "true"
}
// use addslashes to prevent sql injection, and use isset to handle $_GET variables.
$username = isset($_GET['username']) ? addslashes($_GET['username']) : '';
// the above line is equal to:
// if(isset($_GET['username'])){
// $username = addslashes($_GET['username']);
// }else{
// $username = '';
// }
echo json_encode(checkUserName($username));
?>
By your way, If you want to process the json data in jquery you can do like this
$.ajax({
type:"POST",
data:'username=bob',
url: "do.php",
success: function(jsonData){
var jsonArray = eval('(' + jsonData + ')');
if(jsonArray.username == 'true'){
// some action here
}else if((jsonArray.username == 'false')){
// someother action hera
}
}
},"json");
If you want a fix just replace your checkUsername function with this one:
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT username FROM user WHERE username = '$v' LIMIT 1");
if(mysql_num_rows($findUsername))
return array('username' => mysql_result($findUsername,0));
else
return array('username' => 'false');
}
Or a simplier way:
if(isset($_GET['username'])){
$db = new DB();
$db->connectDB();
$query = mysql_query(sprintf("SELECT username FROM user
WHERE username='%s'",
mysql_real_escape_string($_GET['username'])
);
if(mysql_num_rows($query))
$json = array('username'=>mysql_result($query,0));
else
$json = array('username'=>false);
header('content-type:application/json');
echo json_encode($json);
}
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;
}