jquery .post can't pass the value into php for checking - javascript

I have a question in jquery - Post . when I input the email in the form, the js - jquery will pass the email into sendResetPasswordMail1.php to check email is valid or not.
but now, $.post("sendResetPasswordMail1.php",mail:email},function(resetPasswordMsg) can not work in js.
I can't find what wrong. Distress.
Could you help me please.
Many Thanks.
php
<!--reset Password Popup start-->
<div class="resetPasswordLayer" id="resetPassword" tabindex="-1">
<div class="resetPasswordLayerWall" id="resetPasswordLayerWall">
<button type="button" class="close resetPasswordCloseButton" aria-label="Close"><span aria-hidden="true">×</span></button>
<p><h3 class="layerTittle">Reset Password</h3></p>
<div class="row">
<!--<form class="form-horizontal" action="ResetPassword/sendResetPasswordMail.php" method="post" id="login-form">-->
<div class="form-horizontal form-group">
<div class="input-group">
<p><strong>User can retrieve the password through the mailbox</strong></p>
<!--<p><strong>Enter your registered e-mail, retrieve your password:</strong></p>-->
<p><input type="text" class="form-control" name="resetPasswordEmail" id="resetPasswordEmail" placeholder="Enter your registered e-mail, retrieve your password."><span id="chkresetPasswordMsg"></span></p>
</div>
</div>
<div class="form-group">
<div class="input-group"><!--<div class="col-md-11 col-md-offset-1">-->
<p><input type="button" class="btn btn-success" id="subSendResetPassword_btn" value="Reset"></p>
<!--<button type="submit" class="btn btn-success"id="subSendResetPassword_btn">Reset</button>-->
<span id="resetPasswordMsg"></span>
</div>
</div>
<!--</form>-->
</div>
</div>
</div>
<!--reset Password Popup End-->
js - jquery
$(function(){
$("#subSendResetPassword_btn").click(function(){
var email = $("#resetPasswordEmail").val();
var preg = /^\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/; //match Email
if(email=='' || !preg.test(email)){
$("#chkresetPasswordMsg").html("Please fill in the correct email!");
}else{
$("#subSendResetPassword_btn").attr("disabled","disabled").val('Submit......').css("cursor","default");
alert(email);
$.post("sendResetPasswordMail1.php",{mail:email},function(resetPasswordMsg){
if(resetPasswordMsg == ""){
alert("No Msg Return!");
}
if(resetPasswordMsg=="noRegister"){
$("#chkresetPasswordMsg").html("The mailbox is not registered yet!");
//$("#subSendResetPassword_btn").removeAttr("disabled").val('Submit').css("cursor","pointer");
}else{
$(".resetPasswordLayer").html("<h3>"+resetPasswordMsg+"</h3>");
}
});
}
});
})
php - sendResetPasswordMail1.php
$email = stripslashes(trim($_POST['mail']));
$sql = "select * from user where email='$email'";
$query = mysql_query($sql);
$num = mysql_num_rows($query);
if($num==0){//The mailbox is not registered yet! Return 'noRegister'
$resetPasswordMsg = "noRegister";
echo $resetPasswordMsg;
exit;
}

Prevent the default click event
$("#subSendResetPassword_btn").click(function(e){
e.preventDefault()
});

Related

How to send the drop down list value to an email? [duplicate]

