Multi Dimensional Array Challenge - php

I have been reading endless posts today on php arrays, and multidimensional arrays ... I'm a tad confused :)
I have a mySql table that has rows that consist of the following columns:
name, email, choice1, choice2, choice3, choice4, choice5, choice6, choice7, choice8, choice9, choice10
I'm populating an array as follows:
while($row = mysql_fetch_assoc($result)){
$allResults[$index] = $row;
$index++;
}
I know I can access the data by $allResults[0][name]; that all is fine.
However here is what I'm trying to do.
One of the rows will include a piece of data: IPO3_1 (it would be in one of the choice columns)
I need to cycle through all of the rows in the array, find this data and then pull out the name column. Here is very rough code of my ultimate goal (although incomplete as I cannot get my head around this)
<TR>
<?php
if (in_array("IPO3_1", $allResults[0])||in_array("IPO3_1", $allResults[1])) {
?>
<TD WIDTH="30" ALIGN="CENTER"><input type="checkbox" name="sp1" value="IPO3_1" DISABLED></TD>
<?php
} else {
?>
<TD WIDTH="30" ALIGN="CENTER"><input type="checkbox" name="sp1" value="IPO3_1" ></TD>
<?php
}
?>
<TD WIDTH="210" ALIGN="LEFT"> IPO3 - 1st</TD>
<TD WIDTH="40" ALIGN="CENTER">$120</TD>
<TD WIDTH="270" ALIGN="CENTER"><?php echo $allResults[0][name]; ?></TD>
</TR>
Basically when I find the value "IPO3_1" in any row, I need to disable a checkbox , and also add the name into the table
There could be as many as 34 rows in my mySql table maximum. THere are 34 values similiar to "IPO3_1" but are all unique text strings.
Any thoughts to get me pointed in the right direction ?

I've written as undestood the task. But I'm not shure in my undestanding :)
// $row will be false if string will be not found anywhere
// else it will be index of row, in wwhich first occurence found
$row = false;
foreach($allResults as $key=>$value) {
// remove non-'choice' fields
unset($value['name']);
unset($value['email']);
// Lookup the string in other field
if(in_array('IPO3_1', $value, true))
// if found break the loop
{ $row = $key; break; }
}

Related

Getting id from a textarea in a while loop in PHP for updating in mysql

I have a table where is one week displayed (each row is one day).
I get the rows from a while loop from my database. The rows are displayed in bootstrap accordions.
There is a textarea in every accordion row where the user can input (update) some text.
I want to update this text into my database. It should update the text depending on the day id.
<form method="POST" action="">
<table class="table table-hover" style="border-collapse:collapse;">
<thead>
<tr>
<th>Weekday</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php
// Select Statement (for shortening not included into this Stack question)//
while($row = $statement->fetch()) {
$thedate = $row['Date'];
$weekday=strftime("%A", strtotime($thedate));
$date=date('d-m-Y', strtotime($thedate));
echo "<tr data-toggle='collapse' data-target=#".$row['Date']." class='clickable collapse-row collapsed'>";
echo "<td >".$weekday."</td>";
echo "<td>".$date."</td>";
echo" <td style='color:black; font-size:20px;'><i class='fas fa-angle-down'></i></td>";
echo "</tr>";
echo "<tr><div class='accordian-body collapse' id=".$row['Date'].">
<td colspan='1' class='hiddenRow'><textarea name=".$row['id']." rows='5' cols='80'>".$row['Text']." </textarea></td>
//the $row['id'] should give every textarea a unique dayid from my database
echo"</td>
</div></tr>";
}
if(ISSET($_POST['id'])){
$debug=$_POST['id'];
}
var_dump($debug); // var_dump for debugging. See text below
?>
</tbody>
</table>
<button type="submit" name="Speichern" class="btn btn-lg btn-primary btn-block">Speichern</button>
</form>
Before writing the Sql Update Statement I wanted to debug to find possible bugs.
If i debug this with var_dump I get the error message "Undefined variable $debug" and I dont know why. The variable shouldnt be empty because in the textareas is always text.
Im new to PHP and coding at all so probably Im making a dump mistake.
EDIT: If I put the var_dump inside the if condition i get nothing as return.
I tried it also with the var_dump in the if block but then i get nothing as return.
That’s because you do not have any form field that is actually named id. You put name=".$row['id']." on your textarea, and that is likely a numeric value. And you probably don’t know which one that will be, on the receiving end.
Plus, since you are creating multiple such fields in a loop, PHP will overwrite all values for this parameter with the last one. You need to use a naming scheme that includes square brackets to avoid that, something like name="foo[]" - then $_POST['foo'] will become an array that you can loop over.
And since you will still need your record ID to associate with the data, you can put that into the brackets, name="foo[123]" – then this 123 will become the key of that array element, for this specific textarea.
If you loop over that using the extended foreach syntax, then you have easy access to the ID, and the value entered by the user:
foreach( $_POST['foo'] as $id => $value ) { … }

