Im writing a page in HTML and PHP that connects to a Marina database(boats,owners etc...), displays all of the owners last names in a drop down list and then displays all the boats under the last name that was chosen.
here is my relevant code...
$sql = 'select LastName from Owner';
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$values[] = array(
'LastName' => $row['LastName']
);
}
echo '<form align="left" top="200" action="page2.php" method="post">
<p>Select an owner:</p>
<select top="200" name="form1" id="form1">';
foreach($values as $v){
echo '<option value="'.$v['LastName'].'">'.$v['LastName'].'</option>';
}
echo '</select>
<input type="submit" value="Submit">
</form>';
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql = 'select BoatName from MarinaSlip,Owner where MarinaSlip.OwnerNum = Owner.OwnerNum and Owner.LastName = '.$form1;
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values[] = array(
'BoatName' => $row['BoatName']
);
}
echo '<ol>';
foreach($values as $v){
echo '<li>'.$v.'</li>';
}
echo '</ol>';
}
I have managed to properly display the last names in the drop down list and keep the name chosen as a variable but I am running into a few errors that I cannot solve.
1) when I attempt to reload the page(using Firefox) I get a message "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier" So i was wondering how I could code it so that I don't need to have data being sent initially.
2)After a last name is submitted and I attempt to run a query to match all the boats under that last name I get an error that the $result variable is not a MYSQLI result type even though I used the same code earlier in the script.
I am new to HTML and PHP so any help is greatly appreciated.
That message happens when you reload a page that was the result of a form submission. It means it has to resubmit the form to reproduce the same result. The way to prevent it is to have the form redirect the user to a page that displays the result, rather than displaying the result itself. This can be complicated unless the form submission just makes a change to the database, and then you want to display the contents, rather than display something dependent directly on the form submission.
You need to put quotes around the name:
$sql = 'select BoatName from MarinaSlip,Owner where MarinaSlip.OwnerNum = Owner.OwnerNum and Owner.LastName = "'.$form1.'"';
But it would be better to use a parametrized query. See How can I prevent SQL injection in PHP?
Related
I'm writing a program to create an online forum and I am relatively new to php.
I have used a while loop to display all topics created for discussion in a table. This reads my sql database and echoes out just fine:
if ( mysqli_num_rows( $r ) >0 ) {
while ( $row = mysqli_fetch_array( $r, MYSQLI_ASSOC ) )
{
echo "<tr><th><p align = 'left'>"."Posted By ".$row['first_name']." " .$row['last_name']. " on ". $row['post_date']."<br/>";
echo "<p style = 'color:#2208A1', align='left'>"."Subject:". $row['subject']."<br/><br/>";
echo "Message: ". $row['message']."<br/>";
echo "ID Number = ". $row['post_id']."<br/>";
echo "<p style='color:red;' align = 'right'>"."<a href='http://localhost/FirstCswkAttempts/2017%20Web%20Scenario_A2/cwk_addreply.php?post_id =" .$row['post_id']." '>Reply to Post."."</a></p>";
"</tr></th>";
}
}
However,you can see that in the last line of code I try to concatenate the post_id number to the URL in the hope that I can use this information in another php file:
The code below shows my attempt to do just this. I use the GET method to capture post_id and insert it into another table in my database. If I use var_dump($_GET); I get an empty array. Where am I going wrong??
$q = "INSERT INTO responses(reply_owner, reply_text,reply_create_time,post_id)
VALUES (' ".$_POST['email']." ', ' ".$_POST["message"]."', now(),'".$_GET['post_id']."')";
$r = mysqli_query ( $dbc, $q
) ;
In response to comments, please find the form used to add posts to the topic:
<h1>Reply to Thread</h1>
<!--Display form-->
<form action="cwk_reply_action.php" method="post" accept-charset="utf-8">
<p><strong>Your email:<br><input name="email" type="text" size="55px" maxlength="100"></p>
<p>Message:<br><textarea name="message" rows="5" cols="50px"></textarea></strong></p>
<input type = "hidden" name = "post_id" value = "$_GET['post_id'] ">
<p><input name="submit" type="submit" value="Submit"></p></form>
This is a pretty common type of thing for a PHP application to do. The general pattern is:
Pull a list of items from a database and display them with links to interact with specific items.
When a link is clicked, display a form with the information of the selected item.
When the form is submitted, save the user input to the selected item.
The minimum you need to implement this pattern is the following:
Step 1 (display the items):
<?php
// using mysqli for example here, but the same general idea for pdo or any other
$result = mysqli_query('SELECT id, some_text, other_columns FROM your_table WHERE criteria');
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$id = htmlspecialchars($row['id']);
$text = htmlspecialchars($row['some_text']);
echo '' . $text . '<br>';
}
?>
Clicking a link (<a>) sends an HTTP GET request to the URL in its href parameter.
Step 2 (display the form):
When PHP handles the request, anything you have included in the query string of the URL (the ?id=x portion) will be availabe in the $_GET array.
There are two ways you can handle this piece of data so that it can be passed on to step 3. One way is to include it in the URL in the action parameter of your form:
<form action="url/to/submission_handler.php?id=<?php echo $_GET['id']; ?>" method="post">
Another way is to include a hidden form element that contains the ID.
<form action="url/to/submission_handler.php" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
Step 3 (handle the form submission):
In this step, if you have passed the ID via the action parameter, it will be available in the $_GET array ($_GET['id']), and if you have passed it via an input on the form, it will be available in the $_POST array. ($_POST['id']).
Either way, you should be able to access it for use in your query.
<?php
$id = $_GET['id']; // or $_POST['id'], depending on which way you handled it on your form
// Using a prepared statement here for example rather than concatenating values into the
// SQL string, in order to reduce risk of SQL injection
// (Assuming $mysli is a connected mysqli object)
$stmt = $mysqli->prepare('UPDATE your_table SET ... WHERE id=?');
$stmt->bind_param("i", $id);
$stmt->execute();
?>
Either method of passing the id from your form to the script that handles its submission is perfectly valid, functional and commonly used. As far as I know, which way you should do it is really just determined by your own personal preference.
But you should note that passing parameters in the query string of the action paramater will only work for forms with method="post". If you ever need to use method="get" instead, only the values in the form fields will be available in $_GET; parameters in the query string will be ignored.
(For forms that will make changes on your server, (INSERT, UPDATE, or DELETE queries, writing to files, etc.) you should always be using method="post" anyway, but just FYI.)
If you want to print a variable you need it
<input type = "hidden" name = "post_id" value = "<?php echo $_GET['post_id']; ?> ">
And you will see the value of post_id
I believe you should be more specific however your code seems pretty rusty you need someone to tell you how its done what its your current uri on this script?
its it anything like that:http://localhost/forum.php?post_id=foobar
Are you send a POST or a GET request? what its your enctype?
if it is you can use the $_GET super global just fine just be careful inserting it on your querys, SQL injection still a big problem on this day.
<?php
if ( mysqli_num_rows( $response ) >0 ) {
while ( $row = mysqli_fetch_array( $response, MYSQLI_ASSOC ) )
{
echo "<tr>
<th>
<p align = 'left'> Posted By {$row['first_name']} {$row['last_name']} on {$row['post_date']} <br/>
<p style = 'color:#2208A1', align='left'>
Subject: {$row['subject']} <br/><br/> Message: {$row['message']} <br/>
ID Number = {$row['post_id'] }<br/>
<p style='color:red;' align = 'right'>
<a href='http://localhost/FirstCswkAttempts/2017%20Web%20Scenario_A2/cwk_addreply.php?post_id ={$row['post_id']}'>Reply to Post.</a>
</p>
</tr>
</th>";
}
//This is not recomenended anymore
//But since you are not using PDO and prepared statments its not that bad
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST["message"]);
$postId = mysql_real_escape_string($_GET['post_id']);
//never name your variables less then 4 chars $q = $query, $r = $response , $dbc = $databaseConnection
$query = "INSERT INTO responses( reply_owner, reply_text, reply_create_time, post_id ) VALUES ('$email', '$message', now(),'$postId')";
$response = mysqli_query ( $databaseConnection, $query );
I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)
I've been racking my brain trying to figure out how to get this to work. Now, i'll explain it a bit better here.
What i'm trying to do is, when the user types something into a form it returns the result of the query, then using the results from that query, carry out another query on them. I'm using PHP and an oracle database.
For instance: currently I've a database full of recipes and their ingredients; and I have a form that a user can enter an ingredient into. In this example, it's bacon.
That works just fine. However, what i'm having difficulty achieving is when the user enters another ingredient, the results of the current table there and further queried. Say I enter 'cheese', all the recipes containing bacon AND cheese are then queried and displayed.
This process is easily achieved in simple SQL, however like I saw i'm having difficulty transferring it to use a form.
Now, I've an idea the solution is either something to do with temporary tables, dynamic sql or a combination of the both.
Thank you in advance for any help regarding the matter.
My code is as follows:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
}
function do_fetch($myeid, $s)
{
print '<table border="1">';
while ($row = oci_fetch_array($s, OCI_RETURN_NULLS+OCI_ASSOC)) {
print '<tr>';
foreach ($row as $item) {
print '<td>'.($item?htmlentities($item):' ').'</td>';
}
print '</tr>';
}
print '</table>';
print '<br>';
}
// Create connection to Oracle
$c = oci_connect("system", "luigi98", "localhost/XE");
// Use bind variable
$query = "SELECT DISTINCT r.recipeTitle AS recipe
FROM RECIPES.recipe r
WHERE recipeID IN(
SELECT r.recipeID
FROM recipes.recipeIng il
INNER JOIN RECIPES.ingredient i ON il.ingredientID = i.ingredientID
WHERE il.recipeID = r.recipeID
AND i.ING = :eidbv)";
$s = oci_parse($c, $query);
$myeid = $name;
oci_bind_by_name($s, ":EIDBV", $myeid);
oci_execute($s);
do_fetch($myeid, $s);
// Close the Oracle connection
oci_close($c);
?>
<p>Enter ingredient</p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Search"><br>
</form>
There are several ways you can do that.
The easiest is probably to display your original ingredient(s) in the search box again and instruct the user to add more (separated by space, comma, etc.) ingredients if they want to.
Then you can explode your search terms on these characters and add a condition for every ingredient.
I have the following query that I ran on my database to remove some data:
delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;
But I now need to make the a php function that runs when I press a button called clean
then print out all the subscriber data that was deleted.
Not quitesure where to start with this.
this is my html so far:
<form id="form1" name="form1" method="post" action="">
Clean subscribers:
<input type="submit" name="clean" id="clean" value="Clean" />
</form>
Any help or advice with this is very much appreciated.
C
You'll need the button to submit a form to a handler page, the handler page would then run the query, and collect+print the data.
If you don't want to refresh the page (or have your users diverted into another page), you'll want to use Ajax.
That's where you start.
Is abvious you made no effort! but I will answer you anyway.
<?php
$con = mysql_connect("serverUrl","login","password");
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM subscriber, subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
while($row = mysql_fetch_array($result))
{
echo $row['subscriber.name']; //assuming you have a field {name} in your table
echo "<br />";
}
mysql_query("delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
?>
First you'll need to select the data you're about to delete.
Then you'll need to delete it and return the selected rows.
$rows = array();
mysql_connect(...);
$res = mysql_query(...select query here...);
while($row=mysql_fetch_assoc($res)) {
$rows[] = $row;
}
$res = mysql_query(...delete query here...);
return $rows;
You might not want to totally delete the subscriber. If I were you I would include a field named "deleted" or something along those lines, indicating whether or not the subscriber has been deleted. Then query according to whether or not that field is true or false.
I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>    ";echo $_POST['product_color']; ?>
</div>
I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>    ";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.
echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!