This question already has an answer here:
How to send the selected value of a drop down menu to an email?
(1 answer)
Closed 4 years ago.
I have an question that I need to send selected drop down list value to an email.I already sent the other input values in the contact form to an email. But I do not know how to send the drop down list value to an email. Herewith attached the html, php and js code. Could anyone can help me?
Here is the html code
<!-- Contact form -->
<div class="modal fade" id="modalForm" role="dialog" style="width: 100%;">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Contact Form</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name" style="border: 1px solid #fff; border-bottom: 1px solid #ccc;"/>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
</div>
<div class="form-group">
<label for="inputService">Service</label>
<select name="subject" class="form-control"
id="inputService" size="1">
<option value="Option1">Pr-Matrimonial Services</option>
<option value="Option2">Extra Marital Affairs</option>
<option value="Option3">Divorce Case Support</option>
</select>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
</div>
</div>
</div>
</div>
JS code...
<script>
function submitContactForm(){
var usernameRegex = /^[a-zA-Z0-9]+$/;
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#inputName').focus();
return false;
}else if(name.trim() != '' && !usernameRegex.test(name)){
alert('Please enter valid name.');
$('#inputName').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}else if(message.trim() == '' ){
alert('Please enter your message.');
$('#inputMessage').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'contact.php',
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
php code...
<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
$option= $_POST["subject"];
/*
* Send email to admin
*/
$to = 'support#ribelz.net';
$subject= 'Contact Request of privateeyelk.com';
$htmlContent = '
<h4>Contact request from : '.$email.'</h4>
<p>Name: '.$name.'</p>
<p>Email: '.$email.'</p>
<p>Message: '.$message.'</p>
<p>Service: '. $option.'</p>
';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: Private Eye<privateeyelk.com>' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
You didn't retrieve the value of select in your Js code
Try adding this line in your submitContactForm function
var subject = $('#inputService').val();
Please check this line to
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message+'&service='+subject,

Preventing bootstrap modal from disappearing in case validation failure using PHP after submit button is clicked

My question is how do I stop modal from closing, on two occasions, when user clicks the sign up button:
if the inputs are invalid? and display PHP error message
inputs are valid and to display PHP success message for couple of seconds before closing modal?
for the first case if I reopen the modal I can see the validation error messages which are displayed by PHP.
I have checked this similar question but haven't figure it out how to do it in my case yet so any help will be much appreciated. I would like to fully understand what is going on and what I am doing.
So far after reading here and there I noticed that this can probably be achieved by:
JQuery / JavaScript to do the form validation and not to use PHP
some people suggested using iframe
Is there a way to use the PHP code below and display error / success messages from this code? or it has to be done via JQuery/JS?
My PHP with HTML code
<?php
ob_start();
include('header.php');
include_once("db files/db_connect.php");
if(isset($_SESSION['user_id'])) {
header("Location: index.php");
}
$error = false;
if (isset($_POST['signup'])) {
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$uname_error = "Name must contain only alphabets and space";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error) {
if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$success_message = "Successfully Registered!";
} else {
$error_message = "Error in registering...Please try again later!";
}
}
}
?>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="registrationFormLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" >
<div class="modal-header">
<h5 class="modal-title" id="registrationFormLabel">Register</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- REGISTRATION FORM -->
<div class="container">
<div class="form-row">
<div class="col">
<form onsubmit="return validateForm()" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
<fieldset>
<legend>Sign Up</legend>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($uname_error)) echo $uname_error; ?></span>
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" name="password" placeholder="Password" required class="form-control" />
<span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
</div>
<div class="form-group">
<label for="name">Confirm Password</label>
<input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
<div class="form-group text-center">
<input id="modalSubmit" type="submit" name="signup" value="Sign Up" class="btn btn-primary" formnovalidate />
</div>
</fieldset>
</form>
<span class="text-success"><?php if (isset($success_message)) { echo $success_message; } ?></span>
<span class="text-danger"><?php if (isset($error_message)) { echo $error_message; } ?></span>
</div><!-- / col -->
</div><!-- / form-row -->
<!-- already registered row -->
<div class="row">
<div class="col text-center">
Already Registered? Login Here
</div>
</div> <!-- / already registered row -->
</div><!-- / REGISTRATION FORM container-->
</div><!-- / Modal body div -->
</div>
</div>
</div><!-- / Modal -->
My modal opens when the user clicks the button on index page and here is the JQuery code
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myModal").modal();
});
});
Add below PHP script after end of document (/html) before script tag
<?php
if ($error) {
echo '<script>$("#myModal").modal("show");</script>';
} else {
echo '<script>$("#myModal").modal("hide");</script>';
}
?>
Invalid:
You can stop the submit button from submitting if the inputs are invalid.
To stop submit use the code
$(':input[type="submit"]').prop('disabled', true);
To show modal
$("#myModal").modal('show');
To enable submit again, when modal is closed due to error, use the code
(You will want to enable it again so the user can try again)
$("#myModal").on('hidden.bs.modal', function (e) {
$(':input[type="submit"]').prop('disabled', false);
});
For the validation I would do it this way (add a success variable):
if (!$error) {
if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$success = 1;
} else {
$success = 2;
}
And then call it like this:
<?php if($success == 1){ ?>
<script>
$(document).ready(function() {
$("#yoursuccessmodal").modal('show');
});
</script> <?php } ?>
You can then choose to add a fade to it, or have the user click it away.
The modal will then show AFTER the submition has been sent.
This better work, as I have used it this way in my project as well and it works like a charm for me.

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

PHP Update Cell Data Error

