update query not working and change fields to 0 - php

i have this form code.
<form action="save_profile.php" method="post">
<table>
<tr><td>First Name:</td><td><input type="text" name="fname" value="<?php echo $fname;?>"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lname" value="<?php echo $lname;?>"></td></tr>
<tr><td>Mail ID:</td><td><input type="text" name="mail" value="<?php echo $mail;?>"></td></tr>
<tr><td>Contact NO:</td><td><input type="text" name="contact" value="<?php echo $contact;?>"></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Save Profile"></td></tr>
</table>
</form>
and my save_profile.php file has this code.
<?php
session_start();
require('config.php');
function is_valid_fname($fname,$lname,$contact)
{
if (empty($fname)) {
?>
<center><strong><font color="red">First Name is required.</font></strong></center>
<?php
return false;
}
if ( !preg_match ("/^[a-zA-Z\s]+$/",$fname)) {
?>
<center><strong><font color="red">First Name Only Contain Letters.</font></strong></center>
<?php
return false;
}
if (strlen($fname)>20) {
?>
<center><strong><font color="red">First Name must be less than 20 Letters.</font></strong></center>
<?php
return false;
}
if (empty($lname)) {
?>
<center><strong><font color="red">Last Name is required.</font></strong></center>
<?php
return false;
}
if ( !preg_match ("/^[a-zA-Z\s]+$/",$lname)) {
?>
<center><strong><font color="red">Last Name Only Contain Letters.</font></strong></center>
<?php
return false;
}
if (strlen($lname)>20) {
?>
<center><strong><font color="red">Last Name must be less than 20 Letters.</font></strong></center>
<?php
return false;
}
if (empty($contact)) {
?>
<center><strong><font color="red">Contact is required.</font></strong></center>
<?php
return false;
}
if ( !preg_match ("/^[0-9\s]+$/",$contact)) {
?>
<center><strong><font color="red">Contact Only Contain Numbers.</font></strong></center>
<?php
return false;
}
if (strlen($contact)>15) {
?>
<center><strong><font color="red">Contact must be less than 20 Digits.</font></strong></center>
<?php
return false;
}
else{
return true;
}
}
function is_valid_email($mail)
{
if (empty($mail)) {
?>
<center><strong><font color="red">Email is required.</font></strong></center>
<?php
return false;
} else {
$email = test_input($mail);
// check if e-mail address is well-formed
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
?>
<center><strong><font color="red">Invalid Email Format.</font></strong></center>
<?php
return false;
}
// now check if the mail is already registered
$slquery = "SELECT 1 FROM user_tbl WHERE user_mail = '".$mail."'";
$selectresult = mysql_query($slquery);
if(mysql_num_rows($selectresult)>1) {
?>
<center><strong><font color="red">This Email Is Already Exits.</font></strong></center>
<?php
return false;
}
// now returns the true- means you can proceed with this mail
return true;
}
}
if (isset($_POST['submit'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$mail = $_POST['mail'];
$contact = $_POST['contact'];
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (is_valid_email($mail) && is_valid_fname($fname,$lname,$contact))
{
$query="UPDATE user_tbl SET user_fname='".$fname."' AND user_lname='".$lname."' AND user_mail='".$mail."' AND user_contact='".$contact."' WHERE user_id='".$_SESSION['uid']."'";
$result = mysql_query($query);
if ($result) {
header('location:profile.php');
}
}
else{
?>
<center><strong><font color="red">Error Updating User.</font></strong></center>
<?php
}
}
?>
my problem is after displaying data in form when i change form data and when i submit form it will always update my user_fname=0...when i change other field then my other fields remain same and set user_fname=0.please help me...

Please use comma(,) in stead of and
$query="UPDATE user_tbl SET user_fname='".$fname."', user_lname='".$lname."', user_mail='".$mail."', user_contact='".$contact."' WHERE user_id='".$_SESSION['uid']."'";

"SELECT `1` FROM `user_tbl` WHERE `user_mail` = '".$mail."'";
"UPDATE `user_tbl` SET `user_fname`='".$fname."' AND `user_lname`='".$lname."'AND
`user_mail`='".$mail."' AND `user_contact`='".$contact."' WHERE
`user_id`='".$_SESSION['uid']."'";
You forgot the grave accent.Now check is that still working or not .

Related

Am I missing something ? PHP MYSQL connection through Xammp

I'm trying to add form data into my database table on Xampp ,but while My echo displays everything properly ,it doesn't input anything into the database table and I wonder if I'm missing something here.I made sure to spell everything the same ,so I doubt it's a spelling error atleast....Any help,suggestions and or corrections are greatly appreciated !
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$VarErr = $PavErr = $AdErr = $PkErr = $KiekErr = "";
$Vardas = $Pavarde = $Adresas = $Pk = $Kiekis = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Vardas"])) {
$VarErr = "Įveskite vardą";
} else {
$Vardas= test_input($_POST["Vardas"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Vardas)) {
$VarErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Pavarde"])) {
$PavErr = "Įveskite pavardę";
} else {
$Pavarde = test_input($_POST["Pavarde"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Pavarde)) {
$PavErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Adresas"])) {
$AdErr = "Įveskite adresą";
} else {
$Adresas= test_input($_POST["Adresas"]);
}
if (empty($_POST["Pk"])) {
$Pk = "Įveskite prekės kodą";
} else {
$Pk = test_input($_POST["Pk"]);
}
if (empty($_POST["Kiekis"])) {
$KiekErr = "Įveskite kiekį";
} else {
$Kiekis = test_input($_POST["Kiekis"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Vardas: <input type="text" name="Vardas" value="<?php echo $Vardas;?>">
<span class="error">* <?php echo $VarErr;?></span>
<br><br>
Pavarde: <input type="text" name="Pavarde" value="<?php echo $Pavarde;?>">
<span class="error">* <?php echo $PavErr;?></span>
<br><br>
Adresas: <input type="text" name="Adresas" value="<?php echo $Adresas;?>">
<span class="error"><?php echo $AdErr;?></span>
<br><br>
Pk: <input type="number" name="Pk" value="<?php echo $Pk;?>">
<span class="error"><?php echo $PkErr;?></span>
<br><br>
Kiekis:<input type="number" name="Kiekis" value="<?php echo $Kiekis;?>">
<span class="error"><?php echo $KiekErr;?></span>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $Vardas;
echo "<br>";
echo $Pavarde;
echo "<br>";
echo $Adresas;
echo "<br>";
echo $Pk;
echo "<br>";
echo $Kiekis;
$host = "localhost";
$user = "root";
$password ="";
$database = "uzsakymas";
try{
$connect = mysqli_connect($host,$user,$password,$database);
}
catch(mysqli_sql_exception $ex){
echo 'database connection error';
}
if(isset($_POST['insert'])) {
$Vardas = $_POST['Vardas'];
$Pavarde = $_POST['Pavarde'];
$Adresas = $_POST['Adresas'];
$Pk = $_POST['Pk'];
$Kiekis = $_POST['Kiekis'];
$insert_query = "INSERT INTO uzsakymai (Vardas,Pavarde,Adresas,Pk,Kiekis)VALUES('$Vardas','$Pavarde','$Adresas','$Pk','$Kiekis')";
try {
$insert_result = mysqli_query($connect,$insert_query);
if($insert_result){
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo'Data not Inserted';
}
}
} catch(Exception $ex) {
echo 'Error Insert'.$ex->getMessmessage();
}
}
?>
</body>
</html>
hi your are checking value in insert isset($_POST['insert']) but insert name not assign in any control so assign insert name to your submit control check below :
<input type="submit" value="Submit" name="insert">
I'm kinda confused with your code but I think the wrong part is in here:
<input type="submit" name="submit" value="Submit">
You have this submit but look at this:
if(isset($_POST['insert']))
You are trying to check if POST is set to insert instead of submit.

php login form display errors from array

I'm having some trouble displaying my errors on this login form.
The login works but I can't figure out how to display those errors.
I just need to display them between the login field and the footer. I suppose the problem should be the last part of the foreach that should go true the error array.
<!DOCTYPE html>
<html lang="en">
<body>
<?php
include ('includes/header.php');
?>
<div class="nav">
<?php
include ('includes/menu.php');
$error= logInData();
?>
</div>
<section role="main">
<div class="logIn">
<h3>Intranet Login</h3>
</div>
<form action="" method="post">
<fieldset>
<legend>Student Log in</legend>
<div>
<label for="username">Enter username: </label>
<input type='text' id="userN" name="userN" value = "<?php if (isset($error['usern'])){echo $error['usern'];} ?>">
</div>
<div>
<label for="password">Enter password: </label>
<input type='password' id="pass" name="pass" value = "">
</div>
<div>
<p class="red"><?php if (isset($error['both'])) {
echo $error['both'];
} ?></p>
</div>
<div>
<input type="submit" name="submit" value="Log-In">
</div>
</fieldset>
</form>
</section>
<?php
function logInData (){
$error = array();
$validated = array();
$clean = array();
$pass = false;
if (isset($_POST['submit']) && $pass == true) {
$inputPass = ($_POST['pass']);
$trimPass = trim($inputPass);
$inputUsern = ($_POST['userN']);
$trimUsern = trim($inputUsern);
if(!empty($trimPass)){
if (!ctype_alpha($trimPass)) {
$error['passw'] = 'No special characters allowed on password';
$pass = false;
}else{
if(empty($trimPass)){
$error['passw'] = 'password field empty';
$pass = false;
}else{
$clean['passw'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
if(!empty($trimUsern)){
if (!ctype_alpha($trimUsern)) {
$error['userN'] = 'No special characters allowed on username';
$pass = false;
}else{
if(empty($trimPass)){
$error['userN'] = 'username field empty';
$pass = false;
}else{
$clean['userN'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
$dir = '/home/sbau01/public_www/php/fma/data';
if (is_dir($dir)){
$handleDir = opendir('/home/sbau01/public_www/php/fma/data');
$path = "/home/sbau01/public_www/php/fma/data/data.txt";
if(is_file($path)){
$handle = fopen($path, 'r');
while(!feof($handle)){
$dataRow = fgets($handle);
if(!empty($dataRow)){
$separate = explode(' ',$dataRow);
$storedUsern = trim($separate[3]);
$storedPassword = trim($separate[4]);;
if (($clean['userN'] == $storedUsern) && ($clean['passw'] && $storedPassword)){
$match = true;
header('location: intranet.php');
}else{
$error['match']='<span >Username/Password is incorrect!!</span>';
$pass = false;
}
}
}fclose($handle);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}closedir($HandleDir);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}
}else {
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
}
}
?>
<footer>
<?php include ('includes/footer.php');?>
</footer>
</body>
</html>
Its a simple brackets error:
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
The part above is in the else condition of if (isset($_POST['submit']) && $pass == true) {
Thats why this will never execute. Simply remove the bracket above this part and add it after the foreach.
Saving Passwords in text files is NOT a great idea!
In line 101 you have probably an little mistake:
You just check if there are the variables, you dont check if they are equal ($clean['passw'] && $storedPassword)){
A couple of issues identified.
Do you have display errors turned on? https://stackoverflow.com/a/21429652/1246494
You are calling $error= logInData(); at the top, but have your function logInData() { ... } created down below.
I think what you want to do it put the whole function in an include file at the top like:
include ('includes/header.php');
include ('includes/logInFunction.php');
You then want to call logInData(); down in the body.
Another issue is your function puts data in an array and echos data. If you are going to have $error= logInData(); at the top of your page try moving this out of your function and into your body where you want to output the errors.
if(count($error) > 0)
{
foreach($error as $key => $value)
{
echo "ERROR: $value<br />\n";
}
}

PHP Form executing POST request on load

I am creating an update form, but when I click on the update button it redirects to my update page, and triggers the POST request which makes it a valid post and does not ask for any information to update.
<!DOCTYPE html>
<html>
<?php require ('template/functions.php');
$ID = $_GET['id'];
$sql_query = "SELECT * FROM specialties WHERE id='".$ID."'";
$results = mysqli_query($connect,$sql_query);
$spc = mysqli_fetch_assoc($results);
$error = "";
$specialist_section = false;
$description_section = false;
$specilist_exist = false;
$valid_post = true;
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "post") {
valid();
if ($valid_post){
$sql_query = "UPDATE specialties SET ";
$sql_query .= "specialty='".$_POST['specialty']."',";
$sql_query .= "description='".$_POST[description]."'";
$sql_query .= " WHERE id='".$_GET['id']."'";
$result = mysqli_query($connect,$sql_query);
if (!results){
print "MYSQL_ERROR: ".mysqli_error($connect);
$valid_post = false;
$specilist_exist = true;
$error .= "Specialty already exist <br/>";
}
}else{
$valid_post = false;
}
}
?>
<head>
<title>Specialist Lookup </title>
</head>
<body>
<div class="container">
<?php
if ($valid_post){?>
<h2>Update Complete</h2>
<?php
}else{
if ($error) { ?>
<h3 style="color:red;"><?php echo $error ?> </h3> <?php }?>
<h1>Update Specialist</h1>
<form action="update.php" method="post">
<div class="form-group">
<label for="specialty" style="color:<?php if ($specialist_section){echo "red";}else{ echo "black";} ?>">Specialty:</label>
<input type="text" class="form-control" id="sp" name="specialty" value="<?php echo $spc['specialty'] ;?>" >
</div>
<div class="form-group">
<label for="description" style="color:<?php if ($description_section){echo "red";}else{ echo "black";} ?>">Description:</label>
<textarea class="form-control" rows="5" id="comment" name="description"><?php echo $spc['description'] ; ?></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<?php
}
?>
<div>
</body>
<?php
require ('template/footer.php');
?>
/*Reference for the function*/
function valid(){
$valid_post = true;
if (empty($specialty)) {
$valid_post = false;
$specialist_section = true;
$error = "Please fill in the Specialist section";
}
elseif (empty($description)) {
$valid_post = false;
$error = "Please fill in the description section";
$description_section = true;
}
elseif (empty($description) and empty($specialty)) {
$valid_post = false;
$error = "Please fill in the specialty and description section";
$description_section = true;
}
else{
$valid_post = true;
}
}
By default you set
$valid_post = true;
You need to change the logic:
<!DOCTYPE html>
<html>
<?php require ('template/functions.php');
...
$valid_post = false;
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "post") {
$valid_post = valid();
if ($valid_post){
// ...
}
}
?>
<head>
<title>Specialist Lookup </title>
</head>
<body>
<div class="container">
<?php
if ($valid_post){?>
<h2>Update Complete</h2>
<?php
}else{
// ...
}
?>
<div>
</body>
I do not know what happens in valid() function. But I suggest you this pattern:
$validPost = false;
if (valid()) {
$validPost = true;
}
or
$validPost = valid();
Not too sure how you write your valid() function.
By looking at the code, $valid_post is set to be true by default, so you might want to have a look at your valid() function to see if it is actually setting $valid_post to be false if it is not valid, otherwise it will always trigger your update function even if there is no valid form data.
if your valid() function is returning boolean then just modify your code
change
valid()
to
$valid_post = valid()
Also, you probably dont need else in your code at all, $valid_post = valid() this will simply assign a boolean value already, therefore the else part will be redundant.
Let me know if you have any question

How to validate single checkbox in php script

In the below code i have one check box i don't no how to validate checkbox.
I have a checkbox if it is uncheck it should give message please accept the agreement.
please help me friends
<?php
$firstname = $lname = "";
$firstnameErr = $lnameErr = "";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
/*FirstName Validation starts here*/
if(empty($_POST["fname"])) {
$firstnameErr = "*firstname is Required";
$valid=false;
} else {
$firstname = test_input($_POST["fname"]);
}
/*LastName Validation starts here*/
if(empty($_POST["lname"])) {
$lnameErr = "*lastname is Required";
$valid=false;
} else {
$lname=test_input($_POST["lname"]);
}
if (isset($_POST['confirm'])) {
// do something
}
//if valid then redirect
if($valid){
echo 'success';
exit;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="example.php">
firstname<input type="text" name="fname"/><?php echo $firstnameErr?><br /><br />
lastname<input type="text" name="lname"/><?php echo $lnameErr?><br /><br />
<input type="checkbox" name="agree" />
Agree the terms and condition
<input type="submit" value="Submit" />
</form>
please help me friends
please go through the below code.I think it will work fine.
<?php
$firstname=$lname="";
$firstnameErr=$lnameErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
/*FirstName Validation starts here*/
if(empty($_POST["fname"]))
{
$firstnameErr="*firstname is Required";
$valid=false;
}
else
{
$firstname=test_input($_POST["fname"]);
}
/*LastName Validation starts here*/
if(empty($_POST["lname"]))
{
$lnameErr="*lastname is Required";
$valid=false;
}
else
{
$lname=test_input($_POST["lname"]);
}
if(empty($_POST["agree"]))
{
$agreeErr="*check box is Required";
$valid=false;
}
else
{
$agree=test_input($_POST["agree"]);
}
if (isset($_POST['confirm'])) {
// do something
}
//if valid then redirect
if($valid){
echo 'success';
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="example.php">
firstname<input type="text" name="fname"/><?php echo $firstnameErr?><br /><br />
lastname<input type="text" name="lname"/><?php echo $lnameErr?><br /><br />
<input type="checkbox" name="agree" /><?php echo $agreeErr?>
Agree the terms and condition
<input type="submit" value="Submit" />
</form>
If you checkbox is checked, it will be passed to your PHP, otherwise it won't, so just use the isset() function:
if (!isset($_POST['agree'])) {
echo "Please accept the agreement";
}

validation username and password

This is my php validtion code!
<?php //------------------------------------------------------------------------------>PHP VALIDATION
$user="";
$pass="";
$nameErr="";
$passErr="";
//$pattern='/^[a-zA-Z0-9#_ ]*$/';
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(empty($_POST['uname']))
{
$nameErr='Enter Your Name!';
}
else
{
$user = test_input($_POST['uname']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$user))
{
$nameErr=' Re-Enter Your Name! Format Inccorrect!( only alpha, numbers,#_ are allowed)';
}
}
if(empty($_POST['pas']))
{
$passErr='Enter Your Password!';
}
else
{
$user = test_input($_POST['pas']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$pass))
{
$passErr='Invalid Format! Re-Enter Password!';
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML:
<html>
<body>
<div id='shw'><?php echo $user;?></div>
<fieldset id='fld'>
<form method='post' name='f1' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
<table>
<tr>
<td>
User Name:<input type='text' id='uname' name='uname' class='uname' placeholder='USERNAME' autocomplete='off' autofocus maxlength='25'><span class='error'>*</span>
Password:<input type='password' id='pass' class='pass' name='pas' placeholder='PASSWORD' autocomplete='off'>
<input type='submit' name='submit' id='loggin' value='LOGIN' class='login' onclick='val()'>
</td>
</tr>
</table>
</form>
</fieldset>
<div class='errormsg' id='errmsg'><?php echo $nameErr;?></div>
</div>
</body>
</html>
iam having problm in validation i want to show user name after submit.
problem is that my username if else is running good but it skips the password part. iwant that it shud also validate pass field then only shows the username!
please help!
$user = test_input($_POST['pas']); should be $pass = test_input($_POST['pas']);
Your current code set $user in you first if..else block, it's not that PHP skips your second if...else block, it's just that no matter what this block will do, ûser is already set.
If you don't want to display $user if password is invalid, just set $user later in you code:
$nameErr = null;
$passErr = null;
if (empty($_POST['uname'])) {
$nameErr = 'Enter Your Name!';
} else {
$userTest = test_input($_POST['uname']);
if (!preg_match('/^[a-zA-Z0-9#_]*$/', $userTest)) {
$nameErr = ' Re-Enter Your Name! Format Inccorrect! (only alpha, numbers, #_ are allowed)';
} else {
$valid++;
}
}
if (empty($_POST['pas'])) {
$passErr = 'Enter Your Password!';
} else {
$pass = test_input($_POST['pas']);
if (!preg_match('/^[a-zA-Z0-9#_]*$/', $pass)) {
$passErr = 'Invalid Format! Re-Enter Password!';
} else {
$valid++;
}
}
if (is_null($nameErr) && is_null($passErr)) {
$user = $_POST['uname']
}
Here, I just check if $nameErr and $passErr are still null at the end of your tests. If both are null, then you can set $user, since no error has been detected.

Categories