Checking SQL Database for value - php

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'");

Related

Php getting id of current user not working

I was trying to make a page where you can log in and then change your nickname or/and password. Everything in mySQL database, but when I try to save the id to session variable, it doesn't work. Any suggestions?
I am using XAMPP, users is my table in database users, I'm not posting login form code, because it's very simple.
Everything is connected, code doesn't give any warnings or errors.
login.php (fragment):
$sql = "SELECT * FROM users WHERE nickname = '$myusername' and pass = '$mypassword' and confirmed = 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$logged = true;
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"];
$_SESSION['currentId'] = $row["id"];
echo 'Id: ' . $_SESSION['currentId'];
}
}else {
$error = "Your Login Name or Password is invalid";
}
}
change.php (whole):
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Users";
$currentId = $_SESSION['currentId'];
if($currentId<1){echo 'No Id.';}
else {echo 'CurrentId: ';
echo $currentId;}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully <br>";
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$aCUname = mysqli_real_escape_string($conn,$_POST['CUname']);
$aCUpass = mysqli_real_escape_string($conn,$_POST['CUpass']);
$sql = "UPDATE users SET nickname = '$aCUname', pass = '$aCUpass' WHERE id = '$currentId';";
$result = mysqli_query($conn,$sql);
echo 'Updated successfully.';
}
?>
Thanks for help.
I got a solution. I just had to delete
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
from login.php. Thanks to #Shashikumar Misal !

Accessing two tables within same statement?

I'm trying to create an upvote system where, after checking to see if you're logged in and after getting your userid, it checks if the table has your userid with the postid already in it and if it does then it means it was already upvoted. I just want to know what's wrong in my code, this is being used for learning, I don't need any complex thing.
Code:
if (isset($_GET['upvote'])) {
if ($_SESSION["loggedin"] == true) {
$upvoteid = $_GET["upvote"];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM users WHERE username=".$_SESSION["loggedinusername"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userid = $row["id"];
}
$sql2 = "SELECT userid, postid FROM upvotedposts WHERE userid='".$userid."' AND postid='".$upvoteid."'";
$result2 = $conn->query($sql);
if (!$result2->numrows > 0) {
$sql = "UPDATE posts SET upvotes = upvotes + 1 WHERE id = ".$upvoteid;
if ($conn->query($sql) === TRUE) {
echo "Sucessfully upvoted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
} else {
echo "Failed;
}
$conn->close();
}
}
When I do click the upvote button, it simply does nothing. The issue here is that as far as I know it looks like it would work but I may be forgetting something that I am unaware of or incorrectly using something.
You are missing a closing "
echo "Failed;
should be:
echo "Failed";

Ajax post json response issue

I have an issue with ajax response. I am using custom query for fetch result from database. Json response always shows null value while query is running successfully. Here is my code:
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
while($fetch = mysql_fetch_array($query))
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
#Amandhiman i did not get what is the use of if statement with in the while
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
the mention code definitely works for you
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
Try with the below code, (mysql is deprected), working for me with my test database table (Debug it, var_dump $result, $result->fetch_assoc(), $result->num_rows)
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
else
{
$arr['failed']= "Login Failed try again....";
}
}
echo json_encode($arr);
}
try this
if(isset($_POST)){
$arr = array();
//$query = mysql_query(" insert into login (user,pass) values ('".$_POST['firstname']."','".$_POST['lastname']."') ") or die('test');
$query = mysql_query(" select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ") or die('test');
$rows = mysql_num_rows($query);
if($rows>0)
{
while($fetch = mysql_fetch_array($query))
{
$_SESSION['ID']= $fetch['id'];
$arr['id'] = $_SESSION['ID'];
}
}else
{
$arr['failed']= "Login Failed try again....";
}
echo json_encode($arr);
}
First of all start session before playing with it on the top of page
session_start();
check your database connectivity.
Use print_r($arr) for testing your array();
first off all you are using session variable . to use session variable you need to initialize it by session_start()
you are using key in the array in this way it will return the last inserted record in the array . try this code
<?php
$servername = "localhsot";
$username = "yourser";
$password = "passyour";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
if(isset($_POST)){
$arr = array();
$query = "select * from login where user = '".$_POST['firstname']."' && pass = '".$_POST['pass']."' ";
$result = $conn->query($query);
$rows = $result->num_rows;
while($fetch = $result->fetch_assoc())
{
if($fetch)
{
// if wants to use session then start session
session_start(); // else it will return null
$_SESSION['ID']= $fetch['id']; // i don't know why this ??
// $arr['id'] = $_SESSION['ID']; comment this
$arr[] = array('msg'=>'succsee','ID'=>$fetch['id']);
}
else
{
$arr[]= array('msg'=>'fail','ID'=>null);
}
}
echo json_encode($arr);
}

