form save empty value php - php

I have created a profile page in php, where the user, using a form can save his telephone number in a table named profile in database. If the user decides to change his telephone number can easily go to form change it and save it again. My only problem is the following. Suppose that the user wants to delete his telephone number. If he goes to the form delete his number (makes the field empty) and press save , the telephone number doesn't change to an empty value and continues to keep the previous number. Any idea how to change this in order to keep an empty value?
This is my code with the form :
<form action="" method="POST" >
<?php
if ( isset($_GET['success']) === true && empty($_GET['success'])===true ){
echo'Profile Updated Sucessfuly';
}else{
if( empty($_POST) === false && empty($errors) === true ){
$update_data_profile = array('telephone' => $_POST['telephone']);
update_user_profile($session_user_id, $update_data_profile);
header('Location: profile_update.php?success');
exit();
}else if ( empty($errors) === false ){
echo output_errors($errors);
}
?>
Telephone<input name="telephone" type="text" size="25" value="<?php echo $user_data_profile['telephone']; ?>"/>
<input type="submit" value="" name="submit"/>
</form>
And this is my function that dispatches data to profile table:
function update_user_profile($user_id, $update_data_profile){
$result = mysql_query("select user_id from profile where user_id = $user_id limit 1");
if(mysql_num_rows($result) === 1){
$update = array();
array_walk($update_data_profile, 'array_sanitize');
foreach($update_data_profile as $field => $data ){
if(!empty($data)){
$update[]='`' . $field . '` = \'' . $data . '\'';
}
}
if(isset($update) && !empty($update)){
mysql_query(" UPDATE `profile` SET " . implode(', ', $update) . " WHERE `user_id` = $user_id ") or die(mysql_error());
}
}
else{
$user_id = $update_data_profile['user_id'] ;
if(count($update_data_profile)){
$columns = array();
$values = array();
foreach($update_data_profile as $field => $data){
$columns[] = $field;
$values[] = $data;
}
}
mysql_query(" INSERT INTO `profile` (" . implode(",", $columns) .") values ('" . implode("','", $values) . "')" ) or die (mysql_error());
}
}

You are only updating the field if the data is NOT empty.
See this line:
if(!empty($data)){

Because you're explicitly ignoring empty values with this:
if(!empty($data))

Since empty() function can validate for missing, and false elements, you can't simply pass that on to a SQL query. So, if you want to actually generate a query for these items, you will need to set the value explicitly by doing something like this:
if (empty($data)) {
$update[] = "`{$field}` = ''" ;
} else {
$update[] = "`{$field}` = '{$data}'" ;
}
If you are writing for PHP 5.3 or above, you could also replace the if..else statement and shorten your code by using a ternary operator (conditional assignment) doing something like this:
$update[] = (empty($data)) ? "`{$field}` = ''" : "`{$field}` = '{$data}'";

Related

if else construct issue in value attribute of html

public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
if (empty($_POST)){
$_SESSION['ids'] = "";
$query = mysqli_query($this->connection, "SELECT MAX(EmployeeId) AS EmployeeId FROM employees") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()) {
// Push the id to the array.
$_SESSION['ids'] = $row["EmployeeId"];
}
}
}
The above code snippet bring the latest registered employee ID from the database.
------------------------>--------------------
public function updateSalary(){
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// This code Snippet ensures that in order to access this page Employee needs to be Login.
}
$EmployeeID = (isset($_GET['EmployeeId']) ? $_GET['EmployeeId'] : '');
$query = mysqli_query($this->connection, "SELECT * FROM salary WHERE EmployeeId= '" . $EmployeeID . "'") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()){
// Push the id to the array
$_SESSION['eids'] = $row["EmployeeId"];
$_SESSION['salry'] = $row["Salary"];
if ($_SESSION['ids']) {
$_SESSION['ids'] = "";
}
}
the above code snippet is my update function to update each record. And i have included both the above function in my html form at the top.
The Problem is that : As my insertion and updation form is same, so the session value which is in if statement is echoed in the text box , else part does not work even if session is unset in if part, What should i do ? See the below code
here is the value attribute :
<td>
<input type="number" name="EmployeeId" placeholder="EmployeeId" value="<?php if (isset($_SESSION["ids"])){echo $id_salaries;}else{echo $emp_id;} ?>" id="EmployeeId" autocomplete="off" class="form-control" readonly>
</td>
This is not session unset $_SESSION['ids'] = ""; this is your assigning empty string value to session . session unset should be unset($_SESSION['ids'])

