PHP to SQL on-change not updating - php

I have a fairly general problem. I have a small form
<form action="<?=base_url();?>ticket/close_ticket/<?=$ticket_details['id'];?>" method="post" id="close_ticket" name="close_ticket">
<ul>
<li><label for="frm_status">Status<span class="req">*</span></label>
<span class="input">
<select id="frm_status" name="status" onchange="this.form.submit()">
<option value="<? if ($ticket_details['status'] == "Open") $status= "1"; else $status= "2"; echo $status;?>"><? if ($ticket_details['status'] == "Open") $status= "Open"; else $status= "Closed"; echo $status;?></option>
<option value="<? if ($ticket_details['status'] == "Open") $status= "2"; else $status= "1"; echo $status;?>"><? if ($ticket_details['status'] == "Open") $status= "Closed"; else $status= "Open"; echo $status;?></option>
</select>
</span>
</li>
</ul>
</form>
This form contains the drop list option box, that on change submits the form to the close ticket controller......
public function close_ticket()
{
$this->load->model('ticket_model');
$ticket_id = mysql_real_escape_string($this->uri->segment(3));
if($_POST)
{
//save ticket
unset ($_POST['id']);
$_POST['id'] = $ticket_id;
$this->ticket_model->close_ticket($_POST);
redirect(base_url().'ticket/edit/'.$ticket_id.'/');
return;
}
redirect(base_url().'ticket/edit/'.$ticket_id.'/');
}
which it does. This controller is to post the information to the model to update the SQL.....
public function close_ticket($ticket_post)
{
$query = $this->db->query("SELECT id FROM ".$this->tables_ticket." WHERE id = '".mysql_real_escape_string($ticket_post['id'])."';");
if($query->num_rows() > 0)
{
$row = $query->row();
$query = $this->db->query("UPDATE ".$this->tables_ticket."
SET
status = '".mysql_real_escape_string($ticket_post['status'])."'
WHERE
id = '".mysql_real_escape_string($ticket_post['id'])."'
");
}
if($this->db->affected_rows() > 0) return true;
else return false;
}
then after all this, redirect back to the form. I am assuming that on redirect the form will then populate the drop list with the updated data. This is where I am struggling, as It sends the changed data, and somewhere it is not registering the change and returning the page, unchanged.
Question, would this work with a confirmation/secondary submission page, followed by redirect, and is it that I am trying to return the changed data in the same function where it is failing?
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['customer_list'] = $this->ticket_model->get_customer_details($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
The edit function simply returns a range of population query lists.
unless i need a new query to repopulate the ticket_details list?

Related

Dropdown to read in and sort users with PHP

I am working on a project where I need to read in users (am using MySQL) and be able to sort 1. Men/Women 2. Salary (eg. 30k+, 50k+, 100k+...)
I've tried setting up a select dropdown but for some reason it's showing only the men, even if I select women.
<form action="#" method="post">
<select name="Gender">
<option value=''>Select Gender</option>
<option value="Men">Men</option>
<option value="Women">Women</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
if(isset($_POST['submit']) && $_POST['submit'] = "Men"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
elseif (isset($_POST['submit']) && $_POST['submit'] = "Women"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
else {
print("-");
}
You've assigned the values in the ifs instead of comparing against them. Also, you've used the wrong input to compare against. $_POST['submit'] will always contain the value Get Selected Values.
if (isset($_POST['submit']) && $_POST['Gender'] === "Men") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} elseif (isset($_POST['submit']) && $_POST['Gender'] === "Women") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} else {
print("-");
}
Here's the code a little more simplified and less redundant. And under the assumption that you're using PHPs PDO.
if (strtolower($_SERVER['REQUEST_METHOD']) === 'post') {
$gender = $_POST['Gender'] ?? null; // your old $selected_val variable
if (!$gender) {
// do something to abort the execution and display an error message.
// for now, we're killing it.
print '-';
exit;
}
/** #var PDO $dbConnection */
$dbConnection = create_Conn();
$sql = 'SELECT * FROM users WHERE kon = :gender';
$stmt = $dbConnection->prepare($sql);
$stmt->bindParam('gender', $gender);
$stmt->execute();
foreach ($stmt->fetchAll() as $user) {
if (isset($_SESSION['anvnamn'])) {
// Prints user data
} else {
// Prints user data but emails
}
}
}
As Dan has provided a grand answer prior to mine, this is now just a tack on for something to review.
If you look at your form you have two elements.
On Submission, your script will see..
Gender - $_POST['Gender'] will either be '', 'Men', or 'Women'
Submit - $_POST['submit'] will either be null or the value "Get Selected Values".
It can only be null if the php file is called by something else.
You can see this by using the command print_r($_POST) in your code just before your first if(). This allows you to test and check what is actually being posted during debugging.
So to see if the form is posted you could blanket your code with an outer check for the submit and then check the state of Gender.
The following has the corrections to your IF()s and some suggestions to also tidy up the code a little bit.
<?php
// Process the form data using Ternary operators
// Test ? True Condition : False Condition
$form_submitted = isset($_POST['submit'])? $_POST['submit']:FALSE;
$gender = isset($_POST['Gender'])? $_POST['Gender']:FALSE;
if($form_submitted){
if($gender == 'Men') {
// Stuff here
}
else if($gender == 'Women') {
// Stuff here
}
else {
print("-");
}
} else {
// Optional: Case where the form wasn't submitted if other code is present.
}
You could also consider using the switch / case structure. I'll leave that to you to look up.

How to make my text view get id from my session?

I want to show session data in a text box. I use the following model to get the id and show the data in a drop-down menu. But I don't know how to get [id_dosen] from the session from my database. How can I do that?
This is my _dosen_model.php_:
public function getDosen(){
$this->db->order_by('id_dosen','ASC');
$dosen= $this->db->get('dosen');
return $dosen->result_array();
}
This is my controller for my login:
public function login() {
$user = $_POST['user'];
$pass = $_POST['pass'];
$QuerySaya = $this->db->query(
"SELECT * FROM user LEFT JOIN mahasiswa ON user.id_user=mahasiswa.id_user LEFT JOIN dosen ON user.id_user=dosen.id_user
WHERE user.username='$user' AND user.password='$pass';"
);
if ($QuerySaya->num_rows() == 0) {
$this->load->view('login');
} else {
$data = $QuerySaya->row();
$this->session->set_userdata('id_admin_ti', $data->id_user);
$this->session->set_userdata('username', $data->username);
$this->session->set_userdata('password', $data->password);
$this->session->set_userdata('level_user', $data->level_user);
$this->session->set_userdata('id_kelas', $data->id_kelas);
$this->session->set_userdata('id_dosen', $data->id_dosen);
$this->session->set_userdata('id_mhs', $data->id_mhs);
$level = $this->session->userdata('level_user');
if ($level == 'mahasiswa') {
$this->load->view('dashboard_mhs', $data);
}else if($level == 'admin'){
$this->load->view('dashboard', $data);
}else if($level == 'dosen'){
$this->load->view('dashboard_dosen', $data);
}
}
}
And this is my view:
<select id="dosen" name="dosen" class="required form-control input-xs" placeholder="Mata Kuliah" type="text" required="required">
<option>-Nama Dosen-</option>
<?php
foreach ($dosen as $a) {
echo "<option value=".$a['id_dosen'].">".$a['nama_dosen']."</option>";
}
?>
</select>

Select all data after selecting another option

I am trying to create a submission on a form where I can show all results from a table as well as show individual results. I can achieve the page load to show all until the form is submitted, however when I then try and select all again im struggling.
On page load im simply doing:
<?php
if (isset($_POST['submit'])) {
$teamData = $_POST['teamData'];
var_dump($teamData);
$sql = "SELECT * FROM team WHERE dashboardId = 1 AND id = $teamData";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$teamName = $row['name'];
}
}
} else {
$teamName = 'All';
echo 'no submission yet';
}
?>
Setting the variable to say 'all'
<p>Team: <?php echo $teamName; ?></p>
Once an option has been selected it check the database and uses the name of and sets it. However in the dropdown list if i want to show all results again i get an error of:
Undefined variable: teamName
which makes sense because of my form:
<form method="POST" action="">
<select name="teamData">
<option selected value="" disabled>Select your team</option>
<option value="allTeamData">All team data</option>
<?php teamMembers(); ?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
I am just struggling to understand the logic of how to select all again from the drop down.
$teamName = 'All'; // Initialise the variable at top
// Change the condition to this for better restriction
if ($_POST && isset($_POST['submit'])) {
$teamData = $_POST['teamData'];
var_dump($teamData);
$sql = "SELECT * FROM team WHERE dashboardId = 1 AND id = $teamData";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$teamName = $row['name'];
}
}
}

