Code
<?php
mysql_connect('localhost','root','123456') or die(mysql_error());
mysql_select_db('email') or die(mysql_error());
?>
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$sql=mysql_query("insert into user(name,email)value('$name','$email')");
if($sql)
{
echo '<script>alert("successfull");</script>';
}
else
{
echo '<script>alert("error");</script>';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="" name="form">
<input type="text" name="name" id="name" placeholder="name">
<input type="text" name="email" id="email" placeholder="email">
<input type="submit" name="submit" id="submit">
</form>
</body>
how can we insert data into database without duplicate email id after submit it show alert msg that email id already exist?
thank you
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$query = mysql_query("select * from user where email = '$email'");
$result = mysqli_fetch_assoc($query);
if($result > 0 )
{
echo 'Email already exits';
}
else
{
// code here for insert or what ever you wants
}
}
?>
Firstly the mysql_* functions has been deprecated as of PHP version 5.5.0 and above. So its greatly advised to use mysqli_* functions.
To answer your question, a simple select query along with if statements would do:
$sql="SELECT * FROM users WHERE email = '$email'";
$result = $conn->query($sql);
if($result->num_rows>0){
//Email Already Exists
}
else
{
//Perform Insertion
}
Lastly, its highly recommended to use prepared statements.
First make a select query to check whether on this email and name entry already exist or not.
$SelectSqlQry=mysql_query("select COUNT(email) from user where email = '.$email.'");
$LengthRecords = mysqli_fetch_assoc($SelectSqlQry);
if($LengthRecords > 0) {
//do your alert or anything.
//alert email already exists.
echo '<script>alert("Email Already Exists");</script>';
}
else {
//Insert email..
}
then check your condition on this variable. SelectSqlQry
Related
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
So I'm working on an assignment for my class in which I am supposed to take a username and password and check it against a list contained in a table on a database I am connecting too.
Problem is when I am clicking the submit button nothing is happening I think this is likely to be some sort of error in syntax. Since I am new to PHP there is a good possibility it is something obvious, but not so much to me.
I have my database data stored in two PHP arrays (one for each field). I then converted the arrays to json which I will use in my JavaScript function that will be checked against the user inputted data.
I am including a form, a PHP script, and a JavaScript script in one document could this cause the issue?
Here is my code and thank you for any help!
<html>
<body>
<?php
/*config is included in order to protect my login info*/
require('config.php');
Echo "Project 4";
/*SQL connection*/
$conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
/*Checking Connection*/
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM p4Data";
$data2 = mysqli_query($conn, $sql);
/*Display Data*/
echo "<table border = 1 style='float:left'>
<tr>
<th>Username</th>
<th>Password</th>
</tr>";
//Array Declarations
$usernameArr = [];
$passwordArr = [];
while($records = mysqli_fetch_array($data2)){
array_push($usernameArr,$records["username"]);
array_push($passwordArr,$records["password"]);
}
echo "</table>";
//JSON Conversion
$usernameJson = json_encode($usernameArr);
$passwordJson = json_encode($passwordArr);
mysqli_close($conn);
?>
<!-- JAVA SECTION -->
<script type="text/javascript">
var obj = JSON.parse('<?= $usernameJson; ?>');
var obj2 = JSON.parse('<?= $passwordJson; ?>');
function verifUser(){
var usernameData = document.getElementById("username").value;
var passwordData = document.getElementById("password").value;
for (i = 0; i < 30; i++){
if(usernameData == obj[i]){
alert("Username verfied at " + i);
indexLocated = i;
break;
}
}
}
</script>
<form name='form-main'>
Username: <input type="text" id="username"><br>
Password: <input type="password" id="password"><br>
<input type="button" value="Login >>" id="submitButton"
onclick="verifUser()">
</form>
</body>
</html>
You can use post method to get the value of user input like this
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" value="login">
</form>
and use this php code to get value when form is submitted
if(isset($_POST['submit'])){
$username_input = $_POST['username'];
$password_input = $_POST['password'];
}
Then make a query to sql where username = $username and password = $password. Like below
$sql query = " SELECT * FROM TABLE WHERE username = $username and password = $password";
And use
$num_rows = mysqli_num_rows($sql_query);
Now do a check of $num_rows = 1 that means input username and password is valid else echo Not valid
if($num_rows = 1){
**some code **
}else{
echo "Invalid information provided";
};
I'm making a form at which if user wants to change their password, i made a code that could change password from database but I want to implement some function before changing password, current password would be asked so that they can change their password, But how to do it?
code to update database:
strong text
$result = mysqli_query($con,"SELECT * FROM admin");
if ($row = mysqli_fetch_array($result)) {
$id=$row['id'];
mysqli_query($con,"update admin set password=SHA1( CONCAT('Rajendra')) WHERE id='$id'");
}
echo "<h2>Your password is successfully changed..</h2>";
mysqli_close($con);
?>
here is a code for form:
<?php
include('lock.php');
?>
<form method="post" action="db_change_password.php">
<label><strong>Current password: </strong></label>
<input type="password" name="current_password" value="password"><br><br>
<label><strong>New password: </strong></label>
<input type="password" name="password" value="password"><br><br>
<label><strong>Confirm password: </strong></label>
<input type="password" name="confirm_password" value="password"><br><br>
<input type="submit" value="Submit">
<label><p><strong><br>NOTE: </strong>After changing password, you have to put your new password during login time.</p></label>
</form>
EDITING
login script:
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myemail=mysql_real_escape_string($_POST['email']);
$mypassword=mysql_real_escape_string($_POST['password']);
$sql="SELECT * FROM admin WHERE email='$myemail' AND password='".sha1($mypassword)."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myemail and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION["myemail"];
$_SESSION['login_user']=$myemail;
header("location: home.php");
}
else
{
header("location: invalid_login_form.php");
}
}
?>
I would however make a session with the user_id
$result = mysqli_query($con,"SELECT * FROM admin WHERE email = '".$_SESSION['email']."'");
if ($row = mysqli_fetch_array($result)) {
if(sha1($_POST['current_password']) == $row['password'])
{
$id=$row['id'];
mysqli_query($con,"update admin set password=SHA1( CONCAT('Rajendra')) WHERE id='$id'");
} else {
echo "incorrect password";
}
}
Just before updating the password, you can add a check to test the current password.
the header(location: agentverification.php) does not work when uploaded to godaddy server while it works on localhost server. I've try to edit my codes but the result is still the same. if any of you could help me, I'd appreciate it and thanks in advance.
agentlogin.php
<form method = "post" action = "agentverification.php" >
<table>
<input type="text" name="ID" size=20 ><br></td></tr>
<tr>
<td>Password <font color=red>*</font></td>
<td><input type="password" name="pass" size=20><br></td></tr>
</table>
<input type = "hidden" name = "login">
<input type = "submit" name = "login" value = "submit" id="pop">
agentverification.php
<?php
session_start();
$link = mysqli_connect('localhost', 'root', '','db5') or die(mysqli_error());
if(isset($_POST['login']))
{
extract($_REQUEST);
$id = $_POST['ID'];
$pass = $_POST['pass'];
$query= "SELECT * FROM agentReg WHERE AgentID = '$id'";
$record = mysqli_query ($link,$query);
$check=FALSE;
while($row=mysqli_fetch_array($record))
{
if($id === $row['AgentID']&& $pass === $row['password'] )
{
$check=TRUE;
}
}
if($check == TRUE)
{
$_SESSION['AgentID'] = $id;
$_SESSION['password'] = $pass;
header("Location: agentpage.php");
}
else
{ ?> <script>
alert ("Wrong combination of ID and Password. Please try again.");
</script> <?php
session_destroy();
header("location: agentlogin.php");
}
}?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
agentReg database structure
CREATE TABLE agentReg
(AgentID varchar (100) primary key,
password varchar (100));
You cannot use header('Location: ...'); after you've printed an output.
In your last else you should only include session_destroy(); and for instance header('Location: agentlogin.php?error=idpassword');. The error message should be in agentlogin.php.
Use
window.location.href = 'http://www.google.com'; //Will take you to Google.
All I;m building a web based system. Here I was thinking whether I can get Name according to the number I enter in a text box. What I've tried is as follows. I know it's not working. Will there be another workaround for that? Please help...
html code is
Item No:<input name="iNo" type="text" id="iNo" size="40" maxlength="6" onblur="namesrch()">
Item Name:<input name="na" type="text" id="na" size="40" maxlength="40" disabled>
Here's my javascript
function namesrch(){
iNumber = document.getElementById('iNo').value;
document.getElementById('na').value="<?php $SQL="SELECT iName FROM item Where iNo='iNumber'" ; $run=mySQL_Query($SQL,$con) or die ("SQL error"); while($rec=mySQL_fetch_array($run)){echo $rec{'iName'}}?>";
}
Hope you can understand what I'm trying to do. Thanks in advance..
JavaScript is a client side language, where as PHP is a server side language. You can't run PHP inside JavaScript like that. What you need is Ajax.
Here is a quick example:
Javascript
$('#iNo').on('update', function() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { no: $(this).val() }
success: function(name) {
$('#na').val(name);
}
});
});
Ajax.php
$dbConn = new MySqli($host, $username, $passwd, $dbName);
$no= filter_input(INPUT_POST, "no", FILTER_VALIDATE_INT);
$query = "SELECT iName FROM item WHERE iNo = $no";
$result = $dbConn->query($query);
$name = '';
if($dbConn->errno) {
//An error occurred
} elseif($result->num_rows) {
$row = $result->fetch_assoc();
$name = $row['iNo'];
$result->free();
}
echo $name;
You will notice I used MySQLi, rather than MySQL. MySQL is depreciated and should no longer be used. It is worth your time learning to use either MySQLi or PDO.
I hope this helps.
You can't mix php and js. Assuming you want all the code in one file:
filename.php (Not tested)
<?php
if (isset($_GET['iNumber'])) {
$mysqli = new mysqli("localhost", "my_user", "my_password", "database_name");
// You need to check for sql injection here
$SQL = "SELECT iName FROM item Where iNo = '".$_GET['iNumber']."'' LIMIT 1";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
echo json_encode(array('iName' => $row['iName']));
exit();
}
?>
<html>
<head>
<title></title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
Item No:<input name="iNo" type="text" id="iNo" size="40" maxlength="6" onblur="namesrch()">
Item Name:<input name="na" type="text" id="na" size="40" maxlength="40" disabled>
<script type="text/javascript">
function namesrch() {
iNumber = document.getElementById('iNo').value;
$.getJSON('filename.php?iNumber='+iNumber, function(response) {
$('#na').value(response.name);
});
}
</script>
</body>
</html>