Form validation with JQuery and PHP not working - php

I am validating my form using jquery and after the form is left with no errors, I want to insert the data into the database but for some reasons, it is not working properly. Can you help me find out my mistake. Thanks,
The JQuery is
$.post('register_user.php',
{
'name' : name,
'email' : email,
'password': password
},
function(data) {
if(data == "success"){
alert("success");
} else if(data == "fail"){
alert("fail");
}
});
THE PHP
$name = $_POST['name']; //else assign it a variabl
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT email FROM users WHERE LOWER(email) = '" . $email . "'";
$result = mysql_query($sql) or die("Could not get email: " . mysql_error());
if(mysql_num_rows($result) > 0) {
//email is already taken
}
else {
$query = mysql_query("INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')") or die(mysql_error());
$result2 = mysql_result($query);
if((mysql_affected_rows($result2) ==1){
echo 'success';
} else {
echo 'fail';
}
}

I dont have enough rep yet to comment, so I'll have to put this as an answer.
Step 1:
Echo (or print) out what you can.
Add echo inside your logic, like where you have: //email is already taken
Also echo out the POST variables.
If they all look OK, you should try to echo out your queries.
Eg. copy your query line that is like:
$query = mysql_query("INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')")
Then paste it and change it to:
echo "INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
Then if this looks bad, it's your query.. You can of course test the output in mysql directly via phpmyadmin or ssh to your server and run the commands through the console (if they give you shell access)
If you manage to get this to work, as some others commented: mysqli or pdo should be your next steps. You also need to do some basic stuff, even though that will take care of mysql injection.
You are still vunerable to XSS and also simply things like whitespace at the end of the email (users often get this, when they copy stuff and insert it into forms).
You can solve some of it by some helper functions you make in PHP, like:
function cleanData($data) {
return strip_tags(trim($data));
}
That was a very simple sample by me, you can also add other parameters to the function, like casing. Then you can switch the casing and do strtolower, strtoupper, ucwords(strtolower(, etc. And you can then simply wrap your variables inside the function :-)
Btw. E-Mail I would check with regular expressions. Also dont let JS / client side code do the input validation, as it's very easy to manipulate the DOM, or even post from an alternative source. You have to think of this data as "dirty", as it's easy to tamper with.

Related

How to insert a new record to the table created in mysql

I created a table in mysql as'cus_info'. It has columns as 'iD' 'NAME' 'PASSWORD' 'eMAIL'. iD column is auto increment. I want to insert a new row to this table when a new customer registered. For that I wrote the following code in PHP
<?php
error_reporting(0);
require "init.php";
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."');";
if(!mysql_query($con, $sql)){
echo '{"message":"Unable to save the data to the database."}';
}
?>
but always I get the message as "unable to save data to the database"
Could you please tell me where I have gone wrong?
Thanks in advanced.
Could you please tell me where I have gone wrong?
In more than one place.
To most directly answer your question, you can use mysql_error() to print the error you're getting from mysql. To even more directly answer it, you have swapped the order of the parameters and you don't need the semicolon to be included in the query. (See example code here.)
You shouldn't be using PHP's "mysql_*" functions, which were deprecated in PHP5.5 and even removed in PHP7. You also should not be passing user input from a form directly into a MySQL database without any cleaning.
First show your $con and then put error_reporting(1) to check if other error occurs.
And finnaly copy and replace in your code.
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."')";
Try This
<?php
error_reporting(0);
require "init.php";
if(isset($_REQUEST["save"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = mysql_query("INSERT INTO `cus_info` (`name`,`password`,`email`) VALUES ('$name','$password','$email')");
$values=mysql_insert_id();
if($values!='')
{
echo '{"message":"Successfully save the data to the database."}';
}
else
{
echo '{"message":"Unable to save the data to the database."}';
}
}
?>

Entries to the database automatically after reload the web site

( Sorry for my bad english )
I am new to PHP. I have two input fields. One for the username and one for the comment. My problem is when I Reloaded my page that simply blank entries I posted my table. Why is that?
Existing Code :
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
Seeing that your code is coming from a POST form, you can use a conditional statement around it.
For example, in your HTML form:
<input type="submit" name="submit" value="Submit" />
then use:
if(isset($_POST['submit'])){
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
}
another thing is to make sure that fields are not left empty, using empty() I.e.:
if(empty($_POST['username'])){
echo "Enter a username.";
exit;
}
also isset(). I.e.:
if(isset($_POST['username'])){
// do something
}
You can also use a header("Location: http://www.example.com/page.php");
but make sure there is nothing else above your PHP, echo, HTML, etc.
In regards to your present code:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements, it's much safer.

Values are not being added to the database

I am very new to PHP and Mysql. I have made a registeration form but the values being inputted are not being saved in my database. I don't know why. I am connected to the database. Could anyone give me some insight? By the way, I know you are going to say "Mysql" is deprecated. But I am just starting out and learning how all of this works. As soon as I have a thorough understanding of the processes I am going to change my code to Mysqli...
<?php
//form data
$submit = strip_tags($_POST['submit']);
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$usernamereg = strip_tags($_POST['usernamereg']);
$passwordreg = strip_tags($_POST['passwordreg']);
$email = strip_tags($_POST['email']);
$emailcheck = strip_tags($_POST['emailcheck']);
$date = date("Y-m-d");
if($submit)
{
//check for existence
if($fname&&$lname&&$usernamereg&&$passwordreg&&$email&&$emailcheck)
{
//encrypt password
$password = md5($passwordreg);
if(strlen($usernamereg)>25)
{
echo "Username must be 25 characters or less.";
}
else
{
//checks password length
if(strlen($passwordreg)<6)
{
echo "Passwords must be atleast 6 characters long";
}
else
{
if($email!=$emailcheck)
{
echo "emails to not match";
}
else
{
//open database
$connect = mysql_connect("localhost","root","clandestine");
mysql_select_db("user_db"); //selects database
$queryreg = mysql_query("INSERT INTO users VALUES('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
echo "You have been registered!";
}
}
}
}
else
echo "Please fill in <b>all</b> fields!";
Try assigning the columns in the INSERT query.
$queryreg = mysql_query("INSERT INTO users (`randomField`, `date`, `first_name`, `last_name`, `username`, `password`, `email`, `email_check`) VALUES ('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
What is the first column supposed to be?
Have you done any sanity checking? (ie, printing test data to the screen at certain points in the code to make sure your IF statements are evaluating to true?
Additionally, try saving your INSERT query as a variable string:
$query = "INSERT INTO.............";
and then printing it to the screen. Copy and paste that query into PHPMyAdmin (if you have access to it) and see if there are any errors with your statement. PMA will tell you what errors there are, if any.
EDIT: Also, please don't ever MD5 a password or other highly sensitive data. Use a secure algorithm and salt the password. If you're unsure of what this all means:
refer to this link
What do you get if you do:
$query = "INSERT INTO users
(date, first_name, last_name, username, password, email, email_check)
VALUES
('$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck')";
mysql_query($query)or die('Error: <br />'.$query.'<br />'.mysql_error());
Note the removal of the backticks was just to simplify the code. It's correct to leave them in but with no spaces etc in your column names it should work anyway. Oh, and this is NOT good practice for production, of course. Just really clear debug.

What is wrong with this MySQL insert statement?

The form is ok and it captures all of the information correctly, however, the errors started when I used a function to generate a random string that is used for user activation.
function generateActivationString() {
$randomSalt = '*&(*(JHjhkjnkjn9898';
$uniqId = uniqid(mt_rand(), true);
return md5($randomSalt.$uniqId);
}
if (!get_magic_quotes_gpc()) {
// $_POST['pass'] = addslashes($_POST['pass']);
$username = addslashes($_POST['username']);
$firstname = addslashes($_POST['firstname']);
$surname = addslashes($_POST['surname']);
// $_POST['email'] = addslashes($_POST['email']);
$email = mysql_real_escape_string(addslashes($_POST['email']));
$pass = mysql_real_escape_string(sha1($_POST['pass']));
$activationString = generateActivationString();
}
$insert = "INSERT INTO users (username, password, firstname, surname, email, activation_string)
VALUES ('".strtolower($username)."', '".$pass."', '".strtolower($firstname)."', '".strtolower($surname)."', '".strtolower($email)."', '".$activationString."')";
Here is the echoed insert statement:
INSERT INTO users (username, password, firstname, surname, email, activation_string) VALUES ('', '', '', '', '', '')
I know it has created a new entry as the auto_increment id row is populated however al of the other fields remain empty.
Here is the code from the generateActivationString() so I know that's working too! - 264361eeb6e75d3934ce249a0d05f2c1
Any suggestions are more than welcome and greatly appreciated!
Going strictly by the code above, your variables like $username,$password etc are in the scope of your if block, move them outside of the if.
I don't see you send that query anywhere, maybe that's your problem...
Oh dear. The biggest problem with your statement is that you are not using prepared statement and taking info directly from the POST parameters. This is a recipe for disaster and how most sites get hacked.

code sometimes does not insert the mysql query

This code was designed to upload files from a flash javascript uploader plugin.
It doesn't give me an error but sometimes it does not insert the mysql query.
P.s: every posted variable is cleaned up via javascript (just alphanumeric text)
<?php
include 'a/inc/db.php';
if (!empty($_FILES))
{
$tempFile = $_FILES['Filedata']['tmp_name'];
if (substr($_FILES['Filedata']['name'],-3)!='mp3')
{
echo 'ERROR: your file was not an mp3';
die();
}
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_POST['folder'] . '/';
$titlepost = $_POST['title'];
$tagspost = $_POST['tag'];
$artist= $_POST['artist'];
$i= $_POST['i'];
$targetFile = str_replace('//','/',$targetPath) .time().".mp3";
$targetFilea = $targetFile;
$targetFilea = substr($targetFilea , strrpos($targetFilea , 'music') -1);
move_uploaded_file($tempFile,$targetFile);
mysql_query('set names utf8');
$sql = mysql_query("INSERT INTO `Music` (`filename`, `title`, `tags`, `rating`, `click`, `rand`, `album`, `i`, `artist`)
VALUES ('".$targetFilea."', '".$titlepost."', '".$tagspost."', '0', '1', '".$ras."', '1', '".$i."', '".$artist."');")
or die(mysql_error());
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".$i."', 'upload', '".$titlepost."');")
or die(mysql_error());
$click = mysql_query("SELECT *
FROM `Music`
WHERE `filename`='".$targetFilea."' ;");
while($row = mysql_fetch_array( $click ))
{
$mid=$row['id'];
echo "<id>".$row['id']."</id>";
}
mysql_close($connection);
}
echo "1";
?>
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".$i."', upload', '".$titlepost."');")
there is a ' missing before upload
try this instead (also added mysql_real_escape_string for security):
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".mysql_real_escape_string($i)."', 'upload', '".mysql_real_escape_string($titlepost)."');")
What really wrong is: your code is totally insecure. You sanitize POST-Data only using javascript and place it into your SQL query? Anybody can EASILY inject some custom SQL-Code and to really bad things to your database. Never ever rely on any HTTP-Data (be it GET, POST or anything else) to be secure.
I know you are new to PHP, so I honestly encourage you, for the sake of your customer, your project or anyone using your code, before you do anything else, sanitize your POST-Data with PHP before using it within SQL-Querys. Please.
There is even an article on Wikipedia on it, and it is a huge mistake newbies make with huge consequences which is quite easy to prevent.
http://en.wikipedia.org/wiki/SQL_injection
http://www.smashingmagazine.com/2009/03/24/10-useful-php-tips-revisited/ (Tip 1)
If the record is not getting inserted, this means most likely that there is some error. Possibly you have not set the proper error reporting that is why you don't see any error.
Put below two lines on top of your script so that all errors are shown.
ini_set('display_errors', true);
error_reporting(E_ALL);

Categories