Having trouble pushing data from a sql query to an array for comparison

So I am trying to compare user input from a form with data from a database, first name, last name, and email. My problem has been comparing my results with the ones that the user put in. What I am trying to do is put the results from my query into an array and then compare each array item against the input of the user. Yet I can't get through my process. What am I doing wrong?
Thank you all in advance.
P.S. I am a php newbie so any suggestions would also be appreciated
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$email = $_POST['email'];
//query for the database to select the columns
$queryFirst = "SELECT firstname FROM users";
$queryLast = "SELECT lastname FROM users";
$queryEmail = "SELECT email FROM users";
//query results
$resultFirst = $conn -> query($queryFirst);
$resultLast = $conn -> query($queryLast);
$resultEmail = $conn -> query($queryEmail);
$firstResult = array();
$lastResult = array();
$emailResult = array();
array_push($firstResult, $resultFirst);
array_push($lastResult, $resultLast);
array_push($emailResult, $resultEmail);
$firstValid = mysqli_result::fetch_array($firstResult);
$lastValid = mysqli_result::fetch_array($lastResult);
$emailValid = mysqli_result::fetch_array($emailResult);
//comparing query results to user input
foreach($firstResult as $comp) {
if(strpos($firstname, $comp) !== false) {
$firstname = true;
} else {
return false;
}
}
foreach($lastResult as $comp) {
if(strpos($lastname, $comp) !== false) {
$lastname = true;
} else {
return false;
}
}
foreach($emailResult as $comp) {
if(strpos($email, $comp) !== false) {
$email = true;
} else {
return false;
}
}
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($firstname && $lastname && $email = true) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Okay so first thing as already told you andrewsi, you can get all the info in one query. But if you want to select only one row, you should use a WHERE clause telling what to look for.
Check this:
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user . addslashes is for security, so they won't break your query and potentially abuse it.
$firstname = addslashes($_POST['first']);
$lastname = addslashes($_POST['last']);
$email = addslashes($_POST['email']);
//query for the database to select the columns
$query = "SELECT firstname, lastname, email FROM users WHERE firstname = '$firstname' and lastname = '$lastname' and email = '$email'";
//query results
$result = $conn -> query($query);
$numRows = $result->num_rows;
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($numRows > 0) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Haven't tested it but the idea is to check for a match in the query, not afterwards. Then if there's a match, it will return at least one row (if you defined your table correctly it shouldn't be possible to have duplicates).
Then based on that you make your choice.

php query alwaysfalse no matter what

I have tried to read and do (incorporate) anything I find on here. But I have not found the solution. I'm using wamp server and I have a user table with 2 users one with email and password as test and test1 and no matter what I try the if statement always returns false.
<?php
$user = "root";
$pass = "";
$db = "testdb";
$db = new mysqli("localhost", $user, $pass, $db) or die("did not work");
echo "it connected";
$email = "test";
$pass1 = "test1";
$qry = 'SELECT * FROM user WHERE email = " '. $email .' " AND password = " '.$pass1.' " ';
$result = mysqli_query($db, $qry) or die(" did not query");
$count = mysqli_num_rows($result);
if( $count > 0)
echo " found user ";
else
echo " did not find user or password";
?>
I have tried to augment mysqli_num_rows but then it comes out always true
You have spaces in your query around your variables:
" '. $email .' "
change to:
"'. $email .'"
MySQL will take those spaces literally when it searches for matches.
I needed to eliminate the blank spaces in the encapsulation of the variable
<?php
$user = "root";
$pass = "";
$db = "testdb";
$db = new mysqli("localhost", $user, $pass, $db) or die("did not work");
echo "it connected";
$email = "test";
$pass1 = "test1";
$qry = 'SELECT * FROM user WHERE email = "'. $email .'" AND password = "'.$pass1.'"';
$result = mysqli_query($db, $qry) or die(" did not query");
$count = mysqli_num_rows($result);
if( $count > 0)
echo " found user ";
else
echo " did not find user or password";
?>
If you are using mysqli class version then you should use like below :
<?php
$user = "root";
$pass = "";
$db = "testdb";
$mysqli = new mysqli("localhost", $user, $pass, $db);
$email = "test";
$pass1 = "test1";
$qry = sprintf('SELECT * FROM user WHERE email = "%s" AND password = "%s"',$email,$pass1);
$result = $mysqli->query($qry);
$count = $result->num_rows;
if( $count > 0)
echo " found user ";
else
echo " did not find user or password";
$mysqli->close();
?>

Categories