Update query executing but not updating table - php

I am having difficulties using the UPDATE statement with a WHERE clause
I am using the following code to try to update a record in the table WHERE squadnumber is the value in the squadnumber dropdown.
<img src="header.png" alt="Southside FC Header">
<h1>Player Statistics</h1>
<?php
require("config.inc.php");
if (!empty($_POST)) {
//initial query
$query = "UPDATE playerstatistics SET squadnumber=':squadnumber', appearances=':appearances', subappearances=':subappearances',
goalsscored=':goalsscored', yellowcards=':yellowcards', redcards=':redcards' WHERE squadnumber=':squadnumber'";
//Update query
$query_params = array(
':squadnumber' => $_POST['squadnumber'],
':appearances' => $_POST['appearances'],
':subappearances' => $_POST['subappearances'],
':goalsscored' => $_POST['goalsscored'],
':yellowcards' => $_POST['yellowcards'],
':redcards' => $_POST['redcards']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
header('Location: http://localhost/webservice/errorCouldNotAddData.php');
die(json_encode($response));
}
$response["success"] = 1;
header('Location: http://localhost/webservice/managerhomepage.php');
echo json_encode($response);
} else {
?>
<br />
<form action="addplayerstatistic.php" method="post">
Squad Number: <br />
<select name="squadnumber">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
</select>
<br />
Number of appearances:<br />
<input type="number" name="appearances"/><br />
Number of appearances as a substitute:<br />
<input type="number" name="subappearances"/><br />
Number of Goals Scored:<br />
<input type="number" name="goalsscored"/><br />
Number of yellow cards:<br />
<input type="number" name="yellowcards"/><br />
Number of red cards:<br />
<input type="number" name="redcards"/><br />
<input type="submit" value="Add statistics" />
</form>
<img src="backButton.png">
<?php
}
?>
$response["success"] is being set to one as the query appears to have ran correctly, however when I check the database nothing has changed.
I think my problem surrounds the WHERE clause not being set to the number in the dropdown so no row is updated.
Any ideas?
Thanks

Try to update your query
$query = "UPDATE playerstatistics SET squadnumber=:squadnumber, appearances=:appearances, subappearances=:subappearances,
goalsscored=:goalsscored, yellowcards=:yellowcards, redcards=:redcards WHERE squadnumber=:squadnumber";
You should not escape your parameters - PDO does that for you.

Related

Working with session in PHP

