PHP novice here. Goal is to:
a) Display a table of booking options (fitness classes) dynamically from database records, allow user to select multiple options with checkboxes against each row - this bit's working.
b) Pass the checkbox selection to a table listing the selected data on a confirmation page. I'm getting an error here: Invalid argument supplied for foreach().
c) Update the database when user hits the second page's 'Confirm' button.
Research so far uncovered this advice on using $_GET and $_POST to achieve this with an array.
My checkbox code on the initial page:
echo '<form action="makebooking.php" method="get">';
echo '<td><input type="checkbox" name="class_id[]" value=' . $row['class_id'] . '</td></tr>';
The foreach statement error comes from this code that generates the table of choices on the second page:
//Check if the GET is set from classes.php
if (isset($_GET['class_id'])) {
// Grab the score data from the GET
foreach($_GET['class_id'] as $class_id) {
$_GET['class_id'] = $class_id;
}
}
//table header
echo '<table class="table table-bordered table-hover">';
echo '<thead><tr><th>Date</th><th>Time</th><th>Venue</th><th>Who\'s going?</th> <th>Add someone</th></tr></thead>';
//create the form
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
//Get the class IDs from the GET to use in the POST
foreach ($_GET['class_id'] as $class_id) {
$sql = "SELECT class_id, DATE_FORMAT(date, '%a, %d %b') AS new_date, DATE_FORMAT(time, '%H:%i') AS new_time, venue FROM classes WHERE class_id = '$class_id'";
$data = mysqli_query($dbc, $sql);
//---------------------------------------------------------------------------------
//get table data
while ($row = mysqli_fetch_array($data)) {
$date = $row["new_date"];
$time = $row["new_time"];
$venue = $row["venue"];
$class_id = $row["class_id"];
}
//---------------------------------------------------------------------------------
//Show a table of the selected classes
echo '<input type="hidden" name="id" value= ' . $class_id . ' />';
echo '<td>' . $date . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $venue . '</td>';
echo '<td>' . $username . '</td>';
echo '<td><button class="btn btn-mini" type="button"><i class="icon-user"></i><i class="icon-plus"</i></button></td></tr>';
}
echo'</table>';
// Make booking button
echo '<input type="submit" name="submit" class="btn btn-large btn-primary pull-right" value="Confirm">';
echo '</form>';
}
Full code of both pages at this pastebin. All error-fixing advice gratefully accepted!
Figured out that I had been declaring the variables in if/else loops that made them inaccessible to other parts of the code.
I also added some extra hidden input arrays into both tables to validate the input. This required a string-to-integer conversion of the class ID in order to update the db with the selected data.
Full fixed code is here for anyone struggling with something similar.
Related
I have PHP code creating multiple forms on a single page and the submission of any of these forms should trigger an API call based on which form was submitted.
if(isset($_POST['pickApples'])) {
echo '<h1>Picking Apple ' . $_POST['appleId'] . '</h1>';
// Function that calls API
pickApple($_POST['appleId']);
}
// $listOfApples is a list of 10 apples each with a unique ID
foreach ($listOfApples as $apple) {
echo '<form method="post" action="mypage.php">';
echo '<input type="hidden" name="appleId" value="' . $apple->{"id"} . '">';
echo '<button type="submit" class="my-button-class" value="click" name="pickApples">Pick Me</button>';
echo '</form>';
}
No matter which of the form buttons I click, the value in $_POST['appleId'] is the ID of the first apple in the list. I don't have much experience with PHP or HTML forms, is my approach completely off?
I am seeing some small mistakes as
echo '<input type="hidden" name="appleId" value"' . $apple->{"id"} . '">';
You should fix it,instead of foreach yor can use for loop to display forms,
as I haven't $listofapples,I used 10,you can query for row numbers than place row numbers value as $listofapples,then echo your unique id to input value,
Finally it's working as you wished
Check it & let me know if it's the perfect fit for you
<?php
if(isset($_POST['pickApples'])) {
echo '<h1>Picking Apple ' . $_POST['appleId'] . '</h1>';
// Function that calls API
pickApple($_POST['appleId']);
}
$listOfApples = 10;
// $listOfApples is a list of 10 apples each with a unique ID
$sn=0;
for ($i = 1; $i <= $listOfApples; $i++) {
echo '<form method="post" action="hy.php">';
echo '<input type="hidden" name="appleId" value=" ' .++$sn. '"/>';
echo '<button type="submit" class="my-button-class" value="click" name="pickApples">Pick Me</button>';
echo '</form>';
}
?>
I'm having an issue trying to update multiple entries in my database via a php populated drop down menu. Here is the code on my page that populates the table showing me all entries currently in my database:
$result = mysqli_query($con,"SELECT * FROM Submissions");
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Title</th>
<th>Text</th>
<th>Public Post OK?</th>
<th>Date/Time Submitted</th>
<th>Approved?</th>
<th>Test Approved</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . nl2br($row['text']) . "</td>";
echo "<td>" . $row['publicpost'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "<td><select name=\"approved\"><option value=\"" . $row['approved'] . "\">" . $row['approved'] . "</option><option value=\"yes\">Yes</option><option value=\"no\">No Again</option></select></td>";
echo "<td>" . $row['approved'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
<br><br>
<form action="update.php" method="post">
<input type="submit" name="SubmitButton" value="Update" class="submit" style="cursor:pointer;">
</form>
<?php
mysqli_close($con);
?>
This is the php code for "update.php":
$approved = $_POST['approved'];
mysqli_query($con,"UPDATE Submissions SET approved = $approved");
$update_query= "UPDATE Submissions SET approved = '$approved'";
if(mysqli_query($con,$update_query)){
echo "updated";}
else {
echo "fail";}
?>
<form action="approvesubmissions.php">
<input type="submit" value="Approve Submissions page">
</form>
The goal is to have the ability to update the field "approved" with a drop down menu from "NO" to "YES" or vice versa. Instead, what is happening with this query, is that it is erasing the data in the "approved" field instead of updating it. I'm somewhat new to php and i have researched a TON on this and have come up with no solutions. Any help is GREATLY appreciated!
First, let's assume 'approved' is a TINYINT(1) or something.
Your select html should be more like this. It will autofill based on the DB value.
$selected = 'selected="selected"'; // pre-selection attribute
$isApproved = !!$row['approved']; // is this active? (approved is 1 or 0)
echo '<select name="approved">
<option value="1" ' . ($isApproved ? $selected : '') . '>Yes</option>
<option value="0" ' . (!$isApproved ? $selected : ''). '>No</option>
</select>';
Secondly, your form is at the bottom of the table, but your input that you want is in the table. When you submit your form, there is no $_POST['approved'], because that's technically not in a form. To fix, you'll need to put your opening form tag at the top before the table. Then, you'll want to put your submit button and closing form tag at the end, after you've echoed the table out.
Thirdly, your post.php page should NOT ever take user input directly into a query. But, simply do this:
// Convert input to boolean answer, then int (for the query).
$approved = isset($_POST['approved']) ? (int)!!$_POST['approved'] : 0;
mysqli_query($con,"UPDATE Submissions SET approved = '$approved'");
While we're on the topic, this would be a great time to jump into prepared statements for your project. It might sound scary, but it can save you from SQL injection.
// Make the prepared statement
$query = mysqli_prepare("UPDATE Submissions SET approved = ?");
// Safely bind your params
mysqli_stmt_bind_param($query, "i", $approved);
// Run it
mysqli_stmt_execute($query);
// "close" the statement (hint: it's reusable for things like bulk updates, etc)
mysqli_stmt_close($query);
Ive got to make a web-based checkout for an assignment and have come across a problem, ive imported a database and set up the data in a table with added check boxes alongside it. I need to take the reference number (stored first in the array) onto another page using sessions. From using var_dump i cant seem to get anything from the selected from the table.
Code:
Button code
<p><tr>
<input type="submit" name="Select" id="Select" value="Add Selected To Cart"/>
</tr></p>
Access database code(values changed for saftey)
<?php
Accesses database
$con=pg_connect("host=hostname port=portnumbers
dbname=name user=user password=password");
if (!$con)
{
die('Could not connect to database');
}
?>
Database display
//Creates table
echo "<table border='1'>\n<thead>\n<tr>\n";
echo "<th>Title</th>
<th>Platform</th>
<th>Description</th>
<th>Price</th>
<th>Buy</th>\n";
while($row = pg_fetch_array($res)){
echo"<tr>";
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "<td>" . $row['4'] . "</td>";
echo '<td><input type="checkbox" name="selected[]" value="' . $row['0'] . '" /></td>';
echo"</tr>";
}
echo"</table>";
?>
Well, I think you can as follow because you are trying to improve a shopping car:
//Use the `$_SESSION` var to hold the values
foreach ($_POST['selected'] as $item)
$_SESSION['cart'][$item] = $item;
As the item's id will be indexed, each time a submit is performed:
If the item exists, will be replaced
If the item does not exist, will be added
In order to remove items, you should use a "view cart" page and then show the items:
foreach ($_SESSION['cart'] as $item)
echo '' . $item . '';
I have a table being generated from PostgreSQL through PHP.
The user needs to have the option of deleting the row or updating it.
So I have successfully implemented a delete button utilizing hidden elements to pass the key information for the deletion to my delete.php
Now I am trying to add an update button which will send the php to my update.php rather than my delete.php.
However, when I open my form I tell it where to send the data upon submission.
My question then is, is there a way that I can have both buttons available and depending on which button is pressed the form posts the data to the appropriate php- delete.php vs update.php? Perhaps some attribute of input buttons I cannot think of that can direct where to POST rather than having it as a form attribute?
Here is an example of what I have:
echo '<form action="delete.php" method="POST">';
echo '<tr>';
echo '<td class="even">' . $row['id'] . '</td>';
echo '<td class="odd">' . $row['name'] . '</td>';
echo '<td class="even">' . $row['countrycode'] . '</td>';
echo '<td class="odd">' . $row['district'] . '</td>';
echo '<td class="even">' . $row['population'] . '</td>';
echo '<input type="hidden" name="todelete" value="'.$row['countrycode'].'" />';
echo '<input type="hidden" name="cityname" value='.$row['name'].'" />';
echo '<input type="hidden" name="tablename" value="'.$_POST["search-type"].'" />';
echo '<td> <input class="odd" type="submit" name="updateBtn" value="Update?" /></td>';
echo '<td> <input class="even" type="submit" name="deleteBtn" value="Delete?" /></td>';
echo '</tr>';
echo '</form>';
This is generated for each row of the table so each of the forms is unique and only that data is sent.
Let me know if you have any ideas how I can implement the two buttons!
Simplest method is to have a SINGLE script as your action, then have a basic
<?php
if (isset($_POST['deleteBtn'])) {
... do delete stuff
} else if (isset($_POST['updateBtn'])) {
... update stuff here ...
}
Otherwise you're stuck with some javascript to dynamically change the action target.
How do i pass id to delete record in this code?
<form action="index.php">
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('user');
$query = mysql_query("Select * from tbluser");
echo "<center>";
echo '<table style="border:solid 2px black;">';
while(($row = mysql_fetch_array($query)) != NULL) {
echo '<tr>';
echo '<td>' . $row['UserName'] . '</td>';
echo '<td>' . $row['Password'] . '</td>';
echo '<td>' . $row['EmailAddress'] . '</td>';
echo '<td>' . $row['Address'] . '</td>';
echo '<td>' . $row['Address'] . '</td>';
echo '<td><input type = "Submit" value = "Delete" name = "btnDel" /></td>';
echo '</tr>';
}
echo '</table>';
echo "</center>";
?>
</form>
The above code is in index.php and it is submitting it to itself.
Without needing javascript, seperate GET urls etc, just plain old HTML & the original POST: just add the ID to the name of the button:
<input type="submit" value="Delete" name="btnDel[<?php echo $id;?>]">
And in receiving code:
if(isset($_POST['btnDel']) && is_array($_POST['btnDel'])){
foreach($_POST['btnDel'] as $id_to_delete => $useless_value){
//delete item with $id_to_delete
}
}
Here's how I would do it:
Change
echo '<td><input type = "Submit" value = "Delete" name = "btnDel" /></td>';
To
echo '<td><input type = "button" value = "Delete" onclick = "btnDel(' . $row['id'] . ')" /></td>';
Add the following field to the form (outside of the while loop of course):
<input type="hidden" name="id" id="userid" />
Define the following javascript function:
function btnDel(id) {
if (confirm("Really delete id=" + id + "?")) {
document.getElementById('userid').value = id;
document.forms[0].submit();
}
}
Then you can retrieve that value using $_GET['id'] or $_POST['id'] depending on your form's method.
EDIT: Here's a working demo, and its source
Use this to submit the id as a part of form.
<input type="hidden" id="id" name="id" value="<? echo $row['id']; ?>" />
or you can send values in URL to do the same thing
An example:
Delete
A full working sample
<?
mysql_connect('localhost', 'root', '');
mysql_select_db('user');
switch($_GET['action']) {
case "delete":
$query = "DELETE FROM tbluser WHERE id='".$_GET['id']."'"
$result = mysql_query($query);
break;
//well other actions
}
$query = mysql_query("Select * from tbluser");
echo "<center>";
echo '<table style="border:solid 2px black;">';
while(($row = mysql_fetch_array($query)) != NULL) {
echo '<tr>';
echo '<td>' . $row['UserName'] . '</td>';
echo '<td>' . $row['Password'] . '</td>';
echo '<td>' . $row['EmailAddress'] . '</td>';
echo '<td>' . $row['Address'] . '</td>';
echo '<td>' . $row['Address'] . '</td>';
echo '<td>Delete</td>';
echo '</tr>';
}
echo '</table>';
echo "</center>";
?>
You could also send it in the url at action="index.php" given that you move it below while(($row = mysql_fetch_array($query)) != NULL) { like this
echo "<form action='index.php?var=" . $row['id'] . "'>";
You would then get the variable using $_GET['var']
If the id needs to stay hidden (on the page and in the link) a hidden input element and submitting the form using method="post" like previously suggested would be the better way to go.
From the table:
echo '<input type="hidden" name="user_id" value="'.$row['id'].'" />';
echo '<td><input type = "Submit" value = "Delete" name = "btnDel" /></td>';
This will be sent to the server as a parameter named user_id. Ideally, you should be using the POST method in the form.
This assumes that the user id is named, well id in the table.
BTW, the != NULL is unnecessary.
It's sufficient to write:
while($row = mysql_fetch_array($query)) {
NULL evaluates to FALSE in a boolean context.
Update:
As mentioned in comments to another answer, there is an issue with your approach. With multiple rows, you won't be able to distinguish between user ids.
One solution would be use multiple forms.
Another option would be to have the name of the submit button include the id. You'd then parse this out of the name of the $_POST array keys.