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'])
Related
I want to delete a row from a form select when i click on submit input with an sql query,(i think i am wrong on something, but i don't understand what) as you can see below for my example :
My list and the blue case i want to delete on submit
My actual code, and the $supp i want to do when the user click on submit
`
<form method="POST">
<select>
<?php
// Drop Down
$res = null;
$sql2 = "SELECT `sinistre_type` FROM `form_sinistre`";
$query2 = $db->prepare($sql2);
$query2->execute();
// INIT > PREP > EXEC > SUPP
$supp = "DELETE FROM `form_sinistre` WHERE `sinistre_type` = '$res'";
$query3 = $db->prepare($supp);
$sendbddsupp = $query3->execute();
echo "<option disabled selected>..Choix Possible..</option>\n";
while ($res = $query2->fetch(PDO::FETCH_NUM)) {
echo "<option name='res'>" . $res[0] . "</option>\n";
}
?>
</select>
<input type="submit" value="Supprimer">
</form>
`
Some $_POST config
`
<?php
session_start(); //debut de SESSION
include("config.php"); //Appel de la bdd
// ... INIT VARIABLES ...
$sinistre_type = "";
$sinistre_desc_dmg = "";
$list = "";
if (empty($_POST)) { // SANS COOKIES / POST
} else { // AVEC COOKIES / POST
$sinistre_type = $_POST['nom'];
$sinistre_desc_dmg = $_POST['vent'];
$res = $_POST['res'];
$sql = "INSERT INTO `form_sinistre` (sinistre_type, sinistre_desc_dmg) VALUES (:sinistre_type, :sinistre_desc_dmg)";
$query = $db->prepare($sql);
$query->execute(array(':sinistre_type' => $sinistre_type, ':sinistre_desc_dmg' => $sinistre_desc_dmg));
}
var_dump(isset($_POST['res']));
?>
`
(EDIT : my list is linked with my db and working that why i want to send sql query)
Thanks by advance for your help, if you need more information let me know :)
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.
PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
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}'";
I am passing the string value through link in the URL to the next page like this <a href="ApplicationRegister.php?plan=trial">
In the ApplicationRegister.php page, i am getting this value like this $plan = $_GET["plan"];
and i will put this into a session variable like this $_SESSION['plans'] = $plan;
Here i am getting the value. but after the if statement i am not getting the value for this plan even after using Session variable.
My complete code is like this
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $plans;
$myURL ="$_SERVER[HTTP_HOST]";
$myURL =$StoreName.'.'.$myURL;
if (stripos($myURL, 'www.') !== 0) {
$myURL = 'www.' . $myURL;
}
if (stripos($myURL, 'http://') !== 0) {
$myURL = 'http://' .$myURL;
}
if(stripos($myURL, '.com') !== 0) {
$myURL = $myURL . '.com';
}
echo $plans;
$RegistrationType = $_POST['RegistrationType'];
$Status = "Active";
$sql = "select * from plans where planname = '$plans'";
echo $sql;
mysql_query($sql) or die (mysql_error());
$planID = $row['planid'];
$query1 = "select count(CompanyEmail) from ApplicationRegister where CompanyEmail = '$CompanyEmail'" ;
$result1 = mysql_query($query1) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result1))
{
if($row['count(CompanyEmail)'] > 0)
{
$msg = "<font color='red'> <b>This E-mail id is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$query2 = "select count(URL) from ApplicationRegister where URL = '$myURL' ";
$result2 = mysql_query($query2) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result2))
{
if($row['count(URL)'] > 0)
{
$msg = "<font color='red'> <b>This Stroename is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$sql = "INSERT INTO ApplicationRegister(planid, CompanyName, CompanyEmail, CompanyContact, CompanyAddress, RegistrationType, ApplicationPlan, ApplicationStatus, URL, CreatedDate) VALUES ('$planID', '$CompanyName', '$CompanyEmail', '$CompanyContact', '$CompanyAddress', '$RegistrationType', '$plans', '$Status', '$myURL', NOW() )";
mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$_SESSION['application_id'] = $id;
if($plans == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
}
}
}
?>
Only in the beginning it holds the value , if i try to display it within theIf (isset($_POST['submit'])) it shows blank value for plans. Do not know what to do. Plz suggest
EDITED
Even after using like this, its the same. i do not know what may be the problem :(
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plans'] = $plans;
echo $_SESSION['plans'];
// $plan = +$plan;
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $_SESSION['plans'];
EDITED
In ApplicationRegister.php, i have passed the hiddenvalue which i got fro\m previous page like this
<input type="hidden" name="plan" value="<?php echo $plan ?>"/>
then POST method i have used this. Now i am getting the value for it. Thanks to all
EDITED
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
It's because you're not calling session_start() at the top of the page. You need that for your sessions to persist across requests (which is the point of sessions)
As well as not calling session_start();, this code is wrong:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
It should be:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plans'];
echo $_SESSION['plans'];
You are setting $_SESSION['plan'] and then trying to access $_SESSION['plans'].
Also, are you clicking a link or submitting a form? You say that you have a link, yet your code tries to access values passed from a form.
If you are using a form, don't use links. Instead, use a select element to select a plan, and then change $plan = $_GET["plan"]; to $plan = $_POST["plan"];.
EDIT:
For the redirection problem, try this code:
echo "<pre>** Plan Name: **\n";
var_dump($PlanName);
echo "</pre>";
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location: PaymentGateway.php");
exit();
}
and see what it outputs.
When someone clicks the link, it's going to set the variable properly. However, it's not going to hit the $_POST['submit'] logic, because it's not a post, just a get. Then, assuming your actually posting to that page at a later point, trying to access anything in $_GET will be null, and will then reset the session variable to null.
Your first page should have code something like this
<form action="ApplicationRegister.php" method="post">
<select name="plan">
<option value="trial">Trial</option>
</select>
<input type="submit"/>
</form>
Then, you check for $_POST['plan'] and $_POST['submit']