I can't return MySQL data - php

here is my JS code:
$.ajax({
url: 'login.php',
type: 'POST',
data: {
loginName: $("#loginName").val(),
loginPass: $("#loginPass").val()
},
dataType: 'json',
success: function(data){
if(data.success){
$("#Message").fadeIn(function(){
$(this).html(data.message);
});
}
else
{
$("#Message").fadeIn(function(){
$(this).html(data.message);
});
}
}
});
and here is PHP:
<?php
$data = array();
$data['success'] = true;
$data['message'] = "Here is the message";
echo json_encode($data);
?>
If i have this its be all right, but if i edit the php file to this:
<?
include "db.php";
$data = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['loginName'] == "" && $_POST['loginPass'] == "")
{
#$v = mysql_query("SELECT * FROM users WHERE name LIKE '$registerName'");
#$p = mysql_num_rows($v);
if ($p == 0){
#$v = mysql_query("INSERT INTO users VALUES('','$registerName','$registerPass')");
$data['message'] = "Byly jste úspěšně zaregistrováni.";
$data['success'] = true;
}
else
{
$data['message'] = "Tento uživatel je tu již zaregistrován.";
$data['success'] = false;
}
echo json_encode($data);
}
?>
The ajax do nothing... its just send data but nothing to the alert... :(
and i control this mysql events and its works if i use just php...

Firstly i would like to welcome back little Bobby Tables
Now down to business, look at the following line of code closely:
if($_POST['loginName'] == "" && $_POST['loginPass'] == "")
Next on the agenda, Your error suppression is incorrect, you should control your errors using error_reporting on your config file, and use an error_handler to log the errors for your application.
You should also note that your only responding with a result if certain conditions are met, I would advise you to respond regardless of what data or post method, supply an error message for every possibility, As in development stages this would make things a lot easier.
This is how i would write the code:
include "db.php"; //error_reporting(0);
$data = array();
$user_info = array_map("mysql_real_escape_string",$_POST);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(!empty($user_info['loginName']) && !empty($user_info['loginPass']))
{
$v = mysql_query(sprintf("SELECT * FROM users WHERE name LIKE '%s'",$user_info['loginName']));
if(mysql_num_rows($v) > 0)
{
//Update Here
//Output Success here/ json_encode
exit;
}
}
}
//Output Error here/ json_encode

Why are you supressing errors? It's not even being done correctly:
#$v = mysql_query("SELECT * FROM users WHERE name LIKE '$registerName'");
For one, there's no point in supressing errors on an assignment - an assignment will always succeed. Putting the # on the other side would be useless as well. You'd have absoultely no indication if the query blew up on you. You're not checking if it failed at all. The code should be:
$result = mysql_query(...);
if ($result === FALSE) {
die(mysql_error());
}
Have you checked if your POST data is coming through properly? As it stands now, if neither of those POST fields is set, then your ajax response block is completely bypassed and the script will output nothing.

Related

Data Not inserting into table PHP

The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.

PHP MYSQLI Login Not Working