PHP: Want to keep a persistent variable when submitting form and reloading self-processing form

I am creating a workout logger using PHP and MySQL. The way I have it set up currently, the user uses a select to choose a workout template - and that value is POSTed to the form page. The template name is used to query the database for the names of all the exercises in that template and the number of sets per exercise. The names and sets are put into parallel arrays.
A function is called which generates the form. An element for the template name (ex. Full Body Workout), one for the exercise name (ex. Barbell Deadlift), and one for the set number, with a label/input pair for: weight, reps, rest, and notes.
Screenshot
The increment for the exercise name variable is a counter in $_SESSION, which gets incremented after each successful database insert.
My question is on the logic aspect. How can do I go about incrementing the $_SESSION variable without reseting it back to zero?
session_start();
//User
$user = $_SESSION['email'];
$date = date("Y-m-d");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
//This is the value I want to keep persistent
$_SESSION['nameCount'] = (int)0;
$nameCount = $_SESSION['nameCount'];
//Value from select
$template = $_POST['mySelect'];
//Set log submit button
$logSubmit = $_POST['logSubmit'];
//Check if user is signed in
if ($user) {
if ($template) {
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Return query
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result);
$exerciseArray = exerciseList($result, $numRows); //Returns set of exercises in template
//For some reason, $result and $numRows is empty after being passed into $exerciseArray
//Reinitialize
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result); //numRows
$setsArray = getSets($result, $numRows); //Gets number of sets as array
//Reinitialize
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result);
$exerciseIDArray = exerciseIDList($result, $numRows);
//Build form
buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray);
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} else if (empty($template)){
//Do something if template is empty
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
echo "<p>Seems the template is empty</p>\n";
echo "<p>Template = $template</p>\n";
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} //End if ($template)
} else if (!isset($user)) {
//If user not logged in
require("include/redirect.php");
}
Here are the relevant functions: Build log builds the form and the insert is with it
//Build log form using query result and exercise name increment ($x)
function buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray) {
$logSubmit = $_POST['logSubmit'];
if (!isset($logSubmit)) {
echo "<form action='$thisScript' method='POST' name='log' id='log'>\n";
echo "<fieldset>\n";
echo "<legend>$template</legend>\n";
echo "<h2>$exerciseArray[$nameCount]</h2>\n";
echo "<input type='hidden' name='exerciseArray[]' value='$exerciseArray[$nameCount]'/>\n";
$j = 1;
//Generate exercise form with loop
for ($i=0; $i < $setsArray[$i]; $i++) {
echo "<fieldset>";
echo "<legend>Set $j</legend>\n";
//Use $template in a hidden value to work around issue of value being lost after submitting form
echo <<<BODYDOC
<label>Weight</label>
<input type="text" name="weight[]" required /> \n
<label>Reps</label>
<input type="number" name="reps[]" required /> \n
<label>Rest Time</label>
<input type="number" name="rest[]" required /> \n
<label>Notes</label>
<textarea name="notes[]"></textarea>
<input type="hidden" name="set[]" value='$j' />
<input type="hidden" name='mySelect' value='$template' />
</fieldset>
BODYDOC;
$j++;
} //End form for loop
echo "<br /><button type='submit' name='logSubmit'>Submit</button>\n";
echo "</fieldset>\n";
echo "</form>\n";
echo "<p><a href='newday.php'>Back</a></p>\n";
//Increment exerciseNameArray counter so next form dispays next exercise name
} //End if empty submit
if (isset($logSubmit)) {
//POSTed
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];
$user = $_SESSION['email'];
//Increment exercise name counter
$nameCount++;
//Update Log
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date, $nameCount, $exerciseIDArray);
} //End else if
} //End buildLog($template, $x) function
function updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date, $nameCount, $exerciseIDArray) {
//Insert data with query
$numRows = count($exerciseArray);
//Insert user,exercise name, and date
$insert = "INSERT INTO stats_resistance
(user, exerciseName, date)
VALUES
('$user','$exerciseArray[$nameCount]', '$date')"
or
die(mysql_error());
$result = mysql_query($insert)
or
die("<b>Query Failed</b><br>$insert<br>" . mysql_error());
//Query for stat_ID
$query = "SELECT statsID
FROM stats_resistance
WHERE user = '$user'
AND exerciseName = '$exerciseArray[$nameCount]'
AND date = '$date'";
//Get result
$result = mysql_query($query)
or
die("<b>Query Failed</b><br>$query<br>" . mysql_error());
$statsID = mysql_fetch_object($result);
$statsID = $statsID->statsID;
//echo "statsID = " . $statsID;
//Insert into resistanceSets with statsID as foreignKey
//Can insert multiple value sets by including comma after set parentheses
$insert = "INSERT INTO resistanceSets
(statsID, exerciseID, setID, exerciseName, weight, numReps, rest, notes)
VALUES
('$statsID', '$exerciseIDArray[$nameCount]', '$set[0]', '$exerciseArray[$nameCount]', '$weight[0]', '$reps[0]', '$rest[0]', '$notes[0]'),
('$statsID', '$exerciseIDArray[$nameCount]', '$set[1]', '$exerciseArray[$nameCount]', '$weight[1]', '$reps[1]', '$rest[1]', '$notes[1]'),
('$statsID', '$exerciseIDArray[$nameCount]', '$set[2]', '$exerciseArray[$nameCount]', '$weight[2]', '$reps[2]', '$rest[2]', '$notes[2]')";
$result = mysql_query($insert)
or
die("<b>Query Failed</b><br>$insert<br>" . mysql_error());
//buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray);
} //End updateLog()
It's a simple matter of ensuring the variable is set, if it is then increment it like any other variable.
if(isset($_SESSION['nameCount'])) {
$_SESSION['nameCount']++;
}
Alternatively, given you've set the value of the session variable to a local variable you can increment this local variable and reassign that value to the session variable. I.e.
$nameCount++;
$_SESSION['nameCount'] = $nameCount;
Both will have the same result.

