Adding variables to an array php - javascript

I have the following problem:
I made a form in which the customer can add some items they want and when he's done he will press the submit button on the from, bringing him to the confirmation page. Where he should see all the products and next to them the amount of items ordered.
And there is my problem, i placed all the products in an array like so:
$producten = array("Pizza Margherita", "Pizza Funghi", "Pizza Hawai", "Pizza Quatto Stagioni", "Pizza Calzone", "Broodje Shoarma" ,"Broodje Donor", "Durum Doner", "Knoflook Saus", "Whiskey Saus", "Sambal Saus");
and i show it on the page like so:
echo "<table>";
foreach ($producten as $producten){
echo "<tr>";
echo "<td>";
echo $producten;
echo "</td>";
echo "<td>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
As you can see the second TD is empty, here is where i need to add the amount of items ordered.
But i don't really know how i should make it so that i can add all the $_POST items which i currently have like these:
$Margherita = $_POST['PizzaMargherita'];
$Fungi = $_POST['PizzaFungi'];
$Hawai = $_POST['PizzaHawai'];
$QuattroStagioni = $_POST['PizzaQuattroStagioni'];
$Calzone = $_POST['PizzaCalzone'];
$Shoarma = $_POST['BroodjeShoarma'];
$Doner = $_POST['BroodjeDoner'];
$Durum = $_POST['DurumDoner'];
$Knoflook = $_POST['KnoflookSaus'];
$Whiskey = $_POST['WhiskeySaus'];
$Sambal = $_POST['SambalSaus'];
i read something about making the input field name like products[ ] or something, but the problem is that i'm already using the names for a piece of javascript code on the previous page which, if i change all the names, disables the whole JS code.
I hope my question is clear for you guys.
But to rephrase it very short:
How do I add variables like $Margherita = $_POST['PizzaMargherita']; in an array and let them print out in the other column in my table.

You need a way to associates posts values (lets say $_POST['PizzaMargherita'] for example) with the name of the pizza.
The easiest way is to have your initial array producten indexed with theses keys:
<?php
$producten = array(
'PizzaMargherita' => "Pizza Margherita",
'PizzaFungi' => "Pizza Funghi",
'PizzaHawai' => "Pizza Hawai",
'PizzaQuattroStagioni' => "Pizza Quatto Stagioni",
'PizzaCalzone' => "Pizza Calzone",
'BroodjeShoarma' => "Broodje Shoarma",
'BroodjeDoner' => "Broodje Donor",
'DurumDoner' => "Durum Doner",
'KnoflookSaus' => "Knoflook Saus",
'WhiskeySaus' => "Whiskey Saus",
'SambalSaus' => "Sambal Saus",
);
foreach ($producten as $key => $product){
$number = isset($_POST[$key])?$_POST[$key]:'';
echo "<tr>";
echo "<td>";
echo $product;
echo "</td>";
echo "<td>";
echo $number;
echo "</td>";
echo "</tr>";
}
This solution does not requires you to write all the lines like $Margherita = $_POST['PizzaMargherita'];

Accessing a specific element of an array can be done via the index. Im not sure if that was your question. I just hope so.
$_producten['PizzaMargherita'] = $_POST['PizzaMargherita'];
This will save you a lot of writing. It saves every POST element into the product array and names each index exactly as it is in $_POST
foreach($_POST as $k => $v) {
$producten[$k] = $v;
}

I would make an associative array, using the key as the item and the value as the amount, like this:
$producten = array("Pizza Margherita"=>"2", "Pizza Funghi"=>"1", "Pizza Hawai"=>"2");
then you can foreach like this:
echo "<table>";
foreach ($producten as $item=>$quantity){
echo "<tr>";
echo "<td>";
echo $item;
echo "</td>";
echo "<td>";
echo $quantity;
echo "</td>";
echo "</tr>";
}
echo "</table>";

Try this:
(This is how I think you mean it)
$producten['PizzaMargherita']['Aantal'] = $Margherita;
echo "<table>";
foreach ($product as $producten){
echo "<tr>";
echo "<td>";
echo $product;
echo "</td>";
echo "<td>";
echo $product['Aantal'];
echo "</td>";
echo "</tr>";
}
echo "</table>";
That should do it!
P.S. Krijg er honger van!

I know this is not the answer you want to hear but it is the correct and proper way to do this:
orderpage.html
<form action="summary.php" method="POST">
Margherita
<br />
<input type="text" name="pizzas[Margherita]" value="0" />
<br />
<br />
Fungi
<br />
<input type="text" name="pizzas[Fungi]" value="0" />
<br />
<br />
Hawai
<br />
<input type="text" name="pizzas[Hawai]" value="0" />
</form>
summary.php
<?php
// uncomment the line below when you need to debug
// echo '<div style="background-color:white; padding:15px;"><pre>'.print_r($_POST, true).'</pre></div>';
$total_pizzas = 0;
echo "<table>";
foreach ($_POST['pizzas'] as $producten=>$quantity)
{
echo "<tr>";
echo "<td>";
echo "Pizza $producten";
echo "</td>";
echo "<td>";
echo $quantity;
echo "</td>";
echo "</tr>";
// make sure the user gave you a number before adding to total
$total_pizzas+= (ctype_digit($quantity) ? $quantity : 0);
}
echo "<tr>";
echo "<td>";
echo "Total Pizzas";
echo "</td>";
echo "<td>";
echo $total_pizzas;
echo "</td>";
echo "</tr>";
echo "</table>";
?>
If you need help altering the Javascript please let me know.

Related

Updating mySQL table with user interface - PHP

[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples

How can create a separate click event for each input button displayed using a while loop

I am listing users from the database in a table. for each user; there is an 'Approve' and 'Reject' button.
I want to put my code in such way that when i click each button for each user,only the approval or the reject event should affect that specific user? My table looks like this:
right now when i click 'approve' on one user, the other user's approval event also gets triggered. here is my approval code:
$sql = "select * from user_table ORDER BY date_registered DESC LIMIT 10";
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)){
$emailadr = $row["email"];
$adresses [] = $emailadr;
echo "<tr>";
echo "<td>";
echo $row["firstname"];
echo "</td>";
echo "<td>";
echo $row["lastname"];
echo "</td>";
echo "<td>";
echo $row["idnumber"];
echo "</td>";
echo "<td>";
echo $row["qualification"];
echo "</td>";
echo "<td>";
echo $row["dofa"];
echo "</td>";
echo "<td>";
echo $row["date_registered"];
echo "</td>";
echo "<td>";
echo '<button name="approve" value='. $row["user_id"].'>Approve</button> <button name="reject" value='. $row["user_id"].'>Reject</button>';
echo "</td>";
echo '</tr>';
}
if(isset($_POST['approve'])){
// Approved user ID is now in $_POST['approve']
mail($adresses[$row["user_id"]],'subect
1','approved','From:email#example.com');
}elseif(isset($_POST['reject'])){
//
}
}
print_r($adresses);
When inserting new users, you normally have a auto increment column that relates to each row or user (generally called ID) you can do it a few ways first thing you need to do is include that ID or value so you know which user to change:
Create your Buttons:
<button name="approve" value="5"> Approve</button>
<button name="reject" value="5"> Reject</button>
You would update the value to your user ID
You can then simply check whether you have Approved or Rejected the user:
if(isset($_POST['approve'])){
// Approved user ID is now in $_POST['approve']
}elseif(isset($_POST['reject'])){
// Rejected user ID is now in $_POST['reject']
}
To get $adresses you need to assign it outside the loop. Also updated $adresses [] to array_push($adresses, $row["email"]); just because of preference but can be changed back if you prefer.
<?php
$adresses = array();
$sql = "select * from user_table ORDER BY date_registered DESC LIMIT 10";
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
array_push($adresses, $row["email"]);
echo "<tr>";
echo "<td>";
echo $row["firstname"];
echo "</td>";
echo "<td>";
echo $row["lastname"];
echo "</td>";
echo "<td>";
echo $row["idnumber"];
echo "</td>";
echo "<td>";
echo $row["qualification"];
echo "</td>";
echo "<td>";
echo $row["dofa"];
echo "</td>";
echo "<td>";
echo $row["date_registered"];
echo "</td>";
echo "<td>";
echo '<button name="approve" value='. $row["user_id"].'>Approve</button> <button name="reject" value='. $row["user_id"].'>Reject</button>';
echo "</td>";
echo '</tr>';
}
if(isset($_POST['approve'])){
mail($adresses[$_POST["approve"]],'subect 1','approved','From:email#example.com');
//update DB to approved
}elseif(isset($_POST['reject'])){
//update DB to rejected
}
}
print_r($adresses);
?>
Yes.. Passing the contentid or some unique identifier will solve this.

