I'm trying to submit a form that contains a schedule for each user ID. So far it looks like this:
$sql = "SELECT * FROM dbtable";
$result = $conn->query($sql);
$name_info = "SELECT udidId, name FROM udid";
$name_result = $conn->query($name_info);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$udidId = $row["udidId"];
echo "<label for='hours' class='schedule'><strong>I want <span>".$row["name"]."</span>";
echo "<input type='text' name='udidId' class='hidden' value='".$row["udidId"]."' />";
echo " to be <br />allowed out between <input type='text' name='outAllowedStartHour' placeholder='8' value='" . $row["outAllowedStartHour"] . "'> - <input type='text' name='outAllowedEndHour' placeholder='8' value='" . $row["outAllowedEndHour"] . "'><br />allowed in between <div class='padd_left'></div><input type='text' name='inAllowedStartHour' placeholder='8' value='" . $row["inAllowedStartHour"] . "'> - <input type='text' name='inAllowedEndHour' placeholder='8' value='" . $row["inAllowedEndHour"] . "'></strong></label>";
}
}
if(isset($_POST["update_schedule"])) {
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value' <br />";
while($row = $result->fetch_assoc()) {
foreach($value as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
$update_pets = "UPDATE v_spottData SET $x_value = $x_value WHERE udidId = $x";
$conn->execute($update_pets);
}
}
}
However is only updating inputs from the last ID in the database, and is not updating the input values at all. Any suggestions?
Execute doesn't execute a query, it executes a prepared statement. You need to use prepare to prepare the query.
Prepared statements should use placeholders. The quoting/escaping will be handled by the driver.
Note columns can't be bound/placeheld.
Your current query is trying to update a column with the same value, that can't be right. Change $updating_column below to whatever column you are trying to update.
$columns = array('outAllowedStartHour', 'outAllowedEndHour', 'inAllowedStartHour', 'inAllowedEndHour'); // whitelist columns
if(in_array($updating_column, $columns)) {
$update_pets = "UPDATE v_spottData SET `$updating_column` = ? WHERE udidId = ?";
$stmt = $con->prepare($update_pets);
$stmt->bind_param("ii", $x_value, $x);
$stmt->execute();
} else {
echo 'Using a Not Allowed Column';
}
You can read more about prepared statements here, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
I feel really silly, but for anyone else dealing with the issue, my solution was simple.
Try putting the PHP to handle the form submission at the top of your document, instead of at the bottom. Everything worked fine once I moved it up!
Thank you for all of your help everyone, especially #chris85!
Related
I have a php page that interacts with a database. I am trying to display data from the database as options for a user to select. I am trying to record which option a user selects but the variable I use ($a_game_id) to record which button is clicked gets reverted back to its original value after submitting another form. I have tried declaring the variable as global within the loop and using session variables.
$a_game_id = 9;//starting value - it changes from 9 as desired, but reverts back when another form is submitted
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
global $a_game_id;
// output data of each row
$results = $conn->query($sql);
$resultset = array();
while($a_row = $results->fetch_assoc()){
$resultset[] = $a_row;
}
foreach ($resultset as $row){
echo "<form action='display_lines.php' method='POST'>
<br>" . $row["away"] . " " . $row['away_spread'] . "---TOTAL AVAILABLE: " . $away_sum_array[$row['game_id']].
" <input type='submit' value='Bet " . $row['away'] ."' name='" . $row['game_id']."A' />
at " . $row["home"] . " " . $row['home_spread'] . "---TOTAL AVAILABLE: " .$home_sum_array[$row['game_id']]. "
<input type='submit' value= 'Bet " . $row['home'] ."' name='" . $row['game_id']."H' /> " . $row['date'] . "
</form>
<br>";
///HERE $a_game_id has gets the desired value
if(isset($_POST[$row['game_id'].'H'])){
$a_game_id = intval($row['game_id']);
}else if(isset($_POST[$row['game_id'].'A'])){
$a_game_id = intval($row['game_id']);
}
}
} else {
echo "<br> 0 results";
}
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
if(isset($_POST[strval($row['game_id']).'H'])){
echo '<h3>'.$row['game_id'].'<br>';
echo $row['home'].' '.$row['home_spread'].'<br>';
$team = $row['home'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
else if(isset($_POST[strval($row['game_id']).'A'])){
echo '<h3>' .$row['game_id'].'<br>';
echo $row['away'].' '.$row['away_spread'].'<br>';
$team = $row['away'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
}
if(isset($_POST['new_bet_submit'])){
//HERE $a_game_id reverts back to its original value which is undesirable
$sql3 = "INSERT INTO placed_bets (user_id, game_id, bet_amount, game_date) VALUES ('".$_SESSION['id']."', '".$a_game_id."', '".$_POST['new_bet_amount']."', '".$date."')";
echo $a_game_id.'<br>';
if ($conn->query($sql3) === TRUE) {
echo "<br><h3>BET PLACED SUCCESSFULLY</h3><br>";
} else {
echo '<h3>Error placing bet<br>';
echo $conn->error;
echo '</h3>';
}
}
Thank you for taking a look
Do you mean "when I make another request all my global variables get reset?" If so, yes, that's how they work. Each request is completely independent of others. They do not share variables or other data. All you get is what's in $_SESSION, $_GET, $_POST and $_COOKIE.
If you need to persist between requests you must put that in the session, the database, or something persistent.
If you're used to code where the process persists and the variables stick, like in client-side situations, that's a mode of thinking you need to completely abandon.
I'm working on a project for a class and I'm having trouble passing on a variable from a Chosen selector. I am passing on the $inst variable just fine, but the $focus variable is giving me this:
Undefined index: chzn2 in C:\xampp\htdocs\phptest\results.php on line 20.
fyi: I have allowed for null in the database
Here is the code for the selectors.
$sql = "SELECT institutionName, instID FROM institutions";
$dropq = mysqli_query($conn, $sql);
echo "<select data-placeholder='Select an Institution' name='chzn1' class='chzn-select' standard='true' style='width:250px;'>";
while ($row = mysqli_fetch_array($dropq)) {
echo "<option></option><option value='" . $row['instID'] . "'>" . $row['institutionName'] . "</option>";
}
echo "</select>";
$sql1 = "SELECT orgFocus FROM communityOrgs";
$dropq = mysqli_query($conn, $sql1);
echo "<select data-placeholder='Select Focus Area' name='chzn2' class='chzn-select' multiple='true' style='width:250px;'>";
while ($row1 = mysqli_fetch_array($dropq)) {
echo "<option></option>
<option value='" . $row1['orgFocus'] . "'>" . $row1['orgFocus'] . "</option>";
}
echo "</select>";
Here is the code for the results
if (isset($_POST['submit-search'])) {
if(empty($_POST['chzn1']) && empty($_POST['chzn2'])){
echo "Please enter at least one value!";
}
else if(!empty($_POST['chzn1']) || !empty($_POST['chzn2'])) {
// Grabbing variables from User Inputs
$inst = $_POST['chzn1'];
$focus = $_POST['chzn2'];
$query = "SELECT * FROM partnerships WHERE instID = '$inst' OR orgFocus = '$focus'";
$result = mysqli_query($conn, $query);
$queryResults = mysqli_num_rows($result);
if($queryResults > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<div class='results-container'>
<h3>".$row['instName']."</h3>
<p>".$row['orgName']."</p>
<p>".$row['orgFocus']."</p>
</div>";
;}
}
As the error suggests:
Undefined index: chzn2
and according to your logic one out of the two values can be passed that leaves the ability for one to be unset so an error is thrown - as it should.
You need to do a check to see if either one of the $_POST keys exist separately and set their values respectively, either to what was passed or null.
Example
<?php
$chzn1 = null;
$chzn2 = null;
if (!empty($_POST['chzn1']))
$chzn1 = $_POST['chzn1'];
if (!empty($_POST['chzn2']))
$chzn1 = $_POST['chzn2'];
?>
Now they will both have default value so the error won't be thrown.
Note: Seeing as you are using mysqli_* make use of prepared statements.
Update #1
Maybe due to a formatting error but you also have a floating semicolon ;:
;}
Select and option is not separated. As you are echoing separate make it combine.
$row = "<select data-placeholder='Select Focus Area' name='chzn2' class='chzn-select' multiple='true' style='width:250px;'>";
while ($row1 = mysqli_fetch_array($dropq)) {
$row .= "<option></option>
<option value='" . $row1['orgFocus'] . "'>" . $row1['orgFocus'] . "</option>";
}
$row .= "</select>";
echo $row;
Same for other select tag
I have followed several tutorials on here and I can't figure out my mistake.
The Gallery gets displayed correctly, and the check boxes have the right value when I check with Element inspector in Firefox, but this little script I wrote always unlinks the last picture in the loop, and the Database row does not get deleted.
Maybe you have a better eye for what I am missing then myself?
$sql = "SELECT id, title FROM houses ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
echo $result['title'] . $result['id'];
echo"<br>";
$sql1 = "SELECT * FROM gallery_photos WHERE photo_category=" . $result['id'];
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1)) {
$photo_filename = $row['photo_filename'];
echo "<form action='' method='post'>
<li style='float:left; list-style-type:none;'>
<img src='houses/" . $photo_filename . "' title='$photo_filename' width='100px'>
<input type='checkbox' name='delete' value='$photo_filename'/> <br>
</li> ";
}
echo "<p style='clear:both' /> <input type='submit' value='Delete Selected' />";
echo" </form>";
echo "<p style='clear:both;'>";
echo "<br><br>";
}
if (isset($_POST['delete']) && is_array($_POST['delete']) && count($_POST['delete']) > 0) {
unlink("THIS/IS/A/WORKING/PATH/houses/" . $photo_filename);
unlink("THIS/IS/A/WORKING/PATH/houses/tb_" . $photo_filename);
mysql_query("DELETE FROM gallery_photos WHERE photo_filename = $photo_filename");
}
?>
You're opening the element each time for the new photo, but the submit button and only one closing tag are outside all of the forms. You may want to fix the html to have this working properly.
EDIT:
The wrong file gets deleted, because you're using $photo_filename variable in the last 3 rows instead of the value from $_POST['delete'].
Side note: this code is really awful and buggy. It's a security nightmare.
something like this should sort it, I have not tested it but hopefully it will work.
foreach ($_POST['delete'] as $filename) {
unlink("THIS/IS/A/WORKING/PATH/houses/" . $filename);
unlink("THIS/IS/A/WORKING/PATH/houses/tb_" . $filename);
mysql_query("DELETE FROM gallery_photos WHERE photo_filename = $filename");
}
echo '<form action='' method='post'>';
$sql = "SELECT id, title FROM houses ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
echo $result['title'] . $result['id'];
echo"<br>";
$sql1 = "SELECT * FROM gallery_photos WHERE photo_category=" . $result['id'];
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1)) {
$photo_filename = $row['photo_filename'];
echo "<li style='float:left; list-style-type:none;'>
<img src='houses/" . $photo_filename . "' title='$photo_filename' width='100px'>
<input type='checkbox' name='delete[]' value='$photo_filename'/> <br>
</li> ";
}
echo "<p style='clear:both' /> <input type='submit' value='Delete Selected' />";
echo" </form>";
echo "<p style='clear:both;'>";
echo "<br><br>";
}
notice the [] at the end of the checkbox name, this means that it will create an array of them. You might want to add an additional check around the foreach to prevent it running if the $_POST['delete'] has not been set.
First, just to be sure, you are getting the params, you can use:
echo "<br />Contents of \$_POST:<br />";
foreach ($_POST as $k => $v) {
echo " $k = $v<br />";
}
So you know what params are you getting. And it looks like working.
Also, you can use it, to delete the images,
foreach ($_POST as $k => $v) :
if ( $k == "delete" ) :
// add your code for unlink and delete
endif;
endforeach;
Second, check for permissions before to delete
chmod($this->uploaddir . $this->finalName, octdec(0777)); // Maybe 0666 is enough
#unlink( path_to_file ); // # to avoid see code errors
And just, for you consideration, maybe if you use you don't have to be taking care about float, and clearing
Cheers
I'm using a table to update a database, the table has 264 checkboxes which can be checked and unchecked then updated on the database.
I'm doing this by posting data on the form, using a while loop to set all fields to blank ( the value of the checkbox and the textarea value) for each respective field, then using a foreach loop to update each row in the database with the value of the checkbox.
Now, what I want to do is add the textarea value for each ticked checkbox into the database as well, what i cant figure out is how to do this?
This is my update code:
if (isset($_POST["update"])) {
$seolistRes2 = mysql_query($seolistQ) or die(mysql_error());
while ($seolistRow2 = mysql_fetch_array($seolistRes2)) {
$wsID1 = $seolistRow2["worksheetID"];
$updateWSQ2 = "UPDATE seo_work SET taskValue=0, taskInfo='' WHERE worksheetID=$wsID1 AND userID=$userID";
mysql_query($updateWSQ2) or die(mysql_error());
}
$item = $_POST;
foreach($item as $key => $value) {
$wsID = str_replace("checkbox","",$key);
if (is_numeric($wsID)) {
$updateWSQ = "UPDATE seo_work SET taskValue=$value taskInfo=$value WHERE worksheetID=$wsID AND userID=$userID";
mysql_query($updateWSQ) or die(mysql_error());
header("Location: worksheet.php?y=".$seoworkyear."&userID=$userID&action=success");
}
}
}
This is checkbox and textarea code: (please note this is within a form)
$currentTask = '';
echo "<tr class='tr'>";
while ($seolistRow = mysql_fetch_array($seolistRes)) {
$taskValue = $seolistRow["taskValue"];
$worksheetID = $seolistRow["worksheetID"];
$taskName = $seolistRow["taskName"];
$taskInfo = $seolistRow["taskInfo"];
if ($taskValue == 1) {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox".$worksheetID."' id=checkbox'".$worksheetID."' checked='checked' />".
"<textarea class='textarea' name='textarea".$worksheetID."' id=textarea'".$worksheetID."'>" . $taskInfo . "</textarea>";
}
else {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox".$worksheetID."' id='checkbox".$worksheetID."' />".
"<textarea class='textarea' name='textarea".$worksheetID."' id=textarea'".$worksheetID."'>" . $taskInfo . "</textarea>";
}
if ($currentTask != $taskName) {
echo "</tr>";
echo "<tr class='tr'>";
echo "<td class='task'>".$taskName."</td>";
}
echo "<td class='tick'>".$taskDone."</td>";
$currentTask = $taskName;
}
echo "</tr>";
Use your HTML form like shown below.
$currentTask = '';
echo "<tr class='tr'>";
while ($seolistRow = mysql_fetch_array($seolistRes)) {
$taskValue = $seolistRow["taskValue"];
$worksheetID = $seolistRow["worksheetID"];
$taskName = $seolistRow["taskName"];
$taskInfo = $seolistRow["taskInfo"];
if ($taskValue == 1) {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox[".$worksheetID."]' id='checkbox[".$worksheetID."]' checked='checked' />".
"<textarea class='textarea' name='textarea[".$worksheetID."]' id='textarea[".$worksheetID."]'>" . $taskInfo . "</textarea>";
}
else {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox[".$worksheetID."]' id='checkbox[".$worksheetID."]' />".
"<textarea class='textarea' name='textarea[".$worksheetID."]' id='textarea[".$worksheetID."]'>" . $taskInfo . "</textarea>";
}
if ($currentTask != $taskName) {
echo "</tr>";
echo "<tr class='tr'>";
echo "<td class='task'>".$taskName."</td>";
}
echo "<td class='tick'>".$taskDone."</td>";
$currentTask = $taskName;
}
echo "</tr>";
See the modified name and id of your textarea and checkbox. I have modified it to textarea[SOME_WORKSHEET_ID] and checkbox[SOME_WORKSHEET_ID] respectively.
So, when you submit the form, you will receive those checkbox and textarea value as an array, with worksheetId as an index. You can use this [] technique to retrieve the values of the textarea and checkbox, or as many field you want to add in form.
Use above HTML structure and check the $_POST array.
Hope this will help..
Thanks!
Hussain.
You should be able to get the value in the textarea using $_POST['textarea' . $wsID] after your call to is_numeric.
Here is another approach, not completely tested, but hopefully you get the idea...
if (isset($_POST["update"]))
{
// All to blank
$seolistRes2 = mysql_query($seolistQ) or die(mysql_error());
while ($seolistRow2 = mysql_fetch_array($seolistRes2))
{
$wsID1 = $seolistRow2["worksheetID"];
$updateWSQ2 = "UPDATE seo_work SET taskValue=0, taskInfo='' WHERE worksheetID=$wsID1 AND userID=$userID";
mysql_query($updateWSQ2) or die(mysql_error());
}
// Re use your result from the select to go through all the known IDs
foreach($seolistRow2 as $i => $data)
{
// Obtain the ID
$id = $data['worksheetID'];
// Get the checkbox value for current ID
$checkbox_wsID = $_POST['checkbox' . $id];
// Get the textarea value for current ID
$textarea_wsID = $_POST['textarea' . $id];
// Update the Row using mysql_escape
$updateWSQ = "UPDATE seo_work " .
"SET taskValue = '" . mysql_escape_string($checkbox_wsID) ."' taskInfo = '" . mysql_escape_string($textarea_wsID) ."'" .
"WHERE worksheetID=$id AND userID=$userID";
mysql_query($updateWSQ)
or die(mysql_error());
header("Location: worksheet.php?y=".$seoworkyear."&userID=$userID&action=success");
}
}
I've been trying think of a way to do this. I want it to where users can check off items, hit submit and it goes to the code on the next page and deletes all of the checked items from the database. Problem one is that in the post its only sending over the last checked item. Here is how I have it set up right now.
echo "<form name='fm1' METHOD ='POST' ACTION ='displaydelete.php' > ";
//Draws up the table headers
echo "";
echo "";
echo "Fund Number ";
echo "Hours ";
echo "Percentage";
echo "Delete";
echo "";
//While there are query results data is pushed into table cells
while ($row = mysql_fetch_array($queryResult2))
{
$hours = $row['hours'];
$percentage = $hours / 160 * 100;
echo "<tr>";
echo "<td>";
echo $row['funnumber'];
echo "</td>";
echo "<td>";
echo $hours;
echo "</td>";
echo "<td>";
echo $percentage ."%";
echo "</td>";
echo "<td>";
echo "<input type='checkbox' name='id' value='$row[id]'/>";
echo "</td>";
echo "</tr>";
}
//End of tabel
echo "</table>";
echo" ";
echo "";
What I would like to do is push all of the items into a variable and maybe delete them that way. I'm not really sure how you would handle multiple deletes. I'm doing my delete like this for something else if this helps any.
$query = "DELETE FROM users
WHERE ninenumber = '$ninenumber'";
$result = mysql_query($query)
or die("Query Failed: " .mysql_error());
mysql_close($conn);
In your form:
<input type='checkbox' name='id[]' value='$row[id]'/>
Then, in the file you post to:
if(is_array($_POST['id'])){
foreach($_POST['id'] as $id){
...do something to $id;
}
}
Instead of this:
echo "<input type='checkbox' name='id' value='$row[id]'/>";
You need this:
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
Note the difference. I added [] after the input name. This tells the client and server that there are multiple inputs with that name. $_POST['id'] will be an array you can loop through on the next page.
foreach ($_POST['id'] as $checkbox) {
// DELETE FROM users WHERE ninenumber = $checkbox
}
isset, is_array, and mysql_real_escape_string omitted for brevity.
In the form-generating code, make the name in the html have" []" after it:
...
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
...
Then, in the form-reading code, your post'ed id will be an array.
$id_array = isset($_POST['id']) && is_array($_POST['id']) ? $_POST['id'] : array();
foreach( $id_array as $id ) {
$query = "DELETE FROM users WHERE ninenumber = '" . mysql_real_escape_string($id) . "'";
// execute the delete query
}
Putting [] after the name of a control will turn it into an array in the superglobal that you can then iterate over to get all the values from.
You need to have the same name for all of your checkboxes, then all values are passed as array POST variable.
<input type='checkbox' name='id[]' value='$row[id]'/>
Change
name=id
to
name=id[]
this will then give you an array.