Changing a php "echoed" div attribute with php - php

I'm using PHP to echo a content stored on my database. The content is a DIV carrying any type of data.
The problem is that I don't know the ID and I have some problems with these DIVs if I try to display them more than once.
So, the idea is to modify the DIV id each time I'd like to display them.
Something like this:
<?php modify_div_id($data,"id-456"); ?>
How would I go about doing this?

This is ugly, but i think it works.
function modify_div_id( $data, $new_id ) {
return preg_replace( '/(<div[^>]+?id=)("|\')(.*?)("|\')/i', '$1$2' . $new_id . '$4', $data );
}
The best way to go is to use an XML parser to change the attribute.
Edit: the function assumes the div to already have an id attribute.
Edit #2
It seems to be working!
jwandborg#sophie:~$ cat | php -r "eval( file_get_contents('php://stdin') );"
function modify_div_id( $data, $new_id ) {
return preg_replace( '/(<div[^>]+?id=)("|\')(.*?)("|\')/i', '$1$2' . $new_id . '$4', $data );
}
echo modify_div_id('<div pajas="pajas" id="fisk">Innehåll</div>', 'nytt_id');
# Result: <div pajas="pajas" id="nytt_id">Innehåll</div>

Your question is worded kind of vague.
First off, the id attribute for HTML elements must be unique, so echoing a unique id is appropriate (you can also use a class).
If you've queried your database and received back, say, an array containing an id and the content, you can use the function as follows:
function modify_div_id($data, $id) {
echo "<div id='$id'>$data</div>";
}
Just an example.

Related

preg_replace of php code

I am writing an application that will look at a single record, obtain values from about 12 flags (0 or 1), look up those flags against a status table (in MySQL) and return a variable called $status_message which is in that table.
In this table I need to have hyperlinks (working fine) but also echo some variables, i.e.
You have no bids for {{$row->_item_name}}
or
View this item now by clicking here
Now I need item name and the other example to be translated into <?php echo $row->_item_name; ?>
I have tried a preg_replace with the following:
<?php
$find = array('/{{/', '/}}/');
$replace = array('<?php echo ', ' ?>');
echo preg_replace($find, $replace, $status_message);
?>
but this is not working.
Can anyone advise how I can get the desired result and 'echo' the variable in the MySQL field?
Had a brainwave. Much simpler,
instead of $row->_item_name I just put {{itemname}} in the string. I then use the following code:
<?php
$message_buyer = str_replace('{{itemname}}', $row->_item_name , $message_buyer);
echo $message_buyer;
?>
so no need to have <?php calls in the string at all.

using echo statement after dynamic HTML

Here's the problem, I am trying to echo a statement or an array after dynamically generated HTML, and unfortunately the thing that i want to echo goes above the HTML, is there any way to echo it after that dynamic HTML or work around?
Code:
Link 1
Link 2
if(isset($_GET["id"]) && $_GET["id"] == "do_something") {
$html = "dynamic html generate";
echo $html;
//after this im using foreach
foreach($array as $item) { echo $item . "<br />"; }
}
As I click one of these two , dynamically generated HTML shows up. Now for example I have an array:
$array = array("error1", "error2");
All the generated PHP goes above the dynamic HTML :/.
How should i fix it so that i can echo all of this array below the dynamic HTML?
Thanks
Use buffering with ob_start
ob_start();
// dynamic html code generate
$dynamic_html = ob_get_clean();
echo $dynamic_html;
// your code
echo $dynamic_html;
Sounds like you missed some closing tags (most likely </table>) in the dynamic html. Thats why the later generated echo gets displayed at the top.
Example (Note the missing closing table):
<?php
echo "<table><tr><td>TableText</td></tr>";
echo "I should be bellow the table, but going to the top.";
?>
will produce:
I should be bellow the table, but going to the top.
TableText

WordPress: Hide page element if there is no database data to fill it