HeyHeyHey!
I am having this problem, for some reason it won't add the Data to my MYSQL Database and I have no idea why. I looked at a lot of other posts here on StackOverflow, but can't seem to find a post that helps me :)
Here is my code:
<script>
$('.alert-saved-changes-success2').hide();
$(".save-tradelink-profile").click(function() {
$tradelinkvalue = document.getElementById("tradelink").value;
if ($.trim($('#tradelink').val()) == '') {
alert('Tradelink can not be blank');
} else if ($tradelinkvalue.indexOf("https://steamcommunity.com/tradeoffer/new") >= 0) {
<?php //TRYING TO UPDATE DATA
$TradelinkValue = $_POST['GetTradelinkValue'];
mysql_query("UPDATE item-jackpot-users SET tradelink=$TradelinkValue WHERE steam_id=$steamid") or die(mysql_error());
?>
$("#alert-saved-changes-success").slideDown("slow");
} else {
alert('Tradelink has to be valid');
}
});
$(".logout-button-profile").click(function(){
window.location.href = "steamauth/logout.php";
});
</script>
It seems like the php tag gets loaded before everything else, since the
$('.alert-saved-changes-success2').hide();
doesn't load. It finds the error, and then just killing everything else.
Respecting the fact that yes, php is performed before your webbrowser receives the js text, you could use a form, that sends your update information into post(like using a form tag), reload the page, and make the page perform the update with your post data. You could also use ajax.
<form name="login" class="form-horizontal" method="post" action="refer to this file" >
<div class="form-group">
<label class="col-sm-3 control-label">
Username
</label>
<div class="col-sm-2">
<input class="pull-right" type="text" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">
Password
</label>
<div class="col-sm-2">
<input class="pull-right" type="password" name="password" />
</div>
</div>
<div class="form-group">
<div class=" col-sm-offset-3 col-sm-2">
<button type="submit" name="submitbtn" class="btn btn-default pull-right">
Sign in
</button>
</div>
</div>
</form>
<?php
$user = $_POST['username'];
$pwd = $_POST['password'];
//DO SOME SANITIZATION!
//Store $user and $pwd
?>
Ofcourse you could include the php part somewhere else in the file, like inside of a script tag.

JavaScript Username authentication

The following represent my registration link which lead to open a modal:
Register Here
The following represents the code for my modal dialog:
<div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" name="f2" id="regisform" method="post" onsubmit="return false;" role="form">
<div class="modal-header">
<h4>Registration<button class="close" data-dismiss="modal">×</button></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="inputusername3" class="col-sm-2 control-label">Username</label>
<div class="col-lg-8">
<input type="text" name="txtusername" class="form-control" id="inputusername3" placeholder="username">
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="submit" id="regisBtn" class="btn btn-primary" value="Registration">
<a class="btn btn-default" data-dismiss="modal">Cancel</a>
</div>
</form>
</div>
</div>
</div>
The below represent the JavaScript Code:
$(document).ready(function(){
$("#regisBtn").click(function(){
var username1=$("#inputusername3").val();
$.post("registercheck.php", {username:username1}, function(result){
if(result==='true')
alert("true");
else
alert("false");
});
});
});
The below represent my php code:
<?php
$username1=$_POST['username'];
$con= mysql_connect("localhost","root","");
mysql_select_db("onlineshop",$con);
$query1= mysql_query("select username from users where username=$username1",$con);
if(mysql_num_rows($query1)==1){
echo 'false';
}else{
mysql_query("insert into users(username)values ('".$username1."')",$con);
session_start();
$_SESSION['username']=$username1;
echo 'true';
}
There is error in mysqli_num_rows() shows that it expects parameter 1 to be resource, Boolean given in something like that
I dont knw why my code is not working. please help me with my code to check whether the username is exists or not?
You have 4 problems with your code. First, you are using mysql_* functions. Use mysqli_* instead, mysql_* is deprecated. Second, you are vulnerable to SQL injection. This is fixed below by using mysqli_real_escape_string. Consider using PDO instead. Third, your select query is malformed - any string in the query must be wrapped in single quotes. Fourth, in a couple of mysql_* function calls, your database link is the last parameter. It should always be the first parameter in the call.
<?php
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "onlineshop");
$clean_username1 = mysqli_real_escape_string($con, $_POST['username']);
$query1 = mysqli_query($con, "select username from users where username = '".$clean_username1."'");
if (mysqli_num_rows($query1) == 1){
echo 'false';
} else {
mysqli_query($con, "insert into users (username) values ('".$clean_username1."')");
session_start();
$_SESSION['username'] = $_POST['username'];
echo 'true';
}

Categories

Resources