i wanna make register form.But i cant insert datas into my db table "yeni"
and get "Error....!!".I really need to solve this problem guys pls help me.
http://i.stack.imgur.com/SoCNK.png
registration.js
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var tc = $("#tc").val();
var tel = $("#tel").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || tc == '' || tel == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
}
else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
}
else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
}
else {
$.post("sign.php", {
name1: name,
tc1:tc,
tel1: tel,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
sign.php
<?php
$connection = #mysql_connect("localhost", "root", "");
$db = mysql_select_db("babo", $connection);
$name = $_POST['name1']; // Fetching Values from URL.
$tc = $_POST['tc1'];
$tel = $_POST['tel1'];
$password = sha1($_POST['password1']);
$query = mysql_query("insert into yeni(adi, tc_no, password, tel) values ('$name', '$tc', '$password', '$tel')");
if($query) {
echo "You have Successfully Registered.....";
} else {
echo "Error....!!";
}
mysql_close ($connection);
?>
As allready suggested use mysqli_ function in favor of mysql_ functions
You should use prepered statements
To get a better starting point on whats actually wrong replace echo "Error....!!"; with echo mysqli_error($connection);
Related
I was trying to have my form validate an email address onblur or onkeyup, to check to see if the email address already exists in my database.
Not sure if I'm almost there with this code, something isn't working though. Right now, as soon as I start typing in the field, the input box for email is flagged based on how I would want it flagged if an email address was entered if it was already in my database. The else statement in AJAX doesn't work, and if I submit the form anyway, I get a message on the page from an error box I created mentioning a syntax error.
Also, part of my php is using mysqli and mysql, does that make a difference with trying to get this input field to validate?
The input id is email and the name is Email; I think I have that correct in my code, not entirely sure though.
PHP:
define('DB_NAME', 'database');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'host');
$first = Trim(stripslashes($_POST['First']));
$last = Trim(stripslashes($_POST['Last']));
$city = Trim(stripslashes($_POST['City']));
$state = Trim(stripslashes($_POST['State']));
$country = Trim(stripslashes($_POST['Country']));
$email = Trim(stripslashes($_POST['Email']));
$tempt = $_POST['tempt'];
$tempt2 = $_POST['tempt2'];
$link = mysqli_connect('host','user','password','members') or die("Error " . mysqli_error($link));
$stmt = mysqli_prepare($link, 'SELECT count(*) FROM members WHERE email =?');
mysqli_stmt_bind_param($stmt, 's', $_POST['Email']);
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $count);
/* fetch value */
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
if ($count == 0) {
echo 'true';
}else{
echo 'false';
}
if ($tempt == 'http://' && empty($tempt2)) {
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
if(!preg_match($reg_exp, $email)) {
$error_message .= "<p>A valid email address is required.</p>";
}
if (empty($first)) {
$error_message .= "<p>Please provide your first name.</p>";
}
if (empty($last)) {
$error_message .= "<p>Please provide your last name.</p>";
}
AJAX:
$(function() {
if (valid != '') {
$('form #response2').removeClass().addClass('error2')
.html('' +valid).fadeIn('fast');
}
var valid = '';
$('#email').keyup(function() {
$.post('script.php', { 'Email' : $(this).val() }, function(data) {
if(data !== 'true') {
$('#email').css('border','2px solid #ff0000');
$('#email').css('background-color','#ffcece');
valid += '<p>This email has already subscribed.</p>';
}else{
$('#email').css('background-color','green');
}
});
});
});
You don't need to fetch all the emails to check whether the posted email already exist.
U can do a simple count and test the amount of records. If its 0 then the email is not in the database
Something like this should work (not tested) :
HTML
<input type="text" name="txt_email" id="txt_email" />
Jquery
$(function() {
$('#txt_email').blur(function() {
$.post('location/to/script.php', { 'txt_email' : $(this).val() }, function(data) {
if(data !== 'true') {
$('#txt_email').css('background', 'red');
}else{
$('#txt_email').css('background', 'white');
}
});
});
});
script.php
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$stmt = mysqli_prepare($link, 'SELECT count(*) FROM user WHERE email =?');
mysqli_stmt_bind_param($stmt, 's', $_POST['txt_email']);
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $count);
/* fetch value */
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
if ($count == 0) {
echo 'true';
}else{
echo 'false';
}
$(function() {
$('#txt_email').blur(function() {
$.post('location/to/script.php', { 'txt_email' : $(this).val() }, function(data) {
if(data !== 'true') {
$('#txt_email').css('background', 'red');
}else{
$('#txt_email').css('background', 'white');
}
});
});
});
I have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.
I want to check if the username is already taken, here is my script, which outputs "undefined". Can anyone help me, please? :)
This is in my jQuery - $("#registerusername").val() is the value of an input.
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data.exists);
if(data.exists){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
}, 'JSON');
This is in my checkregister.php
header('content-type: text/json');
if(!isset($_POST['username']))
exit;
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
echo json_encode(array('exists' => $query->rowCount() > 0));
First, You might want to strengthen your php against sql injection by 'sanitizing' the input.
Next why return JSON from the php? It would be much simpler to just return either true or false.
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'true';
}
else{
echo 'false';
}
Then in your javascript:
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data);
if(data == 'true'){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
});
edit---
You could also just return a boolean variable from php rather than a string, but either will work
Simple Example..
Jquery
var username = $.trim($('#username').val());
if(username != '') {
$.ajax({
url : 'localhost/phpScript.php',
data : {username : username},
dataType : 'JSON',
type : 'POST',
cache : false,
success : function(result) {
if(result == '1') { alert('Username Found.'); }
else if(result == '0') { alert('Username Not Found!'); }
},
error : function(err) {
console.log(err);
}
});
}
PHP/MySQL (Make sure that you escape value for user input, Before giving it to MySql)
if(isset($_POST['username'])) {
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == '1') {
echo '1';
} else {
echo '0';
}
}
I have a registration form which when filled and "Register" button pressed is being checked by js, to find empty fields and to check availability of username, or if email or mobile num was already used by sending info through ajax to php and receiving answer. But my js won't work all the way through. This is my js script:
$("#reg_button").click(function(){
user = $("#usr").val();
pass = $("#psw").val();
fname = $("#first_name").val();
sname = $("#second_name").val();
dateb = $("#date_birth").val();
email = $("#email").val();
mobnum = $("#mob_num").val();
if(user == ""){
alert("First name must be filled out");
$('#usr').focus();
return false;
}else if(pass == ""){
alert("Password must be filled out");
$('#psw').focus();
return false;
}else if(fname == ""){
alert("First name must be filled out");
$('#first_name').focus();
return false;
}else if(sname == ""){
alert("Second name must be filled out");
$('#second_name').focus();
return false;
}else if(dateb == ""){
alert("Date of birth must be filled out");
$('#date_birth').focus();
return false;
}else if(email == ""){
alert("Email must be filled out");
$('#email').focus();
return false;
}else if(mobnum == ""){
alert("Mobile number must be filled out");
$('#mob_num').focus();
return false;
}else{
ajaxCheck();
}
function ajaxCheck(){
$.ajax({
type: "POST",
url: "http://imes.*********.com/php/check_info_reg.php",
data: "usr="+user+"&email="+email+"&mob_num="+mobnum,
dataType: "json",
success: function(json){
if(json.success){
var user_conf = json.data.usr;
var email_conf = json.data.email;
var mob_conf = json.data.mob;
if(user_conf == "taken"){
alert("Username already taken. Choose another one.");
$('#usr').focus();
return false;
}
if(email_conf == "taken"){
alert("Email already registered. If you lost your password, retrieve it on login page.");
$('#email').focus();
return false;
}
if(mob_conf == "taken"){
alert("Mobile number already registered. If you lost your password, retrieve it on login page.");
$('#mob_num').focus();
return false;
}
}else{
//Here could go another ajax, for actualy sending the
//info into the php script which sends it to database.
}
},
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
});
return false;
}
});
And my php:
<?php
$username = mysql_real_escape_string($_POST['usr']);
$email = mysql_real_escape_string($_POST['email']);
$mob_num = mysql_real_escape_string($_POST['mob_num']);
include('mysql_connection.php');
mysql_select_db("jzperson_imesUsers", $con);
$sql1 = mysql_query("SELECT * FROM registered_user WHERE username='$username'");
$sql2 = mysql_query("SELECT * FROM registered_user WHERE email='$email'");
$sql3 = mysql_query("SELECT * FROM registered_user WHERE mobile_num='$mob_num'");
$res1 = mysql_num_rows($sql1);
$res2 = mysql_num_rows($sql2);
$res3 = mysql_num_rows($sql3);
if(isset($username) && !empty($username){
if($res1 >= 1){
//JSON message: Username already taken. Choose different.
echo json_encode(array('success'=>true, 'usr'=>"taken"));
}
}
elseif(isset($email) && !empty($email)){
if($res2 >= 1){
//JSON message: Email already registered. Retrieve on "login"(login => link).
echo json_encode(array('success'=>true, 'email'=>"taken"));;
}
}
elseif(isset($mob_num) && !empty($mob_num)){
if($res3 >= 1){
//JSON message: Mobile number already registered. Retrieve on "login"(login => link).
echo json_encode(array('success'=>true, 'mob'=>"taken"));
}
}
else{
echo json_encode(array('success'=>false));
}
?>
You are missing a parenthesis in your php file:
if(isset($username) && !empty($username){
Should be
if(isset($username) && !empty($username)){
i have problems with the code below, I'm trying to bring a message of error if the email already exists, but I'm not having success .. Look at the code:
Ajax an jQuery:
<script type="text/javascript">
// Centering the text content
jQuery(window).resize(function () {
boxHeight();
}).load(function() {
boxHeight();
// Show the content and focus the email input
$("#content").fadeIn();
$("#email").focus();
});
jQuery(document).ready(function($){
$('#subscribe').submit(function(e){
e.preventDefault();
email = $('input#email');
email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!email_regex.test(email.val())) {
$('#response', form).fadeIn(500, function() {
$('#response', form).html('<p class="message warning" align="center">Invalid email</p>');
});
return;
} else {
$('#response', form).html('<p class="message">Please Wait...</p>');
}
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(responseText) { if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else { if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
}
});
});
});
</script>
PHP Database connect:
<?php
$host="xxxx"; // Host name
$username="xxxx"; // Mysql username
$password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="xxxx"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$email = $_POST['email'];
$query = mysql_query("SELECT email FROM banco_emails WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
echo '1';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
The problem is that the ajax code does not show the error message, only the message "Please wait ..." and nothing happens, i don't know why...
Sorry for my bad english.
Thanks in advanced!
Problem solved, the problem was in the php code, I did it and it worked!
$query = mysql_query("SELECT email FROM banco_emails WHERE email = '$email' LIMIT 1");
$email_check = mysql_num_rows($query);
if ($email_check > 0) {
echo '1';
} else if ($email_check == 0) {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
In your success function you incorrectly handle what PHP returns on success. If the email was new and was added to the database, PHP will echo:
<p class="message">Thanks for registering. Our bar is getting crowded!</p>
Your JS parses the response like this:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
The problem here is that you only display the HTML message if responseText is an empty string. You should get rid of the if statement:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
This way the responseText is displayed. And I'm not 100% sure what your submission HTML looks like, but after you show the message you might want to fade out the "please wait" if it would still be visible after you hide the form.
Try to this way:
Make unique email column.
If the email address is already exist its return an error, and you can show the error message to user, on ajax error section.