I'm building a single page application for finding a film based on genre. At the moment it uses the POST method on both the main form and the comments form.
The commments form currently gets the film ID using a GET method (this was chosen to avoid refreshing the page which resets the film suggestion process).
At the moment if I hit submit on the main form, the url changes to index.php? and the film successfully loads based on the criteria.
My question is: Why isn't my filmID echoing out in the main form? How can I stick the film ID into the current URL without using the GET method? So for instance if I typed in index.php?filmID=6 it would load up info about "The Dark Knight".
index.php (Trimmed by request)
//If submit comment pressed, get data and input
if(trim($_POST['submit']) == "Submit comment"){
$userID = $_SESSION['userID'];
$likeit = $_POST['yesornoList'];
$filmID = $_GET['filmID'];
$comment = clean_string($db_server, $_POST['commentBox']);
if ($comment != '') {
$query = "INSERT INTO comments (userID, filmID, comment, likeit)
VALUES ('$userID', '$filmID', '$comment', '$likeit')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server)) . $query;
echo $commentMessage = "<section>Thanks for your comment!</section>";
}
}else{
if (isset($_POST['genreList']) && ($_POST['genreList'] != "")){
$genre = clean_string($db_server, $_POST['genreList']);
//create the SQL query
$query = "SELECT * FROM films WHERE genreID=$genre ";
//$endquery = " AND (";
$endquery = "";
$orFlag = false;
if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){
$endquery .= " netflix IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " lovefilmInstant IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " blinkbox IS NOT NULL";
}
if($endquery != "") $query .= " AND (" . $endquery . ")";
$query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;";
//query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);
//if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
//Whether to display links or not for purchase and streaming
$filmID = $row['filmID'];
//Body content for film
$str_result =
"<section> This is where the film details are
</section>"
. $commentMessage . "
<section>
<form id='frmFilmComments' action='index.php?filmID=" . $filmID . "#comments' method='post'>
<a id='comments' class='anchor'></a>
<h3>Comments</h3>
<p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
<select class='selectbox' name='yesornoList'>
<option value='Yes'>Yes</option>
<option value='No'>No</option>
</select>
<p><span class='bold'>Provide your feedback here:</span></p>
<textarea id='commentBox' class='insertComment' rows='2' cols='30' name='commentBox'></textarea><br>
<input class='formButton' type='submit' id='submit' name='submit' value='Submit comment'/>
</form>
";
mysqli_free_result($result);
//Code to print comments goes here
}else{
$str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='#findafilm'>Please try again.</a></p></section>";
}
}else{
//$str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";
}
$message = $str_result . $likedcomments . $dislikedcomments . "<section/>";
}
}
//Exisiting code to handle options list
?>
<div id="top" class="content container headerMargin">
<div class="content wrapper">
<form id="frmFilmFinder" action="index.php?filmID=<?php echo $filmID; ?>" method="post">
<section>
<h2>Welcome <?php echo $_SESSION['username'] ?>!</h2>
<p class="underHeader">You are now logged in and ready to use the Film Finder.</p>
</section>
<section>
<a class="anchor" id="findafilm"></a>
<h3>Find a film</h3>
<h4>Choose a genre:</h4>
<select class="selectbox" name="genreList">
<?php echo $str_options; ?>
</select>
<h4>Choose a streaming service:</h3>
<input type="checkbox" class="checkbox" id="streamingCheckbox1" name="streamingCheckbox1" value="Netflix"><span class="checkboxText">Netflix</span><br>
<input type="checkbox" class="checkbox" id="streamingCheckbox2" name="streamingCheckbox2" value="LoveFilm"><span class="checkboxText">LoveFilm Instant</span><br>
<input type="checkbox" class="checkbox" id="streamingCheckbox3" name="streamingCheckbox3" value="blinkbox"><span class="checkboxText">blinkbox</span><br>
<input type="submit" class="formButton filmSearch" id="submit" name="submit" value="Submit"/>
<p><span class="italic">Leave all unticked if you wish to buy the film</span></p>
</section>
</form>
<?php echo $message; ?>
</div>
</div>
Principally, you need to be sure that $filmID is set when you write out your forms. It is valid to pass it in the query string (accessible via $_GET['filmID'] even though you are posting the form. It will work and serve its purpose, but be sure to comment what you're doing and why so you remember next time.
You populate it as $filmID = $_GET['filmID'] but only inside the form processing for your comments form. That means it won't be set unless you're receiving a comment. You ought to move that higher in the logic, checking always if it is set.
// near the top, outside if() conditions:
$filmID = isset($_GET['filmID']) ? $_GET['filmID'] : null;
Consider storing it into $_SESSION['filmID'] the first time you set it and any time it changes, so you have it on any script that needs it.
Finally, a side issue mentioned in the comments thread, working with MySQLi is a start, begin familiarizing yourself with how prepared statements work with bound parameters via mysqli::prepare(). All your query input variables should be handled via bound parameters, eliminating the need for escaping. This is a general best practice.
Related
This is just for a school project and it feels like such a simple problem but every time i google what seems to be the problem i just cant understand most of the answers
<form action="bookResults.php" method="get">
<h4>Book Search</h4>
<label for="searchType">Search Type:</label>
<select name="searchType" id="searchType">
<option value="title">Title</option>
<option value="author">Author</option>
<option value="isbn">ISBN</option>
</select><br>
<label for="searchTerm">Search Term:</label>
<input type="text" name="searchTerm"><br>
<a class="btn btn-primary" href="bookResults.php" role="button">Submit</a>
</form>
this is the form in html
<?php
if (!isset($_GET['searchType'])) {
$searchType = $_GET['searchType'];
if (!isset($_GET['searchTerm'])) {
$searchTerm = $_GET['searchTerm'];
echo $searchType;
echo $searchTerm;
if(!$searchType || $searchTerm){
echo 'You have not entered search details. Please go back and try again';
}else{
$mysqli = new mysqli('127.0.0.1:3306','zero','1234','mp7');
if ($searchType == 'title') {
$query = "select * from book where title like '%".$searchTerm."%'";
$result = $mysqli->query($query);
$resultCount = $result->num_rows;
echo "<p>Result for ".$searchType." : ".$searchTerm." </p>";
echo "<p>Number of books found: ".$resultCount."</p>";
for($ctr = 0;$ctr<$resultCount;$ctr++){
$row = $result -> fetch_assoc();
echo "<div class='card col-4'>";
echo " <div class='card-body'>";
echo " <h6>".$row['title']."</h6>";
echo " <p>By ".$row['author_name']."<br/>";
echo " ".$row['isbn']."</p>";
echo " </div>";
echo "</div>";
}
}
and this is my incomplete php code, the goal is to let the user choose with a dropdown menu between 3 categories in my book table in my database. its either they search by Author, title or isbn. But i cant even get to that part without getting this "undefined array key" error in the first few lines
EDIT: The next project i was supposed to work on involved prepared statements, the school just wanted us to use manual insertions i guess
You don't use an anchor to submit a form. You have to use a submit button. So change
<a class="btn btn-primary" href="bookResults.php" role="button">Submit</a>
to
<button class="btn btn-primary" type="submit" role="button">Submit</button>
When you use the anchor, none of the form fields are added to the URL.
You also have some problems in your PHP logic.
You can combine the tests for whether the parameters are set and properly filled in by using !empty(). You can test both parameters at once, rather than using nested if statements.
Your code is also wide open to SQL injection. You should use a prepared statement with parameters rather than substituting the variable into the SQL.
<?php
if (!empty($_GET['searchType']) && !empty($_GET['searchTerm'])) {
$searchType = $_GET['searchType'];
$searchTerm = $_GET['searchTerm'];
echo $searchType;
echo $searchTerm;
$mysqli = new mysqli('127.0.0.1:3306','zero','1234','mp7');
if ($searchType == 'title') {
$query = "select * from book where title like CONCAT('%', ?, '%')";
$statement = $mysqli->prepare($query);
$statement->bind_param("s", $searchTerm);
$statement->execute();
$result = $statement->get_result();
$resultCount = $result->num_rows;
echo "<p>Result for ".$searchType." : ".$searchTerm." </p>";
echo "<p>Number of books found: ".$resultCount."</p>";
for($ctr = 0;$ctr<$resultCount;$ctr++){
$row = $result -> fetch_assoc();
echo "<div class='card col-4'>";
echo " <div class='card-body'>";
echo " <h6>".$row['title']."</h6>";
echo " <p>By ".$row['author_name']."<br/>";
echo " ".$row['isbn']."</p>";
echo " </div>";
echo "</div>";
}
}
} else {
echo 'You have not entered search details. Please go back and try again';
}
I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
My table category has these columns:
idcategory
categorySubject
users_idusers
I have a form with a simple radio buttons and a textbox.
I have a select all statement for category and need to get the idcategory stored into a variable ($getCatId) so I can use this statement:
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
What is the best way to get and store categoryid?
if($_SERVER['REQUEST_METHOD'] != 'POST') //show form if not posted
{
$sql = "SELECT * FROM category;";
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class= 'choice'><input type='radio' name='category' value='". $row['idcategory'] . "'>" . $row['categorySubject'] ."</div></br>";
}
echo 'Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false)
{
echo 'You must be signed in to contribute';
}
else{
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
$result = mysqli_query($conn,$sql);
echo "Added!";
If I understand this question correctly, you'll have your $getCatId (id of the category) in $_POST['category'] (after sending form) in your case
The first thing you should do is protect yourself from SQL injection by parameterizing your queries before old Bobby Tables comes to pay you a visit.
You might also look into using PDO as I've demonstrated below because it's a consistent API that works with a lot of different database management systems, so this leads to wonderfully portable code for you. Here's an annotated working example on Github:
<?php
// returns an intance of PDO
// https://github.com/jpuck/qdbp
$pdo = require __DIR__.'/mei_DV59j8_A.pdo.php';
// dummy signin
session_start();
$_SESSION['signedIn'] = true;
$_SESSION['userid'] = 42;
//show form if not posted
if($_SERVER['REQUEST_METHOD'] != 'POST'){
$sql = "SELECT * FROM category;";
// run query
$result = $pdo->query($sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
// get results
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "
<div class= 'choice'>
<input type='radio' name='category' value='$row[idcategory]'/>
$row[categorySubject]
</div>
</br>
";
}
echo '
Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>
';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false){
echo 'You must be signed in to contribute';
} else {
// simulate your date input
$date = date("Y-m-d");
// bind parameters
$sql = "
INSERT INTO topic (
subject, topicDate, users_idusers, category_idcategory, category_users_idusers
) VALUES(
:subject, :topicDate, :users_idusers, :category_idcategory, :category_users_idusers
);
";
// prepare and execute
$statement = $pdo->prepare($sql);
$statement->execute([
'subject' => "($_POST[topic])",
'topicDate' => $date,
'users_idusers' => $_SESSION['userid'],
// to answer your question, here's your variable
'category_idcategory' => $_POST['category'],
'category_users_idusers' => $_SESSION['userid'],
]);
echo "Added!";
}
}
So I have a form to add a new item to database with a checkbox as follows
So my difficulty is the checkbox. I can easily enough create the array for all items checked but I need an ID for them along with it. I've tried to think of many ways and searched a lot but I just can't think of a way to get the ID in a way that is then useable to me along with the name of the feature (checklist). Since I have to get each feature item and add it to the table houses_has_features.
<?php
$title = 'Add a new house';
require_once 'header.php';
require_once 'nav.php';
require_once 'mysqli-con.php';
$conn = new MYSQLI($hn, $un, $pw, $db);
// If house name and type is set then add them into the database
if( !empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
$house_name = $conn->real_escape_string($_POST['h_name']);
$house_type = $conn->real_escape_string($_POST['h_type']);
//show names added
echo '<b>House name: </b>'.$house_name . '<br><b> House type:</b> ' . $house_type;
$query = "INSERT INTO `house_names` (`id`, `name`) VALUES (NULL, '$house_name')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
global $house_name_id;
$house_name_id = $conn->insert_id;
$query = "INSERT INTO `house_types` VALUES ('$house_name_id', '$house_type')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
} else {
global $house_name_id;
$house_name_id= NULL;
}
//Start container for page content
echo '<div class="container">';
//Display an error message if house name is filled in but not house type
if ( !empty($_POST['h_name']) && empty($_POST['h_type']) || empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
echo "<p class='error-text'>* Please fill in both the house name and house type *</p>";
}
$query_feat = $conn->query('SELECT * FROM features');
$rows = $query_feat->num_rows;
$features_list = $_POST['check_list'];
$feature_id = $_POST['feature_id'];
//display checked boxes.
if(isset($_POST['check_list'])) {
for ($i=0; $i<sizeof($features_list); $i++){
//echo '<br>House name id:' . $house_name_id . '<br> $_POST[] = ' . "$features_list[]";
print_r($features_list); echo '<br>';
print_r($feature_id);
}
}
// Add house form
echo <<<_END
<h1>Add a house</h1>
</div>
<div class="container">
<form action="add.php" method="post">
<p>House Name: <input type="text" name="h_name"></p>
<p>House type: <input type="text" name="h_type"></p>
<b>features:</b>
<ul class="list-group">
_END;
for ($c = 0 ; $c < $rows ; ++$c){
$query_feat->data_seek($c);
$feat = $query_feat->fetch_array(MYSQLI_NUM);
echo '<li><input type="checkbox" name="check_list[]" value="' .$feat[1]. '">'.$feat[1].'</li>';
}
echo <<<_END
<ul>
<input class="btn-primary" type="submit" value="Submit">
</form>
</div>
_END;
require_once 'footer.php';
I'm really lost on this one any help would be greatly appreciated :)
change your value of checkbox to id or anything you want.
<li><input type="checkbox" name="check_list[]" value="' .$feat[0]. '">'.$feat[1].'</li>
$feat[1] => $feat[0] or else
I have built a website where the user plays a simple guess the animal game with the system. The database that the script connects to is a one table binary tree, with each row having a node ID. I need to print the URL on screen that contains the current stage of the game so that if it were copied and pasted it would take another user to the same point. How do I do this?
$query = "SELECT `message`, `parentID`,`answerYesID`, `answerNoID`, `nodeID` FROM `creature`";
$where = "";
if(isset($_POST['answer'])){
$_SESSION['node'] = $_POST['answer'];}
elseif (isset($_SESSION['node'])){ $where = "WHERE `nodeID` = '{$_SESSION['node']}'";}
else { $where = "WHERE `parentID` IS NULL";}
?>
<?php
if (isset($_POST['reset'])){
$where = "WHERE `parentID` IS NULL";
$_SESSION['node'] = 1;
echo $_SESSION['node'];
}
if (isset($_POST['submit']) && (isset ($_POST['answer']))){
$where = "WHERE `nodeID` = '{$_POST['answer']}'";
}elseif (isset($_POST['submit']) && (!isset ($_POST['answer']))){
$where = "WHERE `nodeID` = '{$_SESSION['node']}'";
}
echo'<div class="form">';
$result = mysqli_query($dbconn, $query.$where);
$row = mysqli_fetch_assoc($result);
echo "<p class = \"answer\">";
echo$row['message'];
echo "</p>";
?>
<form action="assignment.php" method="POST">
<input type="radio" name="answer" value="<?php echo $row['answerYesID'];?>">Yes
<input type="radio" name="answer" value="<?php echo $row['answerNoID'];?>">No
<input type="submit" name="submit" value="submit" class = "submit">
<input type='submit' name='reset' value='reset' class = "reset">
click here...
</form>
</div>
<div class = "speech">
<span class= "welcome" ><h1>Welcome!</h1></span>
<p>My name is Barry and I'm the game keeper.<br>
This is the Creatures Expert Game. Answer <br>
the first question to begin. Let's see if I can <br>guess what creature you are thinking of!<br>
<br> Hit the reset button to restart at anytime.</p>
<a><img src="speech.png"></a>
</div>
<div class ="sparky">
<a><img src="sparkydog.png"></a>
</div>
<div class ="sign">
<a><img src="sign.png"></a>
</div>
</body>
</html>
the page is viewable at s573022.neongrit.net/assignment
Since you are using SESSION, instead of href="assignment.php" you can echo:
click here...
But the problem with your existing code is that you are setting $_SESSION['node'] only if you detect a $_POST['answer'] which is impossible if you do not submit a form.
Therefore, you need to first check if you have the nodeId set in the url like so at the very beginning of the file:
if (isset($_GET['nodeId']) && $_GET['nodeId'] != '') {
$_SESSION['node'] = $_GET['nodeId'];
}
else { //do whatever you do now to get the answer }