The Script Always Returns Failure(Regardless Of Correct/Incorrect User Information. Nothing Is Wrong with any other files. The Config File works and is just a starter of the sql connection and selects the database.
#include('../settings/config.php');
if (!#include('../settings/config.php')) {
die("<center>Login Failed</center>");
}
//======================================================================
// POST Check(Isset submit comes from html form)
//======================================================================
if(isset($_POST['submit'])) {
// Sanitize All POST Fields
$_POST = array_map('trim', $_POST);
$_POST = array_map('strip_tags',$_POST);
$login_form_user = $_POST['login_user'];
$login_form_pass = $_POST['login_pass'];
// Testing Only
echo("
<center>
Your Username is: $login_form_user!
<br>
Your Password is: $login_form_pass!
</center>
");
//======================================================================
// Input/Database Check
//======================================================================
$user_fetch = <<<LOGIN
SELECT `id` FROM `users`
WHERE `username`='$login_form_user'
AND `password`='$login_form_pass'
LIMIT 1
LOGIN;
$user_result = $sql_connection->query($user_fetch);
if(!$user_result) {
die("<center>Cannot Execute SQL Login Query</center>");
}
if ($sql_connection->num_rows == 1) {
echo("<center>User $login_form_user Exists</center>");
}
if($row = $user_result->fetch_assoc()) {
if(($row['username'] === $login_form_user) && ($row['password'] === $login_form_pass)) {
// Login Is Successful
echo("<center>Login Successful</center>");
} else {
echo("<center>Login Failed</center>");
}
}
} else {
// No Direct File Access Allowed
unset($_POST);
die('No Direct File Access Allowed!');
}
?>
Change:
if(($row['username'] === $login_form_pass)...
To:
if(($row['username'] === $login_form_user)...
You have typo error in this line please change it
if(($row['username'] === $login_form_pass) && ($row['password'] === $login_form_pass))
$row['username'] === $login_form_user// you are comparing it with $login_form_pass

Extra space/indent prepended to string being printed from php

I'm working on a REST api that people can download and throw on their server and use with little to no programming knowledge. https://github.com/evanstoddard/REST-Easy.
I'm using ajax for the setup page and php returns a string for ajax to see and decide whether to move on to the next step or tell the user to fix an error. It seemed to be working fine and then all of a sudden it won't go past the first step.
In my javascript I have the return value from php printed in my log. The first step is for the user to enter mysql server information such as the server url, username, and password. If a connection is created 'success' is returned. I appear to be getting ' success'. With a space or indent in there.
I commented out a lot of code I was working on before this error had occurred and the error is still there. I also added an extra indentation to my if block to check the return and the script succeeded so somewhere an extra bit is being added.
I don't really want to post my code here because there is A LOT of it and there are a bunch of moving parts which probably isn't the best way to go.
Here's a quick rundown of how this works:
User input(html form)->ajax->data handling php script->class_database.php(prints success->ajax->html
Applicable code:
Html:
<form onsubmit="stepTwo('#stepOneForm'); return false;" id="stepOneForm">
<input type="hidden" name="task" value="1" />
<input type="text" class="inputText" id="serverURL" name="serverURL" placeholder="MySQL Server:" /><br />
<input type="text" class="inputText" id="serverUsername" name="serverUsername" placeholder="Username:" /><br />
<input type="text" class="inputText" id="serverPassword" name="serverPassword" placeholder="Password:" /><br />
<input type="submit" class="blueButton" value="Connect" />
</form>
Javascript(AJAX):
function setupForm(form){
//console.log('Form function called.');
var formData = $(form).serialize();
$.ajax({
type: "POST",
url: "data/data_setup.php",
data: formData,
success: function(result) {
console.log(result)
function showAndTell(hide, show){
$(show).slideDown(600);
$(hide).delay(300).slideUp(600);
}
function showMessage(message, type, holdMessage){
var messageContainer = "#messageContainer";
var messageText = "#messageText";
var messageImage = "#messageImage";
var errorImage = "<img src='images/error.png' alt='Error' height='60px' width='60px' />";
var successImage = "<img src='images/success.png' alt='Error' height='60px' width='60px' />";
if (type === 'error'){
$(messageText).empty()
$(messageImage).empty()
$(messageText).append(message)
$(messageImage).append(errorImage)
$(messageContainer).slideDown(500)
if (!holdMessage) {
$(messageContainer).delay(7000).slideUp(500)
}
}
else if(type === 'success'){
$(messageText).empty()
$(messageImage).empty()
$(messageText).append(message)
$(messageImage).append(successImage)
$(messageContainer).slideDown(500)
if (!holdMessage) {
$(messageContainer).delay(7000).slideUp(500)
}
}
}
if(result === 'success'){
showAndTell('#stepOne', '#stepTwo');
showMessage('Successfully connected to MySQL database.', 'success');
}
else if (result === 'badaccess') {
showMessage('Unsuccessful. Please recheck information.', 'error');
}
else if (result === 'nserver') {
showMessage('Please enter a server URL.', 'error');
$('#serverURL').css('background', '#ffdadb');
}
else if (result === 'nserverusername') {
showMessage('Please enter a server username.', 'error');
$('#serverUsername').css('background', '#ffdadb');
}
else if (result === 'ndatabase') {
showMessage('No database with that name. Create it? Yes | No', 'error', true);
}
else if (result === 'database') {
showMessage('Successfully connected to that database.');
showAndTell('#stepTwo', '#stepThree');
}
else {
showMessage('Unknown error. Please try again later.', 'error');
}
}
});
}
PHP data handling script:
<?php
//Include rest class
require_once('../../classes/class_rest.php');
//Get variables
$task = $_POST['task'];
$database_server = $_POST['serverURL'];
$database_username = $_POST['serverUsername'];
$database_password = $_POST['serverPassword'];
$rest_name = $_POST['restName'];
$username = $_POST['username'];
$password = $_POST['password'];
$confPassword = $_POST['confirm'];
$emailAddress = $_POST['emailAddress'];
$api_name = $_POST['apiName'];
$database_name = $_POST['databaseName'];
$table_prefix = $_POST['tablePrefix'];
if ($task == 1){
if($database_server == ''){
print('nserver');
}
else if($database_username == ''){
print('nserverusername');
}
else{
connectSQL($database_server, $database_username, $database_password);
}
}
else if ($task == 2){
if($rest_name == ''){
print('nrest');
}
else{
databaseDoesExist($rest_name);
}
}
else if ($task == 3){
if($username == ''){
print('nuser');
die();
}
if($emailAddress == ''){
print('nemail');
die();
}
if(!$confPassword == $password){
print('nconf');
die();
}
insertUser($username, $emailAddress, $password);
}
else if ($task == 4){
}
else if ($task == 5){
}
else if ($task == 6){
}
else if($task == 9){
createInitialDatabase();
}
else if($task == 10){
createConfigFile();
}
?>
Function in class_database.php:
//Validates sql information
function connectSQL($server, $username, $password){
//Create sql connection
$con = mysqli_connect($server, $username, $password);
//Checks if connection was successful
if (mysqli_connect_errno($con)){
//Print 'badaccess' for ajax
print('badaccess');
}
//Run if connection successful
else{
//Print 'success' for ajax
print('success');
//Adds session variables for other sql commands later on
$_SESSION['server'] = $server;
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
}
Few comments to your handling script:
* make sure there's no white space before the opening <?php and as well, nothing after the trailing ?> which, btw, can be omitted as well (did you know?).
* what about so called BOM in case of UTF-8 codified source codes? You may wanna choose an editor or editor setting that doesn't write BOM at the beginning of UTF files.
* instead of, print('badaccess'); you might use die('badaccess'); – it will print the argument and stop the script execution.
* at require_once (and directives alike) it's recommended to omit the parenthesis
* consider rewriting long if...else statement dealing with $task to one switch().
it's easy to unintentionally leak a space from php code (space before in any included file), try ob_start() at the begining of "PHP data handling script" and ob_end_clean() just before "print('success')" at connectSql
After the ?> in one of my classes, there was an indent and that's what was causing my problems... programming sucks sometimes.

Failed to assign variable taken from database to json array

I try to get the data from database to display data via ajax but failed to worked. It's partially working because data from mysql make this thing failed to function.
Here is my funds_transfer_backend.php page. This page will assign variable to json array.
session_start();
if(!isset($_SESSION['myusername']))
{
header("Location: ../index.html");
die();
}
include("../connect.php");
$myusername = $_SESSION['myusername'];
$sql="SELECT client_id FROM `client` WHERE username='$myusername'";
$result=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_row($result)){
$id = $row['0'];
}
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
//echo "Please complete the form!";
$response = -1;
}
else {
// check account number exist
$query2 = "SELECT 1 FROM account WHERE id='$to_account_num' LIMIT 1";
if (mysqli_num_rows(mysqli_query($conn, $query2))!=1) {
//echo "Recipient account number is invalid!";
$response = -2;
}
else {
$query2 = "SELECT client.name, client.email FROM account JOIN client USING (client_id) WHERE account.id = '$to_account_num' LIMIT 1";
$result=mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$email = $row['email'];
}
$response = 1;
}
} // check account num else bracket
$display = array('response' => $response, 'name' => $name);
echo json_encode($display);
However if I remove 'name' => $name from array the #stage div will trigger like image below:
Here is my funds_transfer.php page
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
...other code goes here
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<div id="confirm" style="background-color:#FF7800; padding-left:20px; color: white;"></div>
I try to check the data from db whether it exist using manual form method="post" and I can see the name being echo. Any help is appreciated and thanks in advance.
When your response is -1, your $name variable is undefined. So php could show a warning (depending on your settings) and you are trying to add an undefined variable to your array. This will invalidate your output / json.
You can set for example:
$name = '';
at the start of your script or check whether the variable is set with isset($name) before you try to use it to avoid these problems.
There are of course other solutions, like outputting your -1 directly and exiting the script there.
I always initialize my variables.
$myusername = isset($_SESSION['myusername']) ? $_SESSION['myusername'] : false;
Then you can safely do:
if ($myusername) {} without throwing warnings.
I do this weather I get my data from a db, post/get/session or json/ajax.
It takes a little extra time upfront but removes dozens of errors in the back end so you net more time.

PHP and AJAX Log in validation

I need some help troubleshooting my code that's used for Log In validation. It's a combo of AJAX and PHP.
Here's the AJAX code that's directly in the login page.
<script language="javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.post("/ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val()
,rand:Math.random() } ,function(data)
{
if (data=='no')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Incorrect Username or Password.')
.addClass('messageboxerror').fadeTo(900,1);
}
);
}
else if(data=='yes')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Logging in.....').addClass('messageboxok').fadeTo
(900,1, function()
{
document.location='/mainpage.php';
}
);
}
);
}
else
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('User is already logged in.').
addClass('messageboxerror').fadeTo(900,1);
}
);
}
});
return false;
});
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
});
</script>
PHP CODE:
<?
//Log In credentials
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y'){echo "alreadyLogged"; exit;}
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate=mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
}
else
{echo "no";}
?>
To summarize this process, someone logs in and the PHP script checks
if the username and password is valid AND that the person is NOT logged in already - returns value of 'yes'
if the username and password is valid AND that the person IS logged in already - returns value of 'alreadyLogged'
Invalid username or password - returns value of 'no'
This gets passed to AJAX, which SHOULD display the correct messages based on the return values from the php script. For reference (using the above summary):
AJAX should return: Logging in...
AJAX should return: User is already logged in.
AJAX should return: Invalid Username or Password.
The problem is this: If someone logs in correctly and IS NOT already logged in, message 2 appears instead of message 1. (I think that message 1 may appear but it disappears so fast).
I think the culprit is AJAX but unfortunately I'm not as familiar with it as I am with PHP.
I think the problem is with your php code.Your ajax code looks fine
try this
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y')
{
echo "alreadyLogged"; exit;
}
elseif ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
}
I think it is the php problem,it occur an error and return the error message. if ajax_login.php does not return "yes" or "no" it will show the second message, whatever it returns.
Just need modify your PHP. try this :
//Log In credentials
// check if post if (isset($_POST)) {
// must initially to use check if on loggin
session_start();
// set variable post
$username = $_POST['user_name'];
$password = $_POST['password']; // change if use sha1 or md5
$rand = $_POST['rand'];
// check query database
$query = mysql_query("SELECT * FROM Users WHERE username='$username' AND password='$password'");
$user = mysql_fetch_array($query);
$row = mysql_num_rows($query);
if ($row > 0) {
if ($user['LOGGED'] == 'Y') {
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate = mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
} elseif ($user['LOGGED'] == 'N') { // you can use 'else'
echo "alreadyLogged";
exit;
}
} else {
// invalid value password and username
echo "no";
exit;
} }

Categories