Let me begin with stating that you are about to see that I am still using some Mysql code in this question. It is only because I am new to PDO and in an effort to troubleshoot, I wanted to make sure my sql and queries were working so I went with what I know. Once I get the function working and the scripts running, I will convert to PDO.
Heres the question I have. I am submitting a form that subscribes a user to a email list (database). It takes all their info and inserts it into a DB. So far this all works. My Call back function is then supposed to check to see if this user was already in the DB or not.
I was testing to see if a row got returned from the DB based off of the email column being set as a unique column. The problem is that even though the user is already in the DB, the sql returns a line saying "Duplicate entry", so my code is reading the line DUPLICATE ENTRY as a result. Can someone point me in the right direction?
My jQuery code...
$('#contForm').submit(function() { //contForm is the name of my form
var formData = $(this).serialize();
$.post('contact.php',formData,dispAdd); //dispAdd is the callback
function dispAdd(result) {
if (!result) {
$('#main').html('<div>Your have been added to the mailing list</div>');
} else {
if ($('#fail').length==0) {
$('#main').append('<div id="fail">This email address is already subscribed to our mailing list</div>');
}
}
}
return false;
});
My PHP/SQL script
function dispAdd()
{
$email= $_POST['email'];
$sql= "SELECT * FROM mailList WHERE email = '$email'";
$result= mysql_query($sql) or die(mysql_error());
$rows = array();
if(mysql_num_rows($result) > 0)
{
while ( $row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
echo json_encode( $rows );
}
After playing around a lil more I figd out how to make it work but if anyone has other tips or ideas Im happy to hear them. I learn a lot on here so Im welcome to all comments please. Here is how I made it work:
function dispAdd()
{
$email= $_POST['email'];
$sql= "SELECT * FROM mailList WHERE email = '$email'";
$result= mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) > 0)
{
while ( $row = mysql_fetch_assoc($result)) {
}
return;
}
}
Related
I am developing an adroid app and I faced some trouble about php web service.
I want to get user type information form database and according to the answer I will do some process in the background.
So in my authentication code there is a area like this to get usertype;
function getUserType(){
$sql = "SELECT `usertype` FROM `login_test` WHERE username = '". $this->username2."'
AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION, $sql);
if(mysqli_num_rows($result)>0){
return (?);
}
}
and my in my login code the message will be send here;
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'Access Granted';
$json['usertype'] = 'Client';
echo json_encode($json);
Here I dont know how to access a certain field called 'usertype' in my table (I am really new in php) and how to return the value that I got.
Any help will be apreciated
P.S = $userStatus returns ture.
You could try doing this:
$sql = "SELECT * FROM `login_test` WHERE username = '$this->username2' AND password = '$this->password2'";
$result = mysqli_query($this->DB_CONNECTION, $sql);
return $result->fetch_object()->userType;
While please do keep in mind to use prepared statements.
I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.
<?php
$con = mysqli_connect('localhost','root','[mypassword]','dbhwsource');
if(isset($_GET['username'])){
$username = $con->real_escape_string($_GET['username']);
$test = $con->query("SELECT username FROM users WHERE username='$username'");
if($test!=false) die("usererror");
}
if(isset($_GET['email'])){
$email = $con->real_escape_string($_GET['email']);
$test = $con->query("select * from users where email='$email'");
if($test!=false) die("emailerror");
}
$con->close();
echo "ok";
?>
So I'm just trying to check to see if the username / email is available or not, but all i get is "usererror" no matter what the input username is! I'm just frustrated and have searched for sample code everywhere and the code looks like there's nothing wrong with it. What am I doing wrong?
EDIT:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
This worked!
Since your query returns true, this line if($test!=false) die("usererror"); gets executed,
should be something like
$test = $con->query("SELECT username FROM users WHERE username='$username'");
$row_cnt = $test->num_rows;
if( $row_cnt > 0 ) {
//you already have user with this name, do something
}
$con->query returns a result object if the query was successful. This doesn't say anything about how many rows where found or whether the query matched anything, it just means the query executed successfully. Therefore your $test!=false test always succeeds; only in the case of a database error would it fail.
Do the query as SELECT COUNT(*) FROM ..., then fetch the first row of the result and see if the count is > 0.
I recently did something like this for an android app. you should really check this site out. It helped me tremendously. This is a detailed example of having a PHP API for an aplication. Specifically logging in.
To be specific though, here is a snippet from the page for the PHP
/*
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
This worked for me:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
Your code is really not secure not optimized anybody can login with sql injection in your code.
and your code is right as you are checking thar (test != false) it means it is true that's why your code og usererror is executing
here is some tips and always use this style for security and optimization
do same for $email
third after running the query do not check if it is true or false but check again after query
if($test->username === $_GET['username']) { do something }
check sql injections on Google why i did this
NOTE: UPDATE - Please Read
Please Read, updated code, much better:
Also, I added an ajax error function and it doesn't call an error, the first time I do it, but the next time it happens, an error occurs, and the third and fourth times, and so on.
I have some code that doesn't seem to be working, and the problem is probably located in the Ajax request or the PHP receiving function, and I don't know what the problem could be.
Here is the important code, ask for any other code that could also be of help to you.
Jquery Ajax request
$(document).ready(function()
{
$("#secretcoin").mouseover(function()
{
$.ajax(
{
type: "POST",
url: "achievements.php",
data: { Home_Coin_Locator: "Yes" },
error: errorAlert
});
});
});
Receiving side, PHP, which takes this info and stores it in a database:
$achieve4 = $_POST["Home_Coin_Locator"];
$astrSQL = "SELECT * FROM Awards_Inv WHERE Username = '$username'";
$rs3 = mysql_query($astrSQL, $connection);
if ($achieve4 == "Yes")
{
while($row3 = mysql_fetch_array($rs3)){
$soar4 = $row3["Home_Coin_Locator"];
if ($soar4 == "Yes")
{
$soa4 = "Yes";
}
else
{
$soa4 = "No";
$awardSTRsql = "UPDATE Awards_Inv SET 'Home_Coin_Locator' = 'Yes' WHERE Username = '$username'";
mysql_query($awardSTRsql, $connection) or die(mysql_error());
$updatestatsSTRsql = "UPDATE User_Info SET `Coins` = Coins + 120, `Skill Points` = Skill Points + 10, `Awards` = Awards + 1 WHERE Username = '$username'";
mysql_query($updatestatsSTRsql, $connection) or die(mysql_error());
}
}
}
else
{
}
Ok, so my code might be weird, but just try to read it and see what the problem is.
I guess any other advice is also accepted, thanks for looking, and I hope you find something!
I added an error callback function and combined 3 mysql queries into 1, but the problem still exists.
Finally, read this code for info about the $connection and $username variables
$connection = mysql_connect("mysql1.000webhost.com", "username hidden", "password hidden") or die (mysql_error ());
mysql_select_db("a7347456_usersdb") or die(mysql_error());
session_start();
$username = $_SESSION["Username"];
Another factoid:
The error is that the info does not get updated to database, as far as I know.
first thing, make sure that you required the config file witch identify the $connection variable. and it will be easier if you describe what the problem exactly is.
Ok, So I have Google the hell out of this problem and the FB Advanced Registration documentation also did not help. I want to have a Facebook Registration where a user can choose(& Check availability of) his username like this:
(Screenshot of what I plan to do but have failed to do, since I cant post picturesin this question directly)
A link to Screenshot of what I wanted!
I plan to check the availability of the username from my DB in mysql using PHP, but I am stuck with this weird JSON callback thing which I have failed to understand.
My Registration Plugin looks something like this
<fb:registration
fields='[{"name":"name"},{"name":"username","description":"Username","type":"text"}]'
onvalidate="validate_async"
redirect-uri="http://mysite.com/loginFB.php"
fb_only="false"
width="530">
</fb:registration>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
function validate_async(form, cb) {
// $.getJSON('https://graph.facebook.com/' + form.username + '?callback=?',//CODE obtained from FB documentation
$.getJSON('https://mysite.com/checkUsername.php?username=' + form.username + '?callback=?',
function(response) {
if (response.error== "false") {
// Username isn't taken, let the form submit
cb();
}
cb({username: 'That username is taken, Sorry!'});
});
}
</script>
I wanted to know WHAT EXACTLY do I write the in the checkUsername.php.
Right now I have come up with the following code for checkUsername.php which does NOT work:
<?php
$conn = dbconnect(GLOBAL_Db);
$username = $_GET['username'];
$data = array();
$table = mysql_real_escape_string(GLOBAL_Db. "." . GLOBAL_Users);
$sqlCommand = "SELECT * FROM ".$table." WHERE username='$username'";
$query = mysql_query($sqlCommand) or die (mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows>0){
$data['error'] = "true";
} else {
$data['error'] = "false";
}
echo json_encode($data);
?>
This code does not give me that that "The username is taken, Sorry" Message , WHY???
I would really appreciate it if anyone could actually help me out with this getJSON function in the script , AND Also help me out with the checkUsername.php since I have a very crude knowledge of JSON, (JSONP) etc. !
Would be glad to put in more effort to explaain my problem coz this is bugging me for like a Week now!
Happy to accept some valuable help from you guys!
$username = $_GET('username');
$_GET is not a function … maybe you should familiarize yourself with some PHP basics first?
Besides that, your script logic looks a bit weird …
if($num_rows>0){
$data['error'] = "true";
} else {
$data['username'] = $row['username'];
}
If now rows are found, then you want to access the username field in a row that’s not there?
(And you’re not even quoting the username you get as a GET parameter, OMG …)
Set error to true or false depending on if there are rows or none.
And then, in your JS function, give the „username is taken”-message if error=true.