I've created this script to check form of email user will enter into textbox
function checkEmail() {
var mail = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; /* regex koda najdena na codeproject.com*/
if (!filter.test(mail.value))
{
alert('enter valid email');
mail.focus;
return false;
}
It's used to check form in this script and suposed to show you alert, before you are able to continue
<?php
$flag = 0;
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","root","");
if (!$con){
die("cannot connect: " . mysql_error());
}
mysql_select_db("strek", $con);
$nar_db="SELECT * FROM narocniki;";
$result = mysql_query($nar_db, $con);
while($row=mysql_fetch_array($result))
{
if($_POST['mail']==$row['mail'])
$flag = 1;
}
if($flag==0)
{
$sql = "INSERT INTO narocniki (mail) VALUE ('$_POST[mail]')";
mysql_query($sql, $con);
mysql_close($con);
?>
<p align="center" class="vsebina" >
Tvoj mail je bil uspešno sprejet!</p>
<p align="center"><input type="button" name="return" value="nazaj"></p>
<?php
}
else
{
echo '<p align="center" class="vsebina">Naveden mail je že v bazi naročnikov!</p>';
?>
<p align="center"><input type="button" name="return" value="nazaj"></p>
<?php
}
}
else
{
include("vsebina/tabdog.html");
?>
<p align="center" class="vsebina" id="mail">
naroči se na najnovejše novice</p>
<form action="dogodki.php" method="post">
<p align="center" class="vsebina">vnesi svoj e-naslov: <input type="text" name="mail" id="mail" required>
<input type="submit" name="submit" value="potrdi" onClick="return checkEmail()">
</p>
</form>
<?php
}
?>
It's probably just something missing
Should I rather just include script inside the code, and where would be the best to place it-weather directly in head or rather somewhere in between
Is this even possible in my code, because it already checks if mail exists in database, and would then also need to check the form of email
Instead of doing it in the onclick attribute of the submit button, try doing it in the onsubmit attribute of the form:
<form action="dogodki.php" method="post" onsubmit="return checkEmail()">
Related
This is my code, I really don't know whats wrong does anyone else know? Currently the error that comes up is Oops! Something went wrong. Please try again later. I know that the issue is not a connection issue and is not a permissions issue. I'm really confused about what I've done wrong and have even contacted customer support multiple times and they didn't know what the issue is.
<?php
include ('config.php');
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT username FROM users WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location:Login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>
I have built a contact form for my wordpress site. Four fields are there - name, email, subject, message. For logged in users I want their name and email to be auto-filled in their respective fields in the form and those name, email fields will be disabled for them to edit. And for non-logged in users they will put name, email fields manually. I have put this code in the page template file -
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
if ( 0 != $current_user->ID ) {
echo '<script type="text/javascript">
document.getElementById("curUserName").value = "'.$user_name.'";
document.getElementById("curUserName").disabled = "disabled";
document.getElementById("curUserEmail").value = "'.$user_email.'";
document.getElementById("curUserEmail").disabled = "disabled";
</script>';
}
?>
But this code is disabling name, email fields for both users (logged in and non-logged in). I have controlled the script through if condition. Still the javascript is applying for both users. Please advise where I have gone wrong.
Here is the form html -
<form action="/success.php" method="post">
<label>Name :</label><br>
<input type="text" id="curUserName" name="sender_name" required><br>
<label>Email :</label><br>
<input type="text" id="curUserEmail" name="sender_email" required><br>
<label>Subject :</label><br>
<input type="text" name="sender_sub"><br>
<label>Message</label><br>
<textarea name="sender_msg" rows="4" cols="60" required></textarea><br>
<input type="submit" name="submit" value="Send">
</form>
The source you are going to change has disabled option already.. so just remove it if the user is not logged in :)
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
echo '<script type="text/javascript">';
if ( 0 != $current_user->ID )
{
echo 'document.getElementById("curUserName").value = "'.$user_name.'"
document.getElementById("curUserName").disabled = "disabled"
document.getElementById("curUserEmail").value = "'.$user_email.'"
document.getElementById("curUserEmail").disabled = "disabled"';
}
else
{
echo 'document.getElementById("curUserName").disabled = false;
document.getElementById("curUserEmail").disabled = false;';
}
echo '</script>';
?>
Don't echo javascript with php. It's bad practice.
Try using value tags in your inputs, check if user logged in with a ternary operator, and if so, echo to value tag their credentials.
<?php (is_user_logged_in()) ? $current_user = wp_get_current_user() : $current_user = false; ?>
<label>Name</label>
<input type="text" id="curUserName" name="sender_name" value="<?php ($current_user) ? echo $current_user->user_name : '' ?>" required>
<label>Email</label>
<input type="text" id="curUserEmail" name="sender_email" value="<?php ($current_user) ? echo $current_user->user_email : '' ?>" required>
I've build a function in javascript to show me a second submit but only after the first submit was clicked.
Edited - this is ex.php:
<form method="post" action = "ex.php">
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
inputSubmit = document.getElementById("submit");
function myFunction(){
inputSubmit.style.display = "block"; };
</script>
Updated:
I've edited in order to conclude the main problem.
So what I want is this:
a) The user has pressed the first submit button "search" then it will echo on the page "first search" and then show the second submit button "search_close" .
b)Then, if the user has pressed the second submit button it will show "second search".
When first Refreshing:
======
search (button)
======
if clicking the "search" button:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
if clicking the "find close results:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
second search (text)
This code doesn't do what I want. Why?
Updated - why the button find close results disappers after one second?
<?php
session_start();
$db=mysqli_connect("localhost","root","","travelersdb");
if(#$_SESSION["username"]){
?>
<?php
// function to connect and execute the query
function filterTable($query)
{
$connect=mysqli_connect("localhost","root","","travelersdb");
$filter_Result = mysqli_query($connect, $query) or die(mysqli_error($connect));
return $filter_Result;
}
$submit_value = 0;
if(isset($_POST['search']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$Age= $_POST['Age'];
$email = $_POST['email'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($Age)) {
$query.="AND age='$Age'";
}
if(!empty($email)) {
$query.=" AND email='$email'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 1;
}
///Make The search more wider, only for the fields that were in the post
else if(isset($_POST['search_close']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 2;
}
else {
$query = "SELECT * FROM `topics`";
$search_result = filterTable($query);
}
?>
<html>
<head>
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Home Page</title>
<style>
.hidden {
display: none;
}
</style>
<script type="text/javascript">
function showHide()
{
var checkbox = document.getElementById("chk");
var hiddeninputs = document.getElementsByClassName("hidden");
for (var i=0; i != hiddeninputs.length; i++) {
if(checkbox.checked){
hiddeninputs[i].style.display = "block";
} else {
hiddeninputs[i].style.display = "none";
}
}
}
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
myFunction();
inputSubmit = document.getElementById("submit");
function myFunction(){
document.getElementById('submit').style.display = "block";
};
<?php } ?>
</script>
<body>
</body>
</head>
<?php include("header.php");?>
<center>
</br>
<button>Post</button>
</br>
<br/>
<h4>Simple Serach</h4>
<form action="" method="post">
<input type="text" name="Destination" placeholder="Destination" value=
"<?php if(isset($_POST['Destination']))
{echo htmlentities($_POST['Destination']);}?>" ></br>
<input type="text" name="TypeOfTravel" placeholder="Type Of Travel"
value=
"<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['TypeOfTravel']);}?>"
></br>
<input type="text" name="Age" placeholder="Age" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['Age']);}?>">
</br>
</br>
<!-- Advanced Search-->
<input type="checkbox" name="chkbox" id="chk" onclick="showHide()" />
<label for="chk"><b>Advanced search</b></label>
</br>
<input type ="text" name="email" placeholder="Email" class="hidden" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['email']);}?>">
<input type ="text" name="topic_name" placeholder="topic name" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['topic_name']);}?>">
<input type="text" name="StartingPoint" placeholder="Starting Point" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['StartingPoint']);}?>">
</br><br/>
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br><br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<br/>
<?php echo '<table border="1px">';?>
<td width="400px;" style="text-align:center;">
Name
</td>
<td width="400px;" style="text-align:center;">
Destination
</td>
<td width="400px;" style="text-align:center;">
Type Of Travel:
</td>
<td width="80px;" style="text-align: center;">
First Name
</td>
<td width="80px;" style="text-align: center;">
Age
</td>
<td width="400px;" style="text-align:center;">
profile picture
</td>
<td width="80px;" style="text-align: center;">
Creator
</td>
<td width="80px;" style="text-align: center;">
Date
</td>
</tr>
</center>
<?php
$sql = "Select * from `topics`";
$check = mysqli_query($db,$sql);
$rows = mysqli_num_rows($search_result);
if($rows != 0){
while ($row = mysqli_fetch_assoc($search_result)){
$id = $row['topic_id'];
echo "<tr>";
//echo "<td>".$row['topic_id']."</td>";
echo "<td style='text-align:center;'><a href='topic.php?id=$id'>".$row['topic_name']."</a></td>";
echo "<td>".$row['Destination']."</td>";
echo "<td>".$row['typeTravel']."</td>";
$sql_u = "Select * from users where username='".$row['topic_creator']."'";
$check_u = mysqli_query($db,$sql_u);
while ($row_u = mysqli_fetch_assoc($check_u))
{
$user_id = $row_u['id'];
$profile_pic = $row_u['profile_pic'];
$firstname = $row_u['firstname'];
$age = $row_u['age'];
echo "<td>".$firstname."</td>";
echo "<td>".$age."</td>";
echo "<td><img src='".$profile_pic."' width='10%' height='10%' alt='me'></td>";
echo "<td><a href='profile.php?id=$user_id'>".$row['topic_creator']."</a></td>";
}
$get_date = $row['date'];
echo "<td>".$row['date']."</td>";
echo "</tr>";
}
}else {
echo "No topics found";
}
echo "</table>";
if (#$_GET['action']=="logout")
{
session_destroy();
header('location:login.php');
}
}else
{
echo "You must be logged in.";
echo "<a href ='login.php'>Click here to login</a>";
}
?>
</br>
</br>
<body>
</body>
</html>
you need to set type button cause when you set type submit then form automatically submit so show second not show but it work.
<form method="post" action = "">
<input type="submit" id="button" name="search" value="Search" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
$submit_value = 0;
if(isset($_POST['search']))
{
echo "first search";
$submit_value = 1;
}
else if(isset($_POST['search_close']))
{
echo "first search";
echo '<br>';
echo "second search";
$submit_value = 2;
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
document.getElementById('submit').style.display = "block";
<?php } ?>
</script>
check this code
I have cleaned up your code, but the issue of having two submit buttons still persists. Even if the clicking of the first button causes the second to show, the first button will cause the page to reload with the results from the form's action resource. In this example, I have cancelled the form's submit event to show that the display of the second button works.
In the end, I think you are going about this all wrong. I think you should be making AJAX calls to your server-side resource and injecting the results of that call into your page - - no forms and no submits.
// Don't forget to add "var" to your variable declarations, otherwise the variables
// become global!
var sub1 = document.getElementById("btnSub1");
var sub2 = document.getElementById("btnSub2");
// Set up the event handler for the first button
sub1.addEventListener("click", myFunction);
function myFunction(e){
// Adjust classes, not individual styles
sub2.classList.remove("hidden");
// Cancel the native event and stop bubbling
e.preventDefault();
e.stopPropagation();
};
.hidden { display:none; }
<form>
<!-- Submit buttons don't get a name attriute unless you expect their value to be submitted
along with all the other form data. Inline styles should be avoided and internal style
sheets used instead. And, inline JavaScript event attributes (onclick, etc.) should not
be used. -->
<input type="submit" id="btnSub1" name="search" value="Search" >
<br>
<input type="submit" id="btnSub2" class="hidden" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>
here's the code guys please help me
if mysqli_num_rows==false Than code works but why num rows doesn't work i can't get it i tried everything but same error appears
<?php
//Start session
session_start();
//Include database connection details
require_once('db.php');
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['password'];
$query="SELECT * FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($con,$query);
if($row=mysqli_num_rows($result)==1){
mysqli_fetch_array($con,$result);
echo 'Logged in';
header('location:profile.php');
}
else{
echo 'error occured';
}
}
?>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
session_start();
require_once('db.php');
if(!empty(trim($_POST['username'])) && !empty(trim($_POST['password']))){ // check with posetd value
$user_name = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$query = "SELECT * FROM users where username='$username' and password = '$password'"; // don't use plain password, use password hashing mechanism
$result = mysqli_query($con,$query); // run the query
if(mysqli_num_rows($result)>0){ // if data comes
// here do some data assignment into session
header('location:profile.php'); // go to other page
}else{
echo "Login creadentials are not correct"; // else no user is there with the given credentials
}
}else{
echo "please fill the form value";
}
?>
Note:-
Read and use prepared statements to prevent your code from SQL Injection. :-http://us.php.net/manual/en/mysqli-stmt.prepare.php
Above file extension must be .php
I am new to php, mysql, and javascript. Recently I have been working on creating a popups for each button. When I put the code in the form tag, the code works, however it is a general popup for both add and delete. I would like a confirm popup for adding and deleting. I tried putting the code on the input tags but the code did not run. What am I doing wrong?
HTML
<form action="da.php" method="post">
name:<input type="text" name="input1">
<br/>
<input onSubmit="if(!confirm('Submit?')){return false;}" name="add1" type="submit" value="Submit" />
<input onSubmit="if(!confirm('Delete?')){return false;}" name="del1" type="submit" value="Delete" />
</form>
</body>
PHP
define('db_name', 'demo');
define('db_user', 'root');
define('db_password', 'pw');
define('db_host', 'localhost');
$link = mysql_connect (db_host, db_user, db_password);
if (!$link) {
die('could not connect: '. mysql_error());
}
$db_selected = mysql_select_db(db_name, $link);
if (!$db_selected) {
die('can\'t use' . db_name . ': ' . mysql_error());
}
$value = $_POST['input1'];
if (isset($_POST['add1'])) {
$sql = "insert into demo (name) values ('$value')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
}
elseif (isset($_POST['del1'])) {
$sql = "delete from demo where name = ('$value')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
}
mysql_close();
header( 'Location: localhost://da-form.html') ;
?>
try onclick instead of onSubmit
onSubmit is usually used on the form tag
You can use window.confirm in javascript to get confirmation from user.
http://www.w3schools.com/jsref/met_win_confirm.asp
Try this
<form action="da.php" method="post">
name:<input type="text" name="input1">
<br/>
<input onClick="return confirm('Submit?');" name="add1" type="submit" value="Submit" />
<input onClick="return confirm('Delete?');" name="del1" type="submit" value="Delete" />
</form>