I have a problem with a HTML table generated with a PHP class and saved into a variable.
This variable also contains text, saved before the table, but the table is displayed before the text.
Here's what I do :
Put a text in a variable :
$RET='Awesome introduction';
Generate a table with a class of my own (it's still a simple table) :
$TAB=new class_table();
$TAB::add_th('Column'); // saves 'Column' in a 'th' 3D array
$TAB::close_line(); // $num_tr++
$TAB::add_td('Cell'); // saves 'Cell' in a 'td' 3D array
$TAB::display(); // generate the table
When I do this :
$RET='Awesome introduction';
$RET.=$TAB::display();
echo $RET;
... I've got the table before the text.
When I do this :
echo 'Awesome introduction';
$TAB::display();
... I've got the table after the text, and that's correct.
When I generate my table without the class, it's correct too, of course.
Do you know if it's normal (maybe the class' call is executed in first ?) and if I can workaround this ?
I ask because this code is a just a easy sample, the real one is much complex and called with AJAX (and a console.log proves that the table is generated before the text). I hope I'm clear enough.
Thank you.
Yes, probably Completely normal. This Display class is probably doing exactly that. Displaying, not returning values. You are assigning nothing to the $RET.= , You can prove it by echoing it a second time, it will print your header a second time but not your table. At the time that you assign nothing to RET you output the table, probably with print statements or echo statements in the Display class. There maybe be some way to use the eval function to capture the output of the Display class, but that's above my pay grade. (This would just be a comment, but i haven't earned the privilege.)
Related
I'm currently scraping code from a website and I like to mark something, so I need to add a new class to a table row if a cell inside the row does match a pattern.
Structure of the table with the key to search for:
<tr><!-- other code --><td>MY KEY</td><!-- other code --></tr>
This should be transformed to the following:
<tr class="mark"><!-- other code --><td>MY KEY</td><!-- other code --></tr>
I tried the following:
preg_replace('#<tr>(.*)<td>MY KEY</td>(.*)</tr>#', '<tr class="mark">$1<td>MY KEY</td>$2</tr>', $html);
This is not working, and I can't get it to work. I tried some other variations with an eye on the PHP documentation about the function, but these were even worse.
EDIT: The problem is, that too many rows get marked even those which doesn't have this <td>MY KEY</td>.
Someone may help me?
Thanks in advance.
Regards
From the previous comments I understand you cannot show the full code because it holds private data.
Then I had the idea to ask you for only one example of an "alien" row (one being selected though not containing your "MY KEY". At this time I realized that in fact "MY KEY" itself might probably hold private data.
And it leads me to this hypothesis: the real content of "MY KEY" might include some regex-significant characters. If so, did you pay attention to carefully escape them?
This should work :
preg_replace('#<tr>(.*)<td>MY KEY</td>(.*)</tr>#', '<tr class="mark">$1<td>MY KEY</td>$2</tr>', $html);
I have a table with 32,000 entries.
Each entry has a JSON blob against it:
{
"property1": "someValue",
"property2": "AnotherValue"
}
I now need to append another property to this blob for every entrant so that we have:
{
"property1": "someValue",
"property2": "AnotherValue",
"property3": "YetAnotherValue"
}
Because someValue and AnotherValue will be different for different entries I cannot just replace the old records with the new one. Instead (I'm guessing) I'm supposed to parse JSON, add property3 and return it to DB for each of the 32,000 records.
What is the best way to achieve this? I have a MySql database which I interact with through PhpMyAdmin.
I tried writing a PHP script which will basically select and loop through every row, parse and append to my JSON blob and put it back up for every record. However after I run this in a browser it simply times out on me because it takes too long to execute (I suspect it's the wait time between pulling the blob and uploading it back up for every record).
Any help is greatly appreciated!
I would question the need to save JSON into a MySQL DB directly. Let's say your table with the JSON blob is called my_table and it has an id field. I'd create another table, say, my_json_properties. There, I'd create three columns: my_table_id, property_name and property_value. Then just populate that table with the JSON properties, and adding new properties is trivial. Also remember to delete the blob column and of course to update your data access objects.
Note: use the InnoDB storage engine so you get to make the my_json_properties.my_table_id into a foreign key that references my_table.id. MySQL also automatically creates an index with the foreign key columns, so it's very effective to query the properties when you just know the id in the original table.
You could use an UPDATE statement to add this new property to your json blob, if the json is regular, i.e. there's no blank after the last property and the } has got a fixed position in the next line. Building on your example and assuming \n as end of line you could do it like that:
UPDATE example
SET json = REPLACE(
json,
'"\n}',
'",\n "property3": "some value"\n}');
Demo(http://sqlfiddle.com/#!2/db972/1)
A more robust approach would be by the suggestions of Marcus Adams:
UPDATE example
SET json =
CONCAT(
TRIM(
TRAILING FROM TRIM(
TRAILING '\n' FROM TRIM(
TRAILING FROM SUBSTRING_INDEX(json, '}', 1)
)
)
),
',\n "property3": "some value"\n}'
);
This will work independently of trailing spaces after the last property and leading spaces before the }, but it's still relying on the \n as end of line.
Note:
Such statements are usually much faster than row by row updating with a script.
It depends on use case.
If this is a one time task, it would be MUCH better to run your script from the shell and not from browser to avoid web server and browser timeouts.
php -f my_update_script.php
If you cannot run script from the shell for whatever reason you can try to fool the browser and web server as follows:
set_time_limit(3600*2); // two hours should be enougth?
// turn off output buffering
while (ob_end_flush());
ob_implicit_flush();
// Your mysql fetch..update loop here
// begin loop
echo 'Something useful every iteration to let them know your script is alive :)';
// end loop
However this approach may fail if there is caching reverse proxy in front of your web server.
MariaDb has native support for JSON format (since version 10), you may consider to switch to MariaDb.
I've recently thrown together a basic PHP webpage that lists information pulled from an MySQL table and displays it in various sorts. I'm wanting to allow the user to add a new item to the table, edit an item in the list and delete an item in the list without refreshing the page (Ajax).
This currently goes;
To add/edit an article you click on a link which prompts the popover ajax form, and fills it's contents (if editing) by performing the function setEdit(comment) as below;
<a class="popup-button" title="<?php echo $row['comment']; ?>" onclick="setEdit('<?php if($row['comment']){ echo $row['comment']; } else { echo "Enter comment here..."; } ?>');"><?php echo $row['listitem']; ?></a>
The setEdit() comment is as follows;
function setEdit(editcomment)
{
if(editcomment){ document.getElementById('help-us-comment').value=editcomment; }
}
Which is then, after submitting the ajax form, handled by the following php code;
if(isset($_POST['comment_text']))
$comment=$_POST['comment_text'];
$sql = "INSERT INTO table SET
comment='$comment'";
Problem: I'm having constant issues trying to get the database contents through 1, 2, 3 without falling over at a new line, single or double quote. I've tried endless combinations of replacing tags, htmlspecialchars and nl2br with no half successes - where it's got to the point that it's so convoluted and encoded/decoded now that I'm assuming that there is a far simpler and obvious way that I'm missing.
The main problem happens when trying to load the data into the form, typically having either the form fall over and refuse to populate at all (typically by the a link becoming broken by the data extracted i.e. single quote or new line) or the form being populated with special characters instead of plain text to edit.
I've tried to go into as much detail as possible, but if any more is needed I'm happy to provide. Also apologies if this is an obvious fix/mistake, and I'm being an idiot.
You have two problems here: storing and displaying.
To display you should look in to htmlentities that makes it safe HTML (it does all the quotes replacing, html encoding, etc. for you) so that your string to be safe to be displayed as plain text, or as inputs' values.
To store the data, you should sanitize your queries. You could use mysqli and bind parameters, or use mysql_real_escape_string to escape your input manually.
Otherwise, say hi to Bobby Tables ;)
I want to create a page with 2 independent columns. If the text does not fit in one colum on one page it should be continued on the next page with the same column setup.
I tried using setColumnsArray and selectColumn the problem with this is, that if the first column is full it continues on the next column instead on the next page.
It there a posibility to achive this?
Thank You
See Sample10 which is doing exactly what you are asking for:
PHP Source code: http://www.tcpdf.org/examples/example_010.phps
Final PDF: http://www.tcpdf.org/examples/example_010.pdf
Sample7 might help too but column spreads over multiple pages:
PHP Source code: http://www.tcpdf.org/examples/example_007.phps
Final PDF: http://www.tcpdf.org/examples/example_007.pdf
I solved the problem now without writing everything in html.
I used to following aproache:
Save the top of the columns with getY and getPage.
Write the first column
Use setY and setPage to go back to the top of the second column
Use setX to move the seconds column on the right side.
Using the following hack to get around the problem with different page borders on right and left pages on the second column:
if ($curPage<>$pdf->getPage())
{
$curPage=$pdf->getPage();
if (($curPage % 2)==1)
{
$xPos+=15;
}
else
{
$xPos-=15;
}
}
$pdf->SetX($xPos);
I have a weird question. I want to create script in javascript (or PHP if I have to, I'm just more comfortable in javascript) that reads through a table until it finds specific text (know how to do that) and then returns the text three cells to the right.
To be specific, I want a script that finds a row for a specific printer on this site and returns the printer's status. I know how to select unique text, but not so much about nonunique text.
Try this
$('.epi-dataTable tr:gt(0) td:first-child:contains("printerName")')
.closest('tr').find('td:eq(4)').text();
var printerName = 'yourname',
status = $(':contains(' + printerName + ')').siblings().eq(2).text();
If I understood your question correctly, this is how you could do it using jQuery:
$("td").filter(function() {
return $(this).text() === yourSeachText;
}).next().next().next().text();
Clarifying: the filter function will select only the column whose text equals your search text, and each call to next will return the column's next sibling - another td. Three calls later, you have the column you want, so you can get its text.
Update: you might also be interested in this question, if the site you're querying is not in the same domain as your script. If it is, you can simply load its contents to a div before querying it:
$("#placeholder").load("http://clusters.andrew.cmu.edu/printerstats/", function() {
// The contents were loaded to #placeholder, do your query here
});
If it's not, then you'll have to load that html data somehow, and according to an anwser to that question, your best route is really to do it in PHP (or at least use it to echo the other site's contents to your own).