I have a form from which i take some datas and using session i want to keep that datas as a history on my page, and also when i click on one line from my history i want my datas to be autocomplete in my form. I saw an example on one page and i tried doing it to apply to what i want but it's not quite functional.
This is my code for the form:
<form method="get">
Create:<br><br>
Name:<br> <input type="text" id="name" value="" /><br>
surname:<br> <input type="text" id="surname" value="" /><br>
Sex:<br> <div class="select-wrapper">
<select name="sex" id="sex">
<option value="">- Sex -</option>
<option value="woman">Woman</option>
<option value="male">Male</option>
</select>
</div>
Role: <div class="select-wrapper">
<select name="rol" id="rol">
<option value="">- Role -</option>
<option value="visitor">Visitor</option>
<option value="Professor">Professor</option>
<option value="Student">Student</option>
</select>
</div>
Text color: <div class="select-wrapper">
<select name="cul" id="cul">
<option value="">- Text color -</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
</select>
</div>
Font text: <div class="select-wrapper">
<select name="font" id="font">
<option value="">- Font text -</option>
<option value="15px Arial">Arial</option>
<option value="15px Times New Roman">Times New Roman</option>
<option value="15px Georgia">Georgia</option>
<option value="15px Comic Sans MS">Comic Sans MS</option>
<option value="15px Lucida Sans Unicode">Lucida Sans Unicode</option>
<option value="15px Courier New">Courier New</option>
</select>
</div>
Format : <div class="select-wrapper">
<select name="format" id="format">
<option value="">- Format -</option>
<option value="portrait">Portrait</option>
<option value="landscape">Landscape</option>
</select>
</div>
Style text: <div class="select-wrapper">
<select name="stil" id="stil">
<option value="">- Style text -</option>
<option value="stil1">Stil1</option>
<option value="stil2">Stil2</option>
<option value="stil3">Stil3</option>
<option value="stil4">Stil4</option>
<option value="stil5">Stil5</option>
<option value="stil6">Stil6</option>
</select>
</div>
</form>
And this is where i tried to use session:
<?php
session_start();
$createpas = parseRequest();
storecreatepas($createpas);
include "form.php";
$createpases = $_SESSION['createpases'];
include "history.php";
function storecreatepas($createpas) {
if (!isset($_SESSION['createpases'])) {
$_SESSION['createpases'] = [];
}
if (!$createpas->isEmpty()) {
$_SESSION['createpases'][] = $createpas;
}
}
function parseRequest() {
$createpas = new createpasRequest;
$createpas->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
$createpas->font = !empty($_GET['font']) ? $_GET['font'] : "";
$createpas->format = !empty($_GET['format']) ? $_GET['format'] : "";
$createpas->stil = !empty($_GET['stil']) ? $_GET['stil'] : "";
return $createpas;
}
/**
* createpas request
*/
class createpasRequest
{
public $cul = "";
public $font = "";
public $format = "";
public $stil = "";
function toQueryString() {
$params = [
'cul' => $this->cul,
'font' => $this->font,
'format' => $this->format,
'stil' => $this->stil
];
return http_build_query($params);
}
function isEmpty() {
return !$this->cul || !$this->font || !$this->format || !$this->stil;
}
function culAsObject() {
return new DateTime($this->cul);
}
function fontAsObject() {
return new DateTime($this->font);
}
function formatAsObject() {
return new DateTime($this->format);
}
function stilAsObject() {
return new DateTime($this->stil);
}
}
And the display code:
<ul>
<?php
foreach ($createpases as $s) {
?>
<li><a href="search.php?<?php echo $s->toQueryString() ?>">
<?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?> - <?php echo $s->stil?>
</a></li>
<?php
}
?>
</ul>
It works just fine until some point. It gets my datas from my form posts them on the page but when i click on them they don't autocomplete in in my form. And also if i want the options to be unique in the list how can i do that? Right now if i complete the same datas 2 or 3 times they appear multiple times in my list.
Thank you for your help!
You need to start the session in the Form page and then check if the SESSION array contains the values to be echoed.
So your code will become:
<?php session_start();
if(!isset($_SESSION['name']){$_SESSION['name']=''}
if(!isset($_SESSION['sex']){$_SESSION['sex']=''}
if(!isset($_SESSION['rol']){$_SESSION['rol']=''}
?>
//this way you will not have issues on page first load before the user fills in the form
<form method="get">
Create:<br><br>
Name:<br> <input type="text" id="name" value="<?php echo $_SESSION['name']; ?>" /><br>
surname:<br> <input type="text" id="surname" value="" /><br>
Sex:<br> <div class="select-wrapper">
<select name="sex" id="sex">
<option value="" <?php if($_SESSION['rol']==''){echo 'selected'} ?>>- Sex -</option>
<option value="woman" <?php if($_SESSION['rol']=='woman'){echo 'selected'} ?>>Woman</option>
<option value="male" <?php if($_SESSION['rol']=='visitor'){echo 'selected'} ?>>Male</option>
</select>
</div>
Role: <div class="select-wrapper">
<select name="rol" id="rol">
<option value="" <?php if($_SESSION['rol']==''){echo 'selected'} ?>>- Role -</option>
<option value="visitor" <?php if($_SESSION['rol']=='visitor'){echo 'selected'} ?>>Visitor</option>
<option value="Professor"<?php if($_SESSION['rol']=='Professor'){echo 'selected'} ?>>Professor</option>
<option value="Student"<?php if($_SESSION['rol']=='student'){echo 'selected'} ?>>Student</option>
</select>
</div>
and so on.
It appears that your form does not auto-fill with the data because you do not have such a functionality implemented. This auto-complete functionality is not automatic, as in, the server does not do it for you.
Here is an example of what you need to do in order to get the autocomplete to work:
Name:<br> <input type="text" id="name" value="<?= $_SESSION['name'] ?>" /><br>
For the select to auto-complete, you'll need to do something like this:
<select name="cul" id="cul">
<option value="">- Text color -</option>
<option value="red" <? echo ($_SESSION['cul']==="red")?"selected='selected'":""; ?>>Red</option>
<option value="blue" <? echo ($_SESSION['cul']==="blue")?"selected='selected'":""; ?>>Blue</option>
<option value="black" <? echo ($_SESSION['cul']==="black")?"selected='selected'":""; ?>>Black</option>
</select>
This sets the value for each form element by directly setting the value / selected item using the $_GET data from a previous submission, or if there is no data, everything will be empty / default values.
Per a suggestion from one of the comments to this answer, I would like to point out that you must include "session_start()" to the top of the document if you wish to use the session variables on the document (if you have not done so already).
One question about the original question: is that first code block procedurally generated, or hand-typed?

PHP and SQL - How can I make this ID into a variable?

I am making a PHP website, and I want my user ID to load into the tickets table when you order a ticket. There is a webpage where you can select the ticket, the amount, and the ID is already given as a label.
The first code adds the data to my database
function best(){
global $db, $errors;
// receive all input values from the form
$ticket = e($_POST['tickety']);
$aantall = e($_POST['aantal']);
$usidd = e($_POST['usid']);
// form validation: ensure that the form is correctly filled
if (empty($ticket)) {
array_push($errors, "Ticket is verplicht");
}
if (empty($aantall)) {
array_push($errors, "Aantal is verplicht");
}
// order ticket if there are no errors in the form
if (count($errors) == 0) {
$con = new PDO("mysql: host=localhost; dbname=website", "root", "");
mysqli_query($db, $query);
$_SESSION['success'] = "Ticket besteld";
header('location: index.php');
$query = "INSERT INTO tickety (ticket, aantal, userid)
VALUES('$ticket', '$aantall', '$usidd')";
mysqli_query($db, $query);
}
}
This code defines the input fields
<form method="post" action="ticketpag.php">
<?php echo display_error(); ?>
<div class="input_group">
ID
</br>
<input type='hidden' name='usid'>
<h4><?php
echo $_SESSION['user']['id'];
?></h4>
</input>
Ticket
</br>
<select name='tickety'>
<?php
$query = "SELECT * FROM `stok`";
$result = mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<option>".$row['naam']."</option>";
}
?>
</select>
</br>
Aantal
</br>
<select name="aantal">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
</select>
</div>
<div class="input-group">
<button type="submit" class="btn" name="bestel_btn"> Bestellen</button>
Terug
</div>
</form>
Add $_SESSION['user']['id']; to an input field instead of a label and it should work.
Example:
<input type="hidden" name="usid" id="usid" value="<?php echo $_SESSION['user']['id'];?>" />
Hidden fields are not shown to a user.
Addition:
But, as #mickmackusa mentioned, sending existing SESSION data using a POST request is a bad-practise. Instead test and see what happens when you echo $_SESSION['user']['id'] inside of best(). You should not be using POST to deliver existing SESSION data.

Stop Upload to SQL database if permission is not granted

I need to stop data being uploaded to the database when permissions are not granted. Is there a way to kill the session and only permit my script to upload data if permission has been granted.
PAGE 1:
<?php
session_start();
$_SESSION['user']='studentadmin';
?>
<!DOCTYPE html>
<html>
<head>
<style >
body {background-color: rgb(255,66,69);}
h3{font-size: 250%};
h4{font-size: xx-small;}
</style>
<title>Student Examinations 2017 </title>
<body>
<font style="font-family: Arial;";
<h4>Chichester Secondary School</h2>
<div align="center">
<h3>End of Year Examinations 2017</h1>
<i><p>Using the form below please submit examination results for the end of the academic year.</p></i>
<i><p>This years results are represented with the new government grading system. '9-1' rather than 'A*-G' </i></p>
<form action="MySQL.php" method="POST"><br>
<b> <br> Student: </b><br>
<br> First Name <br>
<input type="text" name="fname"><br/>
Last Name <br>
<input type="text" name="lname"><br/>
<br>
<br><b>Exam Board: <br></b><br>
<input type="radio" name = "examboard" value="AQA" checked> AQA
<input type="radio" name = "examboard" value="EdExcel" checked> EdExcel <br><br>
<b><br>Subject Grades: </b><br>
<br>
English<br>
<select name="Grade">
<option value="-">-</option>
<option value="9">9</option>
<option value="8">8</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br>
Maths<br>
<select name="Grade2">
<option value="-">-</option>
<option value="9">9</option>
<option value="8">8</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br>
Science<br>
<select name="Grade3">
<option value="-">-</option>
<option value="9">9</option>
<option value="8">8</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br>
<br> Additional Comments <br>
<textarea name ="additionalcomments" rows="2" cols="30"></textarea><br/>
<input type="submit" name="submit">
<input type="reset" name="reset">
<br>
</head>
</form>
</body>
</html>
PAGE 2:
<?php
session_start();
if (isset($_SESSION ['user'])) {
echo "Student record successfully created by user: " .$_SESSION['user'];
unset($_SESSION['user']);
} else {
echo 'You do not have permission to access this page. ';
}
?>
<?php
$DB_HOST = "localhost";
$DB_USERNAME = "admin";
$DB_PASSWORD = "chichester";
$DB_NAME = "results";
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$examboard = $_POST["examboard"];
$grade = $_POST["Grade"];
$grade2 = $_POST["Grade2"];
$grade3 = $_POST["Grade3"];
$additionalcomments = $_POST["additionalcomments"];
$conn = new mysqli($DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);
$sql = "INSERT INTO studentresults (name,lastname,examboard,additionalcomments,grade, grade2, grade3) VALUES ('$fname','$lname','$examboard','$additionalcomments','$grade','$grade2','$grade3')";
if ($conn->query($sql) === TRUE) {
}
$conn->close();
?>
<html>
<head>
<style >
body {background-color: rgb(255,66,69);}
h3{font-size: 500%};
h4{font-size: x-large;}
</style>
<title>Results </title>
<body>
<font style="font-family: Arial;";
When someone "doesn't have permission" this is what you do:
echo 'You do not have permission to access this page. ';
You simply tell them they don't have permission. But you continue to execute the code anyway. If you want the script to stop processing, something like the exit command would accomplish that:
exit('do not have permission to access this page. ');
Also of note... You're outputting a message indicating that a record was successfully inserted before you actually insert anything into the database. That's... optimistic. You should really only be indicating success to the user if the operation is successful. If the operation fails in some way, your users are going to be very confused.
This is how you start your code:
<?php
session_start();
$_SESSION['user']='studentadmin';
?>
Here you assume that studentadmin has logged in and you stored that as user. It is incorrect practice. Somehow you need to make sure that your admin is valid instead of assuming it.
Later you have this:
session_start();
if (isset($_SESSION ['user'])) {
echo "Student record successfully created by user: " .$_SESSION['user'];
unset($_SESSION['user']);
} else {
echo 'You do not have permission to access this page. ';
}
As David already pointed out, here, if there is no $_SESSION['user'], then you just echo a message and continue anyway. His suggestion of using exit is needed here, but only if you remove the part where you assign a value to $_SESSION['user'] anyway. However, damage is already done, users are already considered to be studentadmin. May I suggest that you should use a different key from now on, like $_SESSION['username'], so old, invalid $_SESSION['user'] values will not allow things which should not be allowed? But this will only work if you have a proper login screen where people enter their credentials, which are in turn validated and you only store $_SESSION['username'] if the credentials were valid.

How to combine several dropdown list values in mysql query?

<form method="post" action="search.php">
<select name="Num[]">
<option value="">Select One</option>
<option value="numofpeople">Number of people</option>
</select>
<select name="op[]">
<option value="">Select One</option>
<option value=">4">>4</option>
<option value=">2">>2</option>
</select>
<br />
<select name="num2[]">
<option value="">Select One</option>
<option value="price">Price</option>
</select>
<select name="op2[]">
<option value="">Select One</option>
<option value="<20000"><20000</option>
<option value="<40000"><40000</option>
</select>
<br />
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</form>
Here is my code to provide a dropdown list for the user. It will act as a filter to generate more specific result through mysql and don't get the logic to combine these dropdown values.
I would like to have something like:
Select * from hotel where price < 40000;
and I will provide all keywords after "Where".
Select boxes name are defined as array in html and your requirement is a user can select a single option in a select box. So you need to update the name of select boxes. You no need to add < in select box values, These conditions used at server end. I have corrected the HTML.
<form method="post" action="">
<select name="Num">
<option value="">Select One</option>
<option value="numofpeople">Number of people</option>
</select>
<select name="op">
<option value="">Select One</option>
<option value="4">>4</option>
<option value="2">>2</option>
</select>
<br />
<select name="num2">
<option value="">Select One</option>
<option value="price">Price</option>
</select>
<select name="op2">
<option value="">Select One</option>
<option value="20000"><20000</option>
<option value="40000"><40000</option>
</select>
<br />
<div class="input-group-btn">
<button class="btn btn-default" type="submit" name="search_btn"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
Server Side code for handle selected values and add to query.
if(isset($_POST['search_btn'])){
$conditons = array();
if(isset($_POST['Num'])){
$conditons[] = '`people` = "'.$_POST['Num'].'"';
}
if(isset($_POST['op'])){
$conditons[] = '`option` < '.$_POST['op'];
}
if(isset($_POST['price'])){
$conditons[] = '`price` = '.$_POST['price'];
}
if(isset($_POST['op2'])){
$conditons[] = '`op2` < '.$_POST['op2'];
}
$conditons = implode(' & ', $conditons);
echo $query = 'select * from hotel where '.$conditons;
}
You an update your real field name in conditions. After added conditions, result query will be as -
select * from hotel where `people` = "numofpeople" & `option` < 4 & `op2` < 20000
Here is a very generic example that I just put together. This code is not tested, but I have written like this before.
<?php
// Checks to see if post variables are available
if(isset($_POST)) {
// Creates original command
$query = "SELECT * FROM hotel WHERE "
// gets each value from the post
foreach($_POST as $key => $value) {
$query .= $key . "=" . $value . "AND ";
}
// Removes the trailing "AND "
$query = substr($query, 0, -4);
echo $query;
}
If you need to switch things up depending on key, you can just do a switch inside of the foreach statement that will check the key value. The key is the "name" attr that is assigned in the HTML that you are posting from.
This method is also not sanitized because I did not get a response to which connection type you are using, but it shouldn't be that hard. If you need me to write it, then I would be more than happy to do so.

php form using array

I want to create a form using array that user can select a number and echoes the number's corresponding object name after submit. I don't know why this code does not work, could someone please teach me how to do it the right way :( Thank you so much for your time.
<form name="train" method="GET" action="test.php">
<select name="object">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="all">Show All</option>
</select>
<input type="submit" name="submit" id="submit" value="submit" size="10">
</form>
<?php
$train[0] = "pencil";
$train[1] = "macaron";
$train[2] = "notes";
$train[3] = "book";
$train[4] = "eraser";
$train[5] = "cake";
$train[6] = "laptop";
$train[7] = "mint";
$train[8] = "cup";
if ($_GET['submit']) {
$train = $_GET['obejct'];
echo "<p>I have $train!</p>";
}
?>
Thank you so much!
Looks like you're setting $train to the value of whatever the form passes for the "object" select field, and then echoing that. You would expect then to see a number between 0 and 8, or the word "all" print out, but your reference of the object key has the word "object" misspelled as "obejct", so my guess is you're getting nothing to print as the value of $train.
Either way, what you really want to do is print the value at the key in the $train array that corresponds with what was provided by the user. This means that once you've created your array, which functions as a map, you must select the item from the array that you want to print.
You also need to handle the "all" case or you will get an error.
Here's how it would look if you continue using the array option:
<form name="train" method="GET" action="test.php">
<select name="object">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="all">Show All</option>
</select>
<input type="submit" name="submit" id="submit" value="submit" size="10">
</form>
<?php
$train[0] = "pencil";
$train[1] = "macaron";
$train[2] = "notes";
$train[3] = "book";
$train[4] = "eraser";
$train[5] = "cake";
$train[6] = "laptop";
$train[7] = "mint";
$train[8] = "cup";
if ($_GET['submit']) {
if ($_GET['object'] != 'all') {
//Handle the non-all case
$value = $train[$_GET['object']]; //This references a key in your array, like $train[0]
echo "<p>I have $value!</p>";
} else {
//Handle the all case here
}
}
?>

Categories