{php} Column count doesn't match value count at row 1

I make a add forum
if ($_SERVER['REQUEST_METHOD'] == "POST" AND isset ($_REQUEST['addfinal'])) {
$name_1 = clear_form_text ($_REQUEST['name_1']);
$name_2 = clear_form_text ($_REQUEST['name_2']);
$car_name = intval ($_REQUEST['id_car_name']);
if (empty ($name_1)) $stop .= "Error text!<br>";
if (empty ($name_2)) $stop .= "Error text!<br>";
if ($stop == false) {
$db->query ("INSERT INTO car_class (name_1, name_2, id_car_name) VALUES ('$name_1', '$name_2' '$car_name')") or die ($db->error);
$infomessage = "<div class=\"attention-box attention-success\"><p class=\"text-muted\">Add success. Back</p></div>";
} else {
$infomessage = "<div class=\"attention-box attention-danger\"><p class=\"text-muted\">" . $stop . " Врати се назад</p></div>";
}
} else {
$result = $db->query("SELECT id, name FROM car_name");
while ($row = $result ->fetch_array())
$arrayrow[] = $row;
foreach ($arrayrow as $row) {
$select .= "<option value='".$row['id']."'>".$row['name']."</option>";
}
$template->set_block ('car_class-add', '', 'car_class');
$template->set ('car_name', $select, 'car_class');
}
The Select need to read values from car_name (id, name) and writes it id in car_class
But when i click on submit give me
Column count doesn't match value count at row 1
Where is the problem with this code?
Thank you
EDIT
Problem from above is solved.
NOW script work but do not write value in id_car_name Only write 0
car_class.id_car_na‌​me = car_name.id Why still this problem?
You must add comma after '$name_2' :
$db->query ("INSERT INTO car_class
(name_1, name_2, id_car_name)
VALUES ('$name_1', '$name_2', '$car_name')")
or die ($db->error);

PHP Friend Relationship between 2 rows?

first time I've used this site .. I've had a good look around but I cant seem to find the answer to my question. It's been answered in other ways but not for what I want I think..
Image of the database table so it's easy to see: http://puu.sh/6BtmZ.png
So basically I've got a friends.php page that has an input field and submit button, you put a username in and press submit and I want it to send a request to that user; I've got that to work, the user can accept but it only places the "friend" into him. As in FRIENDA is friends with FRIENDB but on FRIENDB's page he isn't friends with FRIENDA .. I hope this makes sense.
I just basically want it so, you send a request and the person accepts it and BOTH parties can see each other as friends.
<?php
include 'core/init.php';
// check
protect_page();
include 'includes/templates/header.php';
$user_id = $user_data['user_id'];
if (empty($_POST) === false) {
$required_fields = array('username');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'You need to enter a username to send a request!';
break 1;
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === false) {
$errors[] = 'Sorry, the username \'' . htmlentities($_POST['username']) . '\' doesn\'t exist.';
}
}
}
if (isset($_GET['success']) && empty($_GET['success'])) {
echo 'Friend request sent!';
} else {
if (empty($_POST) === false && empty($errors) === true) {
// add friend
$username = $_POST['username'];
$get_userid = mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'");
$row = mysql_fetch_array($get_userid);
$username_id = $row[user_id];
$user_id = $user_data['user_id'];
mysql_query("INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')");
//redirect
header('location: friends.php?success');
//exit
exit();
} else if (empty($errors) === false) {
// output errors
echo output_errors($errors);
}
}
?>
<h1>Friends</h1>
<p>
<h2>Send a friend request:</h2>
<form id="friend_request" action="" method="POST">
<ul>
<li>Username: <input type="text" name="username"><input id="friend_request" type="submit"></li>
</ul>
</form>
</p>
<p>
<h2>Pending requests:</h2>
<?php
if(isset($_POST['decline'])){
$decline_id = $_POST['decline_friend_id'];
$decline_query = "DELETE FROM `users_friends` WHERE `id` = $decline_id";
$accept_result = mysql_query($decline_query);
}
if(isset($_POST['accept'])){
$accept_id = $_POST['accept_friend_id'];
$accept_query = "UPDATE `users_friends` SET `request_pending` = 0 WHERE `id` = $accept_id";
$accept_result = mysql_query($accept_query);
}
$result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 1");
while($requests_row = mysql_fetch_array($result)) {
$get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$requests_row[user_id]'");
$get_username_row = mysql_fetch_array($get_username);
$request_from = $get_username_row[username];
echo 'Request from: ' . $request_from . '<form id="decline" action="" method="POST">
<input type="hidden" name="decline_friend_id" value="' . $requests_row['id'] . '">
<input type="submit" value="Decline" name="decline">
</form>
<form id="accept" action="" method="POST">
<input type="hidden" name="accept_friend_id" value="' . $requests_row['id'] . '">
<input type="submit" value="Accept" name="accept">
</form>';
echo '<br />';
}
?>
</p>
<h2>Your friends:</h2>
<?php
$friends_result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 0");
while($friends_row = mysql_fetch_array($friends_result)) {
$get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$friends_row[user_id]'");
$get_username_row = mysql_fetch_array($get_username);
$friend = $get_username_row[username];
echo $friend . '<br />';
}
?>
</p>
<?php include 'includes/templates/footer.php'; ?>
Hopefully someone might be able to help? Thanks in advance!
What you probably want to do is insert both directions in the friends relationship once both friends have confirmed. So instead of doing this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')
You would do this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id'),('$username_id','$user_id')
This would allow you to do the friend lookup in either direction.
What is unclear to me however is how you store pending friend requests in your database. So what you may ultimately need to do is to insert those relations in the DB and then simply update those DB records to change the value of an "accepted" flag once the friendship has confirmed.
If the structure of "users_friends" table looks like this:
me friends_with request_pending
to get the result (= if the user is your friend):
"SELECT * FROM `users_friends` WHERE (`friends_with` = '$user_id' AND `me`= `$me`) OR (`friends_with` = '$me' AND `me`= `$user_id `) AND `request_pending` = 0"
You check if the user is in friends_with where YOU are in me.. or if the user is in me and you're in friends_with