value of $_POST is always the last value of my <tr>

I have a problem in which I cannot solve. I have a simple page where I query all Users and list them in a table. When a user clicks on one of the table rows, it should be taken to another page where the user can edit information of the that they picked. The problem is that in my script, the $_POST value is always the value of the last
CODE
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub();'>";
echo "<td>";
echo $assoc['UserID'];
echo "<input type = 'hidden' name = 'UserID' value = '". $assoc['UserID'] ."' />";
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(){
document.getElementById("edit").submit();
return false;
}
</script>
I've slightly modified your code - this should work:
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub(". $assoc['UserID'] .");'>";
echo "<td>";
echo $assoc['UserID'];
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(UserID){
document.location.href = 'http://www.yourdomain.com/something.php?UserID='+UserID;
return false;
}
</script>

loop list of input checkbox and get values

I am trying to get a table of names checked,
and send this array to a PHP page.
But I dont know how, I began by this code:
$(".ok").click(function(){
$("input[type='checkbox']:checked").each(function() {
var tt = $(this).val();
alert(tt);
});
});
echo "<table>";
foreach ($result as $data) {
echo "<tr>";
echo "<td><input type='checkbox' value='$data[0]' /></td><td>$data[0]</td>";
echo "</tr>";
}
echo "</table>";
Try..
$(".ok").click(function(){
//check if any are checked and if so redirect..
if($("input[type='checkbox']:checked").length > 0)
window.location.href = 'page.php?'+$("input[type='checkbox']:checked").serialize();
});
then in page.php..
$result = $_GET;
if(count($result)){
foreach($result as $data){
echo "<tr>";
echo "<td><input type='checkbox' value='$data' /></td><td>$data</td>";
echo "</tr>";
}
}

Echoing a table in PHP

I want to have this table in PHP? how can I create this and use it in Javascript after?
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
echo "<td>";
echo "<div";
echo "class='hiding' style='display:none'>" . $row['meaning'];
echo "</div>";
echo "</td>";
echo "<td>";
echo "<input name=\"f\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
I want to use columns that have class=hiding attribute. but in this way it doesn't work and I have an error:
document.getElementsByClassName(...).item(0) is null
document.getElementById('hiding').style.visiblility = 'visible';
I think I should echo table another way but I don't know how?
Here is my Javascript code:
document.getElementsByClassName.item(0).('hiding').style.visiblility = 'visible';
You can not use getElementById to get an element by its classname.
Try something like
document.getElementsByClassName('hiding')[0].style.visibility = 'visible'
change style.visiblility to style.display, and style.display = 'block' for shown

Categories

Resources