[php] insert echo into the specific html element like div which has an id or class

I have this code.

<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
<?php

$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("juliver", $con);

$result = mysql_query("SELECT * FROM hi");

while($row = mysql_fetch_array($result))
{

echo '<img src="'.$row['name'].'" />';  
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}

mysql_close($con);

?>
</body>
</html>

the above code works.

now, I want to insert this

echo '<img src="'.$row['name'].'" />'; 
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";

into the specified div or other element in the html, example, i will insert this

echo '<img src="'.$row['name'].'" />';

into the html element .

I dont know how to do this, please help me. Thanks

Juliver

This question is related to php javascript jquery

The answer is


You can write the php code in another file and include it in the proper place where you want it.

AJAX is also used to display HTML content that is formed by PHP into a specified HTML tag.

Using jQuery:

$.ajax({url: "test.php"}).done(function( html ) {
    $("#results").append(html);
});

Above code will execute test.php and result will be displayed in the element with id results.


Well from your code its clear that $row['name'] is the location of the image on the file, try including the div tag like this

echo '<div>' .$row['name']. '</div>' ;

and do the same for others, let me know if it works because you said that one snippet of your code is giving the desired result so try this and if the div has some class specifier then do this

echo '<div class="whatever_it_is">' . $row['name'] . '</div'> ;

if yo want to place in an div like i have same work and i do it like

<div id="content>
<?php
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';  
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
?>
</div>

There is no way that you can do it in PHP when HTML is already generated. What you can do is to use JavaScript or jQuery:

document.getElementById('//ID//').innerHTML="HTML CODE";

If you have to do it when your URI changes you can get the URI and then split it and then insert the HTML in script dynamically:

var url = document.URL;
// to get url and then use split() to check the parameter

I use this or similar code to inject PHP messages into a fixed DIV positioned in front of other elements (z-index: 9999) just for convenience at the development stage.

Each PHP message passes into my 'custom_message()' function and is further conveyed into the innard of preformatted DIV created by echoed JS.

There can be as many as it gets, all put inside that fixed DIV, one under the other.

<style>
    #php_messages {
        position: fixed;
        left: 0;
        top: 0;
        z-index: 9999;
    }
    .php_message {
        background-color: #333;
        border: red solid 1px;
        color: white;
        font-family: "Courier New", Courier, monospace;
        margin: 1em;
        padding: 1em;
    }
</style>

<div id="php_messages"></div>

<?php
    function custom_message($output) {
        echo
            '
                <script>
                    var
                        el = document.createElement("DIV");
                    el.classList.add("php_message");
                    el.innerHTML = \''.$output.'\';
                    document.getElementById("php_messages").appendChild(el);
                </script>
            ';
    }
?>

there is no way to specifically target an element with php, you can either embed the php code between a div tag or use jquery which would be longer.


You can repeat it by fetching again the data

 while($row = mysql_fetch_assoc($result)){
 //another html element
 <div>$row['name']</div>
 <div>$row['title']</div>
 //and so on
 }

or you need to put it on the variable and call display it again on other html element

 $name = $row['name'];
 $title = $row['title']
 //and so on

then put it on the other element, but if you want to call all the data of each id, you need to do the first code


The only things I can think of are

  1. including files
  2. replacing elements within files using preg_match_all
  3. using assigned variables

I have recently been using str_replace and setting text in the HTML portion like so

{{TEXT_TO_REPLACE}}

using file_get_contents() you can grab html data and then organise it how you like.

here is a demo

myReplacementCodeFunction(){
  $text = '<img src="'.$row['name'].'" />'; 
  $text .= "<div>".$row['name']."</div>";
  $text .= "<div>".$row['title']."</div>";
  $text .= "<div>".$row['description']."</div>";
  $text .= "<div>".$row['link']."</div>";
  $text .= "<br />";
  return $text;
}

$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;

and now a demo html file:

<html>
<head>
   <style type="text/css">
      body{background:#666666;}
      div{border:1px solid red;}
   </style>
  </head>
  <body>
    {{TEXT_TO_REPLACE}}
  </body>
</html>

Have you tried this?:

    $string = '';
    while($row = mysql_fetch_array($result))
    {
    //this will combine all the results into one string
    $string .= '<img src="'.$row['name'].'" />
                <div>'.$row['name'].'</div>
                <div>'.$row['title'].'</div>
                <div>'.$row['description'].'</div>
                <div>'.$row['link'].'</div><br />';

    //or this will add the individual result in an array
 /*
     $yourHtml[] = $row;
*/
    }

then you echo the $tring to the place you want it to be

<div id="place_here">
   <?php echo $string; ?>
   <?php 
     //or
    /*
      echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
    */
    ?>
</div>

You have to put div with single quotation around it. ' ' the Div must be in the middle of single quotation . i'm gonna clear it with one example :

<?php
        echo '<div id="output">'."Identify".'<br>'.'<br>';
        echo 'Welcome '."$name";
        echo "<br>";
        echo 'Web Mail: '."$email";
        echo "<br>";
        echo 'Department of '."$dep";
        echo "<br>";
        echo "$maj";
        '</div>'
?>

hope be useful.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?