PHP post hexadecimal values from option and store to mysql in string format

I need to store a hexadecimal value (values posted from my <options>) to my mysql database without transforming it (stay as is in string form) so that I can compare that value to my select options in string form. I've tried a lot of things, like base_convert(), (string), hex2bin(), but unfortunately. I don't know how to do this.
The image shows the stored value.
This is what I have done so far.
login.php:
$q = mysqli_query($con, "select * from users where email = '$email' and password = '$password'");
if (mysqli_num_rows($q) == 0)
{
$response['message'] = "Account not found.";
}
else
{
$_SESSION['user_currency'] = (string)$f['user_currency'];
}
dasboard.php:
<form id="form_setting_currency">
<select name="select_currency_symbol" class="form-control">
<option value="$" <?php echo $_SESSION['user_currency'] == "$" ? "selected" : ""; ?> >$ Dollar</option>
<option value="¢" <?php echo $_SESSION['user_currency'] == "¢" ? "selected" : ""; ?> >¢ Cent</option>
<option value="£" <?php echo $_SESSION['user_currency'] == "£" ? "selected" : ""; ?> >£ Pound Sterling</option>
<option value="¥" <?php echo $_SESSION['user_currency'] == "¥" ? "selected" : ""; ?> >¥ Yen</option>
</select>
</form>
SUBMIT_change_currency.php
<?php
include "includes/connection.php";
require_once("includes/encryption.class.php");
$response['success'] = false;
$response['message'] = "An error has occurred.";
if(isset($_POST['select_currency_symbol']) && trim($_POST['select_currency_symbol']) != "")
{
$currencyIcon = mysqli_real_escape_string($con,$_POST['select_currency_symbol']);
// $currencyIcon = mysqli_real_escape_string($con,hex2bin($_POST['select_currency_symbol']));
// $currencyIcon = mysqli_real_escape_string($con,(string)$_POST['select_currency_symbol']);
$query ="UPDATE users SET user_currency = '$currencyIcon' WHERE user_id = $_SESSION[user_id]";
mysqli_query($con,$query);
if(mysqli_affected_rows($con)>0)
{
$response['success'] = true;
$response['message'] = "Successfully changed currency symbol.";
$_SESSION['user_currency'] = (string)$currencyIcon;
}
else
{
$response['message'] = "You have not made changes.";
}
}
die(json_encode($response));
?> `
You need to print it with htmlspecialchars() in the value, so it becomes & amp;#x24

PHP : Not able to show value retrieved from database into dropdown

I have an Task creation - View - Edit page. Once I create the task and user wants to edit it. He clicks edit button. So the value gets populated according to id. All the value gets populated except for Dropdown.:
This are my dropdowns :
<b>Assignee: &nbsp &nbsp &nbsp &nbsp </b><select name = "assignee" value = <?php echo $assignee ?></select>
<b>Priority:</b><select name = "priority" value= "<?php echo $priority; ?>" id="priority"><option>Low</option><option>Medium </option><option>High</option></select>
<b>Status: </b><select name = "status" value= "<?php echo $status; ?>" ><option>Assigned</option><option>Yet to Start </option><option>In Progress</option><option>Completed</option><option>Blocked</option></select>
This is code for getting the values and showing in table and updating to database
<?PHP
function renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, $error) {/connecttothedatabaseinclude ('configdb1.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit'])) {
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])) {
// get form data, making sure it is valid
$id = $_POST['id'];
$task = $_POST['task'];
$comments = $_POST['comments'];
$assignee = $_POST['assignee'];
$priority = $_POST['priority'];
$status = $_POST['status'];
$dataum1 = $_POST['dataum1'];
$dataum2 = $_POST['dataum2'];
// check that firstname/lastname fields are both filled in
if ($task == '' || $comments == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, $error);
} else {
// save the data to the database
mysql_query("UPDATE work SET task='$task', comments='$comments', assignee='$assignee', priority='$priority', status='$status', dataum1='$dataum1', dataum2='$dataum2' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
} else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM work WHERE id=$id") or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if ($row) {
// get data from db
// get data from db
$task = $row['assignee'];
$comments = $row['2'];
$assignee = $row['assignee'];
$priority = $row['priority'];
$status = $row['status'];
$dataum1 = $row['dataum1'];
$dataum2 = $row['dataum2'];
// show form
renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, '');
} else
// if no match, display result
{
echo "No results!";
}
} else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
The select element does not have a value attribute - the selected option has a selected attribute.
In other words, you want something like:
<select name = "priority" id="priority">
<option <?php if ($priority == 'Low') { echo 'selected="selected"'; } ?>>Low</option>
<option <?php if ($priority == 'Medium') { echo 'selected="selected"'; } ?>>Medium </option>
<option <?php if ($priority == 'High') { echo 'selected="selected"'; } ?>>High</option>
</select>

Categories