New lines HTML if value changed in MySql Output via PHP

This is the HTML/PHP , I am using to display some data.
<body>
<section>
<h1>Facebook Search</h1>
<!-- TABLE CONSTRUCTION-->
<table>
<tr>
<th>Comment</th>
<th>Comment Made By</th>
<th>Commentor's Profile Link</th>
<th>Comment ID</th>
<th>Post ID</th>
</tr>
<!-- PHP CODE TO FETCH DATA FROM ROWS-->
<?php // LOOP TILL END OF DATA
while($rows=$result->fetch_assoc())
{
?>
<tr>
<!--FETCHING DATA FROM EACH
ROW OF EVERY COLUMN-->
<td><?php echo $rows['comtext'];?></td>
<td><?php echo $rows['comby'];?></td>
<td><?php echo $rows['compro'];?></td>
<td><?php echo $rows['commentid'];?></td>
<td><?php echo $rows['postid'];?></td>
</tr>
<?php
}
?>
</table>
</section>
</body>
</html>
and I am getting the data like this from the db.
$sql = "SELECT comments.*, posts.postid FROM comments JOIN posts USING(postid)";
$result = $mysqli->query($sql);
$mysqli->close();
This outputs a single table with all the data. My question is , is there a way to break the single table into tables when the value of postid changes? It goes like..is 1 for x number of rows, then 2 for x number of rows and so on. I wanted to have a little break between those tables.
is there a way to break the single table into tables when the value of postid changes
You should stop using "SELECT *", it's inefficient and makes code difficult to maintain. While we're talking about style here, you swap back and forth between PHP and inline HTML which also impacts the readability of your code.
As to your question...
You need to ensure that the output of your query is sorted by postid - or you're going to get a lot of tables.
Use a state variable to track the postid from the previous iteration of the loop.
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
The problem with this is that each iteration of the expects that you've already written <table> to the output stream - including the first iteration. You could do this before the loop - but you'll end up with an empty table at the top of the page. You could add another state variable to track whether you have opened a table tag yet. Personally, I'd go with making inferences from the value of the existing state variable:
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
$prev || close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
(the || is a quick way of writing if (not(condition)) do something() )
Note that unless you fix the size of the columns, then each table will be independently sized to fit the data that resides within it.

How to match two to three words in a text file with whitespace in PHP

I am somewhat new to PHP but have created almost everything I need, except one thing which has led me here. I am creating a simple (for you probably but not for me) site for a friend so they can keep track of when they receive rent payments, input new tenants, and check current balances. I had everything working perfect...I thought. When checking the balance, I tested with only one word input to read the text file and output the proper info. But, what I found is if the first and last name are stored with a space between then, I am not getting a match. I need code to read the inputted tenant name in its entirety with the space between. I haven't found anything I could really comprehend and have been searching for several nights. Here is my full code for searching and retrieving results.
The text file being searched is like this:
John Doe,123 Main St,400.00,01/01/2016,
Jane Doe,124 Main St,300.00,01/01/2016,
John Doe,123 Main St,,01/03/2016,200.00
<?php
$lines = file('data.txt'); //here's the filename
?>
<center>
<table id="historytable" width="640" border="1">
<caption>Billing & Payment History
</caption>
<tbody>
<tr>
<td width="40">Tenant</td>
<td width="40">Address</td>
<td width="40">Date</td>
<td width="40">Rent</td>
<td width="40">Payment</td>
</tr>
<?php
$search = $_POST["name"]; //assigning a string to each piece of input data
// Store true when the text is found
$balance = 0; //assign initial value to balance
$renttotal = 0; //assign initial value to renttotals
$received = 0; //assign initial value to received
$found = false;
foreach ($lines as $line) { //this is the loop to read the txt file
{
if(strpos($line, $search) !== false)
{
$found = true;
list($a,$b,$c,$d,$e) = explode(',', $line); //this assigns a variable name to each data item separated by a comma
$renttotal+= $c; //each time it loops, it gathers the value of c adding it to itself same for the two lines below
$received+= $e;
$balance = $renttotal - $received; //subtracts the final value of renttotal and received assigning the difference to balance
$line_array = explode(",", $line); //breaks each piece of data apart to be placed in a table }
echo "<tr>
<td width=40>$a</td>
<td width=40>$b</td>
<td width=40>$c</td>
<td width=40>$d</td>
<td width=40>$e</td>
</tr>";
}}}
?>
</tbody>
</table>
</center>
<BR />
<BR />
<center>
<p>TOTAL RENTS CHARGED $<?php echo "$renttotal"?><br />
TOTAL PAYMENTS RECEIVED $<?php echo "$received"?><br />
BALANCE DUE $<?php echo "$balance"?></p>
Thank you in advance for any help.
Simply do a urldecode() like so:
$search = urldecode($_POST["name"]);
And you should be fine afterwards.