Error with UPDATE query not updating my MySql database

I am trying to pass an array of data to a Update query, to update customer records. However for some reason the ?success page is showing saying my details have been updated, however they aren't. If I debug and echo
echo implode(', ', $update);
die();
I get the result
mem_first_name = 'Josh', mem_last_name = 'smith', mem_email = 'j.smith#gmail.com', allow_email = '0'
Which looks fine to me. This is my update_user function
function update_user($mem_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id` = '$mem_id'") or die(mysql_error());
}
And my $update_data array
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
$message = 'Your details have been updated';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$update_data = array(
'mem_first_name' => $_POST['mem_first_name'],
'mem_last_name' => $_POST['mem_last_name'],
'mem_email' => $_POST['mem_email'],
'allow_email' => ($_POST['allow_email']) ? 1 : 0
);
update_user($session_member_id, $update_data);
header('Location: settings.php?success');
exit();
} else if (empty($errors) === false) {
$message = output_errors($errors);
}
}
So I have worked out I am losing my backticks after I implode, thus the column names don't have back ticks
This is some sort of typo (and thus not a real question of course).
You are adding backticks to your fields
$update[] = '`' . $field . '`
^ here
But they are absent in the debug out.
So, you are either run or post wrong code, which makes whole question pointless.
check connection with db, and table field name spells., i think no problem in this code.

Categories