Hopefully this is simple to solve. I have a few elements which pull in form data previously entered into the database, which are added to the post as custom fields. I extract this using a php query as such:
<a href="<?php echo get_post_meta($post->ID, 'societywebsite', true); ?>" target="_blank" >Website</a>
Obviously, this appears in the Loop (content.php) and will get added to any appropriate post. Sometimes, however, there won't be any data because a user chose not to enter a website into the 'societywebsite' field on a form. When this happens, there's no need for a link to 'Website' to be there, because it wouldn't go anywhere useful.
What I'd like to know is how to have an If clause that checks if the data exists and then shows the link only if it does. I don't mind javascript, but the cleaner and less 'hacky' the solution, the better, as content.php will run multiple times for search results.
Thanks so much for any help or advice you can provide.
Another way to do this, more according to the Wordpress Codex is the following...
$societywebsite = get_post_meta($post->ID, 'societywebsite', true);
if ($societywebsite != '') {
echo '<a href="' . $societywebsite . '" target="_blank" >Website</a>';
}
You can add an 'else' at the end of this for debugging purposes.
Assuming that field is a string for a url, you could do something like this.
if (strlen(get_post_meta($post->id, 'societywebsite', true)) < 1) {
echo '<a href="' . get_post_meta($post->ID, 'societywebsite', true) . '" target="_blank" >Website</a>';
}
That will very simply check if that field has a string that is more than 1 characters. If it is more than 1 characters, it will display the link. If not...it won't do anything.

Pass PHP array to Javascript via onClick using JSON

I am using PHP and MySQL to loop through products and generating HTML code that consists of an img tag with an onClick event that calls a Javascript function. I want to pass PHP variables via the onClick event to a Javascript function. I'm using jQuery and thought it would be a good idea to use PHP's json_encode() function and jQuery's jquery-json plugin.
My PHP code looks like this:
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a href=\"javascript:;\" onClick=\"changepic('" . htmlentities($onclick) . "')\">";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
As you can see my Javascript function is called changepic(). I've left out a bit of code that is irrelevant to this question (i.e. the database access code and deciding where the thumbnail image is).
My Javascript code is:
function changepic(productarray) {
var productid = $.evalJSON(productarray).productid;
var productdesc = $.evalJSON(productarray).description;
alert(productid);
}
I'm not really doing anything yet with the PHP variables that I'm passing to the Javascript array, I'm just trying to get it to work first! My ultimate aim is to use jQuery to insert the product description into a <div>
A sample product detail might look like this:
ProductID: 30c7508008ac7597619ad9b90a97b40f
Description: <p>Wide and Narrow Bands<br>
Set with Top-Quality Diamonds</p><p>
As you can see the description contains HTML code, as well as a newline after the <br> tag.
The HTML that is generated looks like this:
<img src="products/tn-30c7508008ac7597619ad9b90a97b40f.jpg" width="100" height="100">
When I run this I get a Javascript error:
Event thread: click
Uncaught exception: SyntaxError: JSON.parse: Unescaped control char in string: "<p>Wid
Error thrown at line 18, column 2 in changepic(productarray) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
var productid = $.evalJSON(productarray).productid;
called from line 1, column 0 in <anonymous function>(event) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
changepic('{"productid":"30c7508008ac7597619ad9b90a97b40f","description":"<p>Wide and Narrow Bands<br>\r\nSet with Top-Quality Diamonds<\/p>"}')
From what I can see I've done something wrong with encoding the JSON string. I've done some Googling and found some people that say no encoding is necessary (I tried that and the product description was taken as HTML and showed up in the page), others say to use addslashes() and some say htmlentities().
Do I need to do something in the Javascript function to decode it before I try to use it with evalJSON()?
I usually just do this,
var foo = <?php echo json_encode($foo); ?>;
and I don't really see how this can result in any sort of an "injection" attack as long as json_encode is doing its job.
I don't understand why you are getting into so much mess.. here is the solution and it works
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a id='test' href='' var='$onclick'>";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
Here is your jquery:
$(function(){
$("#test").click(function(){
var img = jQuery.parseJSON(($(this).attr("var")));
alert(img.description);
});
});
Now since you have the json object you can create div tag and put the variables inside or put the content on already existing div tag. I am sure you know what to do here.
Dins
I think I was over-complicating things, I didn't really need to use JSON at all.
I got this working by changing my PHP code to this:
$productid = $productsRow['ProductID']
$description = rawurlencode($productsRow['Description']);
echo "<a href=\"javascript:;\" onClick=\"changepic('$productid','$description')\">";
Then my Javascript looks like this:
function changepic(productid, description) {
description = decodeURIComponent(description);
alert(description);
}
This works fine so now I can continue and actually do something useful in the Javascript function.

Changing Text in PHP

I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.

Categories