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'
Related
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'].
I currently have php generating a table from csv. I use tags to identify columns, which i later use jquery and datatables to sort, filter, and highlight.
I am looking for a way to make the data from a column into links. the data is case numbers and there is a predefinited link, you would just added the case number to the end of it and that would be your link to another page.
Do anyone know how I can achieve this, I'll include a snippet below so you can get an idea of how the table is created.
<th>ASUP Created Flag</th>
</tr>
</thead>
<tbody>
END;
//here we open the csv file as read-only
$f = fopen("cases.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
//this starts the alternation of tr and td for building the table
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
//after the table has been built, this is where we close it out
echo "\n</tbody></table></section></div></body></html>";
?>
Are you asking for something like:
<th>ASUP Created Flag</th>
or for the actual cell data:
foreach ($line as $cell) {
echo "<td><a href='some url'>" . htmlspecialchars($cell) . "</a></td>";
}
If you're wondering what some url should be, well that's completely up to you. If it depends on the cell data, then you would need some way to reference a URL given the cell data (either through a lookup array, database table, just some way to associate a URL with the value in $cell).
Update
If you want your case numbers to be links, and the value of the cell is the exact value you want to use in the URL, you can do something like this:
$count = 0;
foreach ($line as $cell) {
$cell = htmlspecialchars($cell);
if($count == 0) {
echo "<td><a href='/case/" . $cell . "'>" . $cell . "</a></td>";
} else {
echo "<td>" . $cell . "</td>";
}
$count++;
}
I have an array coming from a .csv file. These are coming from a real estate program. In the second column I have the words For Sale and in the third column the words For Rent that are indicated only on the rows that are concerned. Otherwise the cell is empty. I want to display a list rows only For Sale for example. Of course then if the user clicks on a link in one of the rows, the appropriate page will be displayed.
I can't seem to target the text in the column, and I can't permit that the words For Sale be used throughout the entire array because they could appear in another column (description for example).
I have tried this, but to no avail.
/* The array is $arrCSV */
foreach($arrCSV as $book) {
if($book[1] === For Sale) {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
I also tried this:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
Do you mean:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div></div>';
}else{
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
}
I found a solution here:
PHP: Taking Array (CSV) And Intelligently Returning Information
$searchCity = 'For Sale'; //or whatever you are looking for
$file = file_get_contents('annonces.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(";",$line);
//and you know city is the 3rd element
if(trim($col[1]) == $searchCity){
$results[] = $col;
}
}
And then:
foreach($results as $Rockband)
{
echo "<tr>";
foreach($Rockband as $item)
{
echo "<td>$item</td>";
}
echo "</tr>";
}
As you can see I'm learning. It turns out that by formulating a question, a series of similar posts are displayed, which is much quicker and easier than using google. Thanks.
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']