Table of postmeta row (in array) - Wordpress

I need help for a little problem with my custom metabox in Wordpress.
I have a table with a group of 3 values per row. Number of row is undefined, because users can add or remove one of them.
I need to save each row (so 3 values in 3 inputs) in a specific array.
For this source code, i removed voluntarily all the system which is add a row, delete a row etc... I also remove all the query/variable tests.
I think this problem isn't difficult to solve, but i don't see any solution..
Thanks!
function my_meta($post){
$get_values = get_post_meta($post->ID,'_MY_META_ROW',false);
echo '<table>';
foreach($get_values as $v => $MY_META_ROW){
echo '<tr>
<td><input type="text" name="MY_INPUT_1" value="'.$MY_META_ROW['INPUT_1'].'" /></td>
<td><input type="text" name="MY_INPUT_2" value="'.$MY_META_ROW['INPUT_2']'" /></td>
<td><input type="text" name="MY_INPUT_3" value="'.$MY_META_ROW['INPUT_3'].'" /></td>
</tr>';
}
echo '</table>';
}
add_action('save_post','save_my_inputs');
function save_my_inputs($post_id){
foreach($_POST['??????????'] as $value){
$array_row = array (
"MY_INPUT_1" => $POST['MY_INPUT_1'];
"MY_INPUT_2" => $POST['MY_INPUT_2'];
"MY_INPUT_3" => $POST['MY_INPUT_3'];
)
add_post_meta($post_id, '_MY_META_ROW', $value);
}
}

Getting table elements in same row with jquery

I am really confused about how I can do this. I need to get the value of two <td> when one is selected. For example, below let's say I select the td with id=monthly of $550 dollars. I need to get the age and excess that corresponds with that price. I hope this makes sense. SO in the example of selecting $550 I need jQuery to get the values age(18-24) and excess($1000). I then will take these two values and insert into mysql as noted below. Is there anyway I can do this with either jQuery or PHP? I am open to ideas.
<table>
<tr>
<td width="67"></td>
<td width="102" id="excess">$1000</td>
<td width="102" id="excess">$2000</td>
</tr>
<tr>
<td width="67" id="age">18-24</td>
<td width="102" id="monthly">$550</td>
<td width="102" id="monthly">$650</td>
</tr>
<tr>
<td width="67" id="age">25-29</td>
<td width="102" id="monthly">$750</td>
<td width="102" id="monthly">$850</td>
</tr>
</table>
MYSQL(using the example above):
$query = mysql_query("UPDATE table SET Monthly = '$550' WHERE Age = '18-24' AND Excess = '$1000'")or die(mysql_error());
Your HTML is invalid. You cannot have more than one element with the same id, id values (as the name suggests) must be unique. If you're trying to classify elements, use a class. The rest of this answer assumes those id values have been changed to class names.
If I understand you, you want to handle clicks on cells with the monthly class and get the text of the first cell in the row along with the first cell in the column. This is easily done with jQuery (live example | source):
$("td.monthly").click(function() {
var $this = $(this),
firstCellInRow = $this.closest('tr').find('td').first(),
firstCellInColumn = $this.closest('table').find('tr').first().find('td').eq($this.index());
console.log("First cell in row: " + firstCellInRow.text());
console.log("First cell in column: " + firstCellInColumn.text());
});
We find the first cell in the row by finding the row via closest, then finding its first cell via find and first.
We find the first cell in the column by finding the table via closest, then getting the first row via find and first, then getting the index of the clicked cell and finding the cell in the first row with the same index via eq.
$('.monthly').bind('click', function()
{
lstrMonth = $(this).html();
lstrAge = $(this).parent().find('td:first').html();
lnIndex = $(this).parent().index($(this));
lstrExcess = $(this).parent('table').find('tr:first td:nth-child('+ (lnIndex + 1) +')');
// do ajax call to a php script which execute the query
$.post('ajax/update.php',
{
age: lstrAge,
excess: lstrExcess,
month: lstrMonth
},
function(data) // success
{
// do whatever you want
});
});
I think this will work, the PHP will simplified look like:
<?php
$query = mysql_query("UPDATE table SET Monthly = '".$_POST['month']."' WHERE Age = '".$_POST['age']."' AND Excess = '".$_POST['excess']."'")or die(mysql_error());
?>

Categories