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

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.

Related

Pushing Data to a MySQL Database from a Form

I am trying to send data from an HTML form to a MySQL database in phpmyadmin. I have a database named bhs2018 and a table called game 1. Here are the contents of that table.
Here is my form:
<form name="game" action="insert.php" method="post">
<p> <select id="player" name = 'player'>
<option value="b">B</option>
<option value="n">N</option>
<option value="a">A</option>
<option value="c">C</option>
<option value="m">M</option>
<option value="j">J</option>
<option value="ja">Ja</option>
</select>
<select id="what" name = 'what'>
<option value="shoton">Shot on Cage</option>
<option value="shotoff">Shot off Cage</option>
<option value="goal">Goal</option>
<option value="countergoal">Goal on Counter</option>
<option value="countershot">Shot on Counter</option>
<option value="assist">Assist</option>
<option value="block">Block</option>
<option value="steal">Steal</option>
<option value="turnover">Turnover</option>
<option value="drawn">Ejection Drawn</option>
<option value="ejected">Ejected</option>
</select>
<select id="where" name = 'where'>
<option value="set">Set</option>
<option value="navy">Navy</option>
<option value="leftwing">1/2 side past 5</option>
<option value="rightwing">4/5 side past 5</option>
<option value="point">Point/3</option>
<option value="lefttwo">1/2 side 2 meter</option>
<option value="righttwo">4/5 side 2 meter</option>
<option value="1">6 on 5 1</option>
<option value="2">6 on 5 2</option>
<option value="3">6 on 5 3</option>
<option value="4">6 on 5 4</option>
<option value="5">6 on 5 5</option>
<option value="6">6 on 5 6</option>
</select>
<select id="quarter" name = 'quarter'>
<option value="q1">Quarter 1</option>
<option value="q2">Quarter 2</option>
<option value="q3">Quarter 3</option>
<option value="q4">Quarter 4</option>
</select>
<select id="time" name = 'time'>
<option value="0:30">0:30</option>
<option value="1:00">1:00</option>
<option value="1:30">1:30</option>
<option value="2:00">2:00</option>
<option value="2:30">2:30</option>
<option value="3:00">3:00</option>
<option value="3:30">3:30</option>
<option value="4:00">4:00</option>
<option value="4:30">4:30</option>
<option value="5:00">5:00</option>
<option value="5:30">5:30</option>
<option value="6:00">6:00</option>
<option value="6:30">6:30</option>
<option value="7:00">7:00</option>
</select>
Notes: <input type="text" id = 'notes' name = 'notes'>
<button type="submit" onclick="save()"> Save </button> </p>
</form>
Whenever I click my "Save" button, the insert.php script loads. Instead of echoing something, it just shows the code. Here is insert.php.
<?php
$con = mysqli_connect('127.0.0.1','root','password'(my actual password is here);
if(!$con){
echo 'Not Connected to Server';
}
if (!mysqli_select_db($con,'bhs2018')){
echo 'Not Selected';
}
$Player = $_POST['player'];
$Quarter = $_POST['quarter'];
$Time = $_POST['time'];
$Where = $_POST['where'];
$Notes = $_POST['notes'];
$What = $_POST['what'];
$sql = "INSERT INTO game1 (player,quarter,time1,where1,notes,what) VALUES ('$Player', '$Quarter', '$Time', '$Where','$Notes','$What')";
if(!mysqli_query($con,$sql)){
echo'Not Inserted';
}
else{
echo 'Inserted';
}
header('refresh:2; url=index.html');
?>
What is looking wrong with my code? Why does it not run the php script? Thank you so much!
Check your database. Your PRIMARY KEY player should be an integer like int(30) or bigint(200) but not varchar. Create a new column for PRIMARY KEY something like player_id and shift player to next column. Also when primary key is an integer, there is no manual insertion option for inputting it's value in your form. So make your PRIMARY KEY is set to AUTO_INCREMENT in case you don't want to insert it's value manually.

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 do I use PHP to query my SQL database using SELECT tag in html

Basically I'd like to use the choices which the user has selected from a different select tags, and in essence store these as variables which I can then use to query my database in SQL.
My HTML code is here:
<div id ="search_elements">
<img src="UniSelect.jpeg">
<select>
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select>
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
</div>
And the type of php i would be looking to use would be:
//$con=mysqli_connect("localhost","adam","YjM3ZTYwOTQ5OWRmYWZh","adam_...");
//if (mysqli_connect_errno())
// {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
// }
// Perform queries
//$sql=mysqli_query($con,"SELECT CONTENT FROM Blog WHERE ID = 01");
//$result=mysqli_fetch_assoc($sql);
//echo $result['CONTENT'];
//mysqli_close($con);
To make it clear once more, I want to use the different values which the user selects, upon clicking a search button, have these query results shown in a table.
This solution a little differs from yours because you have no provided your form, submit button, etc. but in general, after a few changes, it should work too:
<form method="post" action="">
<img src="UniSelect.jpeg">
<select name="university">
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select name="rent_price">
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
<input type="submit" value="Submit form">
</form>
And now, to get values of these (something like this and I recommend to place it above your form):
if (!empty($_POST)) {
// Checking connection in here
$university_id = mysqli_real_escape_string($con, $_POST['university']);
$rent_price = mysqli_real_escape_string($con, $_POST['rent_price']);
$sql = mysqli_query($con, "SELECT * FROM university WHERE name = '".$university_id."'");
$result = mysqli_fetch_assoc($sql);
// Same thing goes for rent price
}

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
}
}
?>

Update query executing but not updating table

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.

Categories