This is assignment so not looking for anything perfectly safe and secure, just working.I have table in SQL database, I'm printing down all records, all records have unique reference number, for each row of the database I printed down I gave checkbox with value of the row's ref. number, when I submit them by "POST" everything is working and printing out:
if (!$_POST['checkbox']) {
echo "Your basket is empty.";
} else {
echo "<table border='0' id='games_table' cellspacing='1'>";
echo "<tr id='basket_table_row'>";
echo "<td colspan='3'>" . "Logged: " . $_SESSION['user'] . "</td>";
echo "<td colspan ='2'>" . "OS used on this machine: " . "<script type='text/javascript'>document.write(yourOS())</script><noscript>Computers</noscript>" . "</td>";
echo "</tr>";
echo "<tr id='basket_table_row'>";
echo "<td colspan='5'>" . "You put into the basket these games: " . "</td>";
echo "</tr>";
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket']=array($value);
$res=pg_query($conn,"select * from CSGames where refnumber='$value'");
while ($a = pg_fetch_array ($res)) {
echo "<tr id='games_table_row'>";
echo "<td>" . $a["refnumber"] . "</td>";
echo "<td>" . $a["title"] . "</td>";
echo "<td>" . $a["platform"] . "</td>";
echo "<td>" . $a["description"] . "</td>";
echo "<td>" . $a["price"] . "</td>";
echo "</tr>";
}
}
echo "</table>\n";
}
but only think which stays recorded in $_SESSION['basket'] is value of the last checkbox but I need all of them (60 or 70).
what Am I doing wrong?
You are overwriting te value of $_SESSION['basket'] at each iteration of the loop.
The last value is the only one stored.
Currently, you are only storing the last value, if you wish to store every value, you should add it like this:
$_SESSION['basket'][] = $value;
foreach($_POST['checkbox'] as $value){
$_SESSION['basket']=array($value);
}
every iteration of your loop is overwriting the value in $_SESSION['basket'], hence you only seeing the last checkbox value.
In every step of foreach, you create a new array in $_SESSION['basket'] with only one item, the current value of $value. It is corrected like this:
// ...
$_SESSION['basket'] = array();
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket'][] = $value;
// ...
}
// ...
You can directly do it like this
$_SESSION['basket'] = $_POST['checkbox'];
because the data of $_POST['checkbox'] is an array anyway.
What you are doing is looping the $_POST['checkbox'] and saving each data as array to a session.
this $_SESSION['basket'] = $_POST['checkbox'];
and
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket'][]=$value;
}
will have the same value.
What you have right only saves the last value of $_POST['checkbox']
Related
From the research i conducted in SO, this is the only other question similar to what i need, but im afraid that i didnt help me (How to replace null results in sql query result table with a string?).
I have a table that prints the Medical History of a Patient, and the table cells are restored from a database.
A portion of the code is down below:
echo "<tr>";
echo "<th>MRI Onset Localisation</th>";
echo "<th>CNS MRI Lesions Y/N </th>";
echo "<th>CNS MRI Lesions No.</th>";
echo "<th>CNS MRI Location</th>";
echo "<th>Person Signing the form</th>";
echo "<th>Documented at</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['Onsetlocalisation'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['smoker'] . '<br>' . $row['cigars'] . '<br>' . $row['cigardate'] . "</td>";
echo "<td>" . $row['onsetsymptoms'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['MRIonsetlocalisation'] . "</td>";
echo "<td>" . $row['MRIenhancing'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['MRInum'] . "</td>";
echo "<td>" . $row['MRIenhancinglocation'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['signer'] . "</td>";
echo "<td>" . $row['reg_date'] . "</td>";
echo "</tr>";
And the MySQL Query that returns those fields is
$sql = "SELECT * FROM tblName WHERE somefield = $somevar";
The thing is... Some of those fields are allowed to have NULL as a value, but for the front end of the app, i want the table cells that contain NULL values to print a standard string such as "N/A" or "Empty" but i need it to be done inside of the php table portion of my code, or so i think...
I found numerous questions about replacing NULL with a string inside of the MySQL query, but i don't care about that since the query doesn't appear at the end user outside of the table.
I tried to implement the coalescing operator in the following way, but no nothing was displayed:
echo "<td class='tdclass exempt'>" . $row['MRInum'] ?? "N/A" . "</td>";
Any help is absolutely welcome.
You need to put the expression in brackets to make it clear which parts are supposed to be evaluated by the null coalescing operator:
echo "<td class='tdclass exempt'>" . ($row['MRInum'] ?? "N/A") . "</td>";
If you don't, it thinks the "<td class='tdclass exempt'>" is part of the text to be checked for existence - which means it always returns true because that hard-coded text always exists.
You can do this in two ways.
From SQL:
COALESCE(fieldName, 'N/A') AS fieldName
will replace NULLs with, you guessed it, 'N/A'.
Otherwise, when you fetch the row,
$row = $stmt->fetch(PDO::FETCH_OBJECT);
you can vet it:
$replacements = [
'MRI_Data' => 'N/A',
'MRI_Type' => [
'001' => 'Single Scan',
'002' => 'Multi Scan',
'003' => 'Pulsed',
'(null)' => 'N/A',
],
];
foreach ($row as $key => $value) {
if (array_key_exists($key, $replacements)) {
if (is_array($replacement[$key])) {
if (empty($value)) {
$value = '(null)';
}
if (array_key_exists($value, $replacement[$key])) {
$row[$key] = $replacement[$key][$value];
}
} else {
if (empty($value)) {
$row[$key] = $replacement[$key];
}
}
}
}
I have a php file that creates a table for me using data fetched from a mysql database.
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "<td>" . $row['District'] . "</td>";
echo "<td>" . $row['Population'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "<td><input type=\"number\" name="quantity" id="quantity"></td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
At the end of each row, I have an input number so that I can calculate the amount of each product(countries in this case). How could I get the amount of each country, multiply it by the price and return a total at the end of my table?
If you want to do it with PHP, you have to do it in two steps, because the PHP is processed in the server. So you would enter all the quantities you want and when you press the "Compute" button, the page would send all the values to the server who would compute everything you want and give you the final result.
A problem that I see with this solution is that once you have get all the quantities you want, you would have to get the prices once more. I don't its very efficient because you already have them on the first page. I see two solutions here :
When you display the values, keep track of the prices in a $_SESSION field, thus you will be able to access them after leaving the page, without having to get them from the database.
When you display the values, display the prices in an input field (I would recommend as readonly so that the user won't change this value here), and thus they would be included in the $_POST (or $_GET, if you use this) variable that your browser would send to the server.
If you're only interested to display the value, without using it after, you can use javascript to compute it, it might be easier.
Even though it's not the point here, you should be careful when displaying inputs via PHP on a while loop, because here all of your inputs have the same id, which would make thing harder to compute what you want to.
Hope it helps!
You must add a form tag around the table and then sum record price * qty on every row
What I did here is I checked if the quantity is set in the POST variable or not. if it exists I put data in quantity value. after that, you must make the name of quantity capable of taking array inside with the key of record Id.
after that, if the form submitted the quantity will send back to the page as a query string. then I multiply the price with quantity and add it to sum varaible. after finishing the loop and echo out the sum variable at the end of the table.
$html = '';
if ($result->num_rows > 0) {
$html .= '<form method="GET" action="" target="_self>';
$row = $result->fetch_assoc();
if(isset($_GET['quantity'][$row['ID']]))
$qty = $_GET['quantity'][$row['ID']];
else
$qty = 0;
$sum = 0;
// output data of each row
while ($row) {
$html .= '<tr>';
$html .= '<td>' . $row['ID'] . '</td>';
$html .= '<td>' . $row['Name'] . '</td>';
$html .= '<td>' . $row['CountryCode'] . '</td>';
$html .= '<td>' . $row['District'] . '</td>';
$html .= '<td>' . $row['Population'] . '</td>';
$html .= '<td>' . $row['Price'] . '</td>';
$html .= '<td>
<input type="number" name="quantity[' . $row['ID'] . ']" value="' . $qty . '">
</td>';
$html .= '<td>' . ($sum += $row['Price'] * $qty) . '</td>';
$html .= '</tr>';
}
$html .= '<input name="submitForm" value="submitForm">';
$html .= '</form>';
$html .= '<tr>';
$html .= '<td>Total = '.$sum.'</td>';
$html .= '</tr>';
} else {
$html .= "0 results";
}
$conn->close();
echo htmlspecialchars($html);
remember to use htmlspecialchars to echo out the result.
I am trying to sort an associative array in ascending in order and then transfer it to a HTML table and I am currently stumped at an error. I looked for guidelines here on SO and followed instructions on some posts:
PHP display associative array in HTML table
But still no luck, here is my attempt:
<?php
function format($g){
array_multisort($g, SORT_ASC);
echo "<table>";
foreach($g as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
$bib = array("Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40");
format($bib);
?>
My debugger is telling me there is an error at my for each loop but I don't see how it is wrong unless there is some syntax error that I am not seeing? The error is saying Invalid argument supplied for foreach()
Because your $bib is only single array but you use two foreach to loop this array
At 2nd loop, your $row variable is a string, you can't use foreach for this type
Can you try that for single array ?
<?php
function format($data) {
array_multisort($data, SORT_ASC);
echo "<table>";
foreach($data as $k => $v) {
echo "<tr>";
echo "<td>$k</td>";
echo "<td>$v</td>";
echo "</tr>";
}
echo "</table>";
}
$bib = array("Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40");
format($bib);
?>
$k is Luke John Matt and Mark,
$v is 10 30 20 and 40
You can see the foreach example here: http://php.net/manual/en/control-structures.foreach.php
Hope this helpful ^^
You can try this
<?php
function format($data){
array_multisort($data, SORT_ASC);
echo "<table>";
foreach($data as $key => $row) {
echo "<tr>";
echo "<td>" . $key . "</td>";
echo "<td>" . $row . "</td>";
echo "</tr>";
}
echo "</table>";
}
$bib = array(
"Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40"
);
format($bib);
?>
To begin with I know very little PHP and no java/javascript or jquery. I have created an html table populated from mysql database. It is for a call log. I am wanting to click on either a <td> or <tr> to open the corresponding record in a new page to be viewed in more detail. I have thought about putting the call_id value in a hidden column to be used in a variable somehow, but don't know where to go from there or if that is anywhere near the correct way to accomplish this.
Assuming that you're creating the table doing something like this,
$results = some_mysql_query;
foreach ($results as $index => $array) {
echo "<tr>";
echo "<td>";
echo $array['RecordNumber'];
echo "</td>";
echo "<td>";
echo $array['CallerName'];
echo "</td>";
echo "<td>";
echo $array['Time'];
echo "</td>";
echo "<td>";
echo $array['Duration'];
echo "</td>";
echo "</tr>";
}
Then you can add in a link by doing something like this:
$results = some_mysql_query;
foreach ($results as $index => $array) {
echo "<tr>";
echo "<td>";
echo "<a href='recordInfo.php?record='" . $array['RecordNumber'] . "'>" . $array['RecordNumber'] . "</a>";
echo "</td>";
echo "<td>";
echo "$array['CallerName'];
echo "</td>";
echo "<td>";
echo $array['Time'];
echo "</td>";
echo "<td>";
echo $array['Duration'];
echo "</td>";
echo "</tr>";
}
NOTE the use of single-quotes, ', inside the double-quotes - and the '" / "' surrounding the variable.
Alternatively, your echo with the link could look like this:
echo "<a href='recordInfo.php?record='{$array['RecordNumber']}'>{$array['RecordNumber']}</a>";
These accomplish the same thing.
This principle is the same, BTW, if your code looks like this:
$results = some_mysql_query;
while ($row = mysql_fetch_array($result)) {
...
echo $row['RecordNumber'];
Also, in case you're not already aware of how this will work, your recordInfo.php will receive its information in the $_GET array; specifically, it will refer to the RecordNumber as $_GET['RecordNumber'].
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP: How to remove specific element from an array?
I've got an array for holding shopping basket information:
session_start();
$items = $_SESSION['items'];
$values = $_SESSION['values'];
if (isset($_POST['addtobasket']))
{
$items[] = $_POST['item'];
$values[] = $_POST['value'];
$_SESSION['items'] = $items;
$_SESSION['values'] = $values;
}
print("Added " . $_POST['item'] . " with value of " . $_POST['value'] . "to basket");
?>
At the checkout screen I'd like to be able the user to be able to remove items:
<?
echo "<table class='basketdisplay'>";
echo "<tr><td>Item</td><td>Price</td></tr>";
foreach($items as $key => $item)
{
echo "<tr>";
echo "<td>" . $item . "</td>";
echo "<td>£" . $values[$key] . "</td>";
echo "<td>" . $key . "</td>";
echo "</tr>";
}
echo "</table>";
?>
So instead of the last column showing the key, some form of button to remove the item at that key?
Does anyone know how I'd go about this, my php is not strong. TIA
You could use http://php.net/manual/en/function.unset.php to remove items from the array.
You'd have to figure the code though:)
unset($array[$key]);
manual
if(isset($_REQUEST['removeitem']))
{
unset($items[$_REQUEST['removeitem']]);
}
Where $_REQUEST['removeitem'] is the key of the item you want to remove. Then have your href do something like remove item.
Regarding your removal feature, you could just use a checkbox (or even a submit button) like:
echo "<td><input type=checkbox name='remove[$key]' value=1>remove</td>";
(Take care that all variables ($key) in your output also need htmlspecialchars() handling.)
Then if the basket form is submitted again, you can simply probe for elements to be removed with:
foreach ($_REQUEST["remove"] as $key) {
unset($_SESSION["items"][$key]);
}
Firstly, change this line:
echo "<td>" . $key . "</td>";
to this:
echo "<td><a href='new_php_page.php?key=$key'>Remove Item</td>";
new_php_page.php:
<?php
session_start();
$items = $_SESSION['items'];
// validate session key here - that it is an integer etc.
if (array_key_exists($_POST['key'], $_SESSION['items'])) {
unset($_SESSION['items']);
}
// redirect to cart page again
?>
An improvement would be to replace the link to a button. You could then consider using AJAX to have the item removed 'behind-the-scenes'.
Make the table a form and the final element of the row an HTML input field:
<FORM target="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<?php
echo "<table class='basketdisplay'>";
echo "<tr><td>Item</td><td>Price</td></tr>";
foreach($items as $key => $item)
{
echo "<tr>";
echo "<td>" . $item . "</td>";
echo "<td>£" . $values[$key] . "</td>";
?>
<TD>
<INPUT type="submit" name="DELETE_<?php echo $key; ?>" value="Delete"/>
</TD>
<?php
echo "</tr>";
}
echo "</table>";
?>
</FORM>
And then at the start of the script, use something like:
<?php
foreach ($_POST as $name=>$value)
{
if (preg_match('/^DELETE_(\d+)$/',$name,$matches)) //Assumes that $key is numeric
{
$keyToDelete=$matches[1];
// Put your delete code in here
}
}
?>
or something like that.
First, you must use prepared statement to prevent SQL Injection and for filtering purpose. Use PDO for this.
but i don't sure, because you don't make any link for user to delete their item.
first you must make an unique id for all item, so easy for you to remove, example :
echo 'Remove'