Link to home
Start Free TrialLog in
Avatar of doctorbill
doctorbillFlag for United Kingdom of Great Britain and Northern Ireland

asked on

php and div elements

I have been trying to get this code to arrange my images in to 2 columns across the page for the first 2 images, then a second row of 2 columns for the next 2 images and so on down the page
All I get is 2 images displayed
Any ideas please?

<style>
#myDiv {
  border: thin solid blue;
}
</style>

<script>
function myFunction() {
  document.getElementById("myDiv").style.borderColor = "red";
}
</script>

<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx^";
$dbname = "wp_zj0qw";
$search= $_POST['xxx'];

$width_xsml = 12;//Columns size for extra small screen
$width_sml = 6;
$width_med = 4;
$width_large = 3;//Column size for large screen
$col_width = 12 / $width_large;//12 column layout
$row_count = 0;//The loop counter

//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
// $sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( ( id >= 3 ) AND ( id <= 20 ) )";
$sql = "SELECT * FROM  MV0vqu9WQ_nextend2_image_storage WHERE (image LIKE '%Dream%')";
//$sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( id IN (3,4,5) )";
$result = $conn->query($sql);

if($result->num_rows > 0) {
  //output data of each row
  while($row = $result->fetch_assoc())  {
$imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);

if ($count % $width_sml == 0) {
        echo '<div class="row">';
    }
    $count++;

   echo <<< HTML
    "<div class='col-$width_sml col-sm-$width_sml col-md-$width_med col-lg-$width_large'>"<img src="{$imagePath}" ><button type="button" onclick="myFunction()">Change color of the four borders</button></div>
 HTML;

echo '</div>';
    if ($count % $width_sml == 0) {
        echo '</div>';
    }

   echo "<hr>";
  echo "Image ID : ". $row['id'];
  }
} else {
   echo "0 results";
}
$conn->close();
?>

Open in new window

Avatar of doctorbill
doctorbill
Flag of United Kingdom of Great Britain and Northern Ireland image

ASKER

Updated Code:
This update creates a new row every 2 images but I want to create 2 columns (2 images across the page) with the first 2 images, then 2 columns across the page  in a second row with 2 images and so on

<style>
#myDiv {
  border: thin solid blue;
}
</style>

<style>
    body {
        background: #0d161f;
    }
    .row {
        background: #00b9eb;
        padding: .4rem;
        margin-top: .6rem;
        text-align: center;
    }
    .a-col {
        background: #de7c8d;
        border: 3px solid transparent;
        background-clip:padding-box;
    }
</style>

<script>
function myFunction() {
  document.getElementById("myDiv").style.borderColor = "red";
}
</script>

<?php
$servername = "localhost";
$username = "wp_etws8";
$password = "42nSCFBdr4ch#B6^";
$dbname = "wp_zj0qw";
$search= $_POST['xxx'];

$width_xsml = 12;//Columns size for extra small screen
$width_sml = 2;
$width_med = 4;
$width_large = 3;//Column size for large screen
$col_width = 12 / $width_large;//12 column layout
$row_count = 0;//The loop counter

//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
// $sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( ( id >= 3 ) AND ( id <= 20 ) )";
$sql = "SELECT * FROM  MV0vqu9WQ_nextend2_image_storage WHERE (image LIKE '%Dream%')";
//$sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( id IN (3,4,5) )";
$result = $conn->query($sql);

if($result->num_rows > 0) {
  //output data of each row
  while($row = $result->fetch_assoc())  {
$imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);

if ($count % $width_sml == 0) {
        echo '<div class="row">';
    }
    $count++;
echo "<div class='col-$width_xsml col-sm-$width_sml col-md-$width_med col-lg-$width_large'>";
   echo <<< HTML
    "<div id='myDiv'>"<img src="{$imagePath}" width="200" height="400"><button type="button" onclick="myFunction()">Change color of the four borders</button></div>
 HTML;

echo '</div>';
    if ($count % $width_sml == 0) {
        echo '</div>';
    }

   echo "<hr>";
  echo "Image ID : ". $row['id'];
  }
} else {
   echo "0 results";
}
$conn->close();
?>

Open in new window

try this code

if($result->num_rows > 0) {
   //output data of each row

   while($row = $result->fetch_assoc())  {
      $imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);

      if ($count % $width_sml == 0) {
         if ($count >0) echo '</div>'
         echo '<div class="row">';
      }

      echo "<div class='col-$width_xsml col-sm-$width_sml col-md-$width_med col-lg-$width_large'>";
      echo "<div id='myDiv'>"<img src="{$imagePath}" width="200" height="400"><button type="button" onclick="myFunction()">Change color of the four borders</button></div>
      echo '</div>';

      $count++;

      echo "<hr>";
      echo "Image ID : ". $row['id'];
   }
   echo '</div>';
} else {
   echo "0 results";
}

Open in new window

I get this:
syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';'
try this on Line 13

echo "<div id='myDiv'><img src='{$imagePath}' width='200' height='400'><button type='button' onclick='myFunction()'>Change color of the four borders</button></div>"; 

Open in new window

Sorry - same problem
which Line? does it say?
I also added ";" to the Line 8...

if($result->num_rows > 0) {
   //output data of each row

   while($row = $result->fetch_assoc())  {
      $imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);

      if ($count % $width_sml == 0) {
         if ($count >0) { echo "</div>"; };
         echo '<div class="row">';
      }

      echo "<div class='col-$width_xsml col-sm-$width_sml col-md-$width_med col-lg-$width_large'>";
      echo "<div id='myDiv'><img src='{$imagePath}' width='200' height='400'><button type='button' onclick='myFunction()'>Change color of the four borders</button></div>";
      echo "</div>";

      $count++;

      echo "<hr>";
      echo "Image ID : ". $row['id'];
   }
   echo "</div>";
} else {
   echo "0 results";
}

Open in new window

It's working now but I am getting 2 rows for the first 2 images, then a break and another 2 rows with 2 images and so on.......
What I am after 2 or 3 images across the page in the first row or div
then another 3 images across the page in the second row or div
Then another 3 images across the page in the third row or div .......

This is what I am currently getting:
User generated image
We are getting there

I also don't understand how the code can be using all these classes at once:
'col-$width_xsml col-sm-$width_sml col-md-$width_med col-lg-$width_large'
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is the code I have inserted:
I get a Parse error:
ParseError thrown
syntax error, unexpected '<'
<style>
#myDiv {
  border: thin solid blue;
}
</style>

<style>
    body {
        background: #0d161f;
    }
    .row {
        background: #00b9eb;
        padding: .4rem;
        margin-top: .6rem;
        text-align: center;
    }
    .a-col {
        background: #de7c8d;
        border: 3px solid transparent;
        background-clip:padding-box;
    }
</style>

<style>
.d-flex {
  display: flex;
}
.flex-column {
  flex-direction: column;
}
.flex-wrap {
  flex-wrap: wrap;
}
.text-center {
  text-align: center;
}
.image-container > div {
  flex: 0 0 33.3333333%;
}
</style>

<script>
function myFunction() {
  document.getElementById("myDiv").style.borderColor = "red";
}
</script>

<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx^";
$dbname = "wp_zj0qw";
$search= $_POST['xxx'];

$width_xsml = 12;//Columns size for extra small screen
$width_sml = 2;
$width_med = 4;
$width_large = 3;//Column size for large screen
$col_width = 12 / $width_large;//12 column layout
$row_count = 0;//The loop counter

//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
// $sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( ( id >= 3 ) AND ( id <= 20 ) )";
$sql = "SELECT * FROM  MV0vqu9WQ_nextend2_image_storage WHERE (image LIKE '%Dream%')";
//$sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( id IN (3,4,5) )";
$result = $conn->query($sql);

if($result->num_rows > 0) {
   //output data of each row

   <div class="d-flex flex-wrap image-container">
<?php
while($row = $result->fetch_assoc()){
  $imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);
   echo <<< HTML
 <div class="d-flex flex-column">
    <div class="text-center">
      <img src="{$imagePath}">
    </div>
     <button type="button" onclick="myFunction()">Change color of the four borders</button>  
  </div>
HTML;
   }
?>
</div>
?>
$conn->close();

Open in new window


You should post a line number reference so we know where to look.

In this case your problem is probably here
if($result->num_rows > 0) {
   //output data of each row


   <div class="d-flex flex-wrap image-container"> <======= HERE
<?php

Open in new window

You have HTML in the middle of a PHP code block.

If I remove this I get the same error
Now I have taken out:
<div class="d-flex flex-wrap image-container"> on line76
Should there be a </div> on line 90

No, don't take it out - wrap it in an echo - you have to have that div. The problem was not that there was a div it was that you were not handling the output of it correctly

echo <<< HTML
  <!-- PUT THE DIV BACK HERE -->
HTML;

Open in new window

ok
The div is back:
echo <<< HTML
<div class="d-flex flex-wrap image-container">
HTML;

I am still getting this error though:

ParseError thrown

syntax error, unexpected '<'

I have cleaned up the code - got rid of code that is no longer needed:
<style>
.d-flex {
  display: flex;
}
.flex-column {
  flex-direction: column;
}
.flex-wrap {
  flex-wrap: wrap;
}
.text-center {
  text-align: center;
}
.image-container  > div {
  flex: 0 0 33.3333333%;
}
</style>

<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";
$search= $_POST['xxx'];

//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
// $sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( ( id >= 3 ) AND ( id <= 20 ) )";
$sql = "SELECT * FROM  MV0vqu9WQ_nextend2_image_storage WHERE (image LIKE '%Dream%')";
//$sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( id IN (3,4,5) )";
$result = $conn->query($sql);

if($result->num_rows > 0) {
   //output data of each row

echo <<< HTML
<div class="d-flex flex-wrap image-container">
HTML;

 <?php
while($row = $result->fetch_assoc()){
  $imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);
   echo <<< HTML
 <div class="d-flex flex-column">
         <img src="{$imagePath}">
    </div> 
</div>
HTML;
   }
?>
</div>
?>
$conn->close();

Open in new window

I guess you should delete Line 50 or 51, one is redundant...
I tried that - no difference
Hey Bill,

No points for this as Julian has already covered it, The problem you're having is jumping in and out of PHP / HTML. Your Parse Error is down to your Line 44 - you've got an opening PHP tag - <?php, but you're already inside PHP code, so that causes an error. Line 55, you've jumped back out of PHP and line 56, you have an extra closing PHP tag. You also don't have a close to your IF statement (not sure whether you've just shown part of the code or not)

Couple of tips that can help you in cases like this. First off - get your indenting sorted. When you're nesting blocks (whether HTML or PHP), it helps to correctly indent your code. You'll get immediate visual feedback. Also, in PHP, the control structures have an alternative syntax that can help when you have control blocks nested within each other. The standard format is to use curly brackets:

if (...) {
    while (...) {
        ...
    }
}

When you code is short and concise, that's fine, but as your code grows and you start dropping in and out of PHP/HTML, the alternative syntax can help make your code easier to read:

if (...):
    while (...):
        ...
    endwhile;
endif;

Have a quick look at this:

<style>
.d-flex {
  display: flex;
}
.flex-column {
  flex-direction: column;
}
.flex-wrap {
  flex-wrap: wrap;
}
.text-center {
  text-align: center;
}
.image-container  > div {
  flex: 0 0 33.3333333%;
}
</style>

<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";
$search= $_POST['xxx'];

//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);

//Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM  MV0vqu9WQ_nextend2_image_storage WHERE (image LIKE '%Dream%')";
$result = $conn->query($sql);

if($result->num_rows > 0):

    echo '<div class="d-flex flex-wrap image-container">';
    
    while($row = $result->fetch_assoc()):

        $imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);
        echo <<< HTML
            <div class="d-flex flex-column">
                <img src="{$imagePath}">
            </div> 
        HTML;

    endwhile;

    echo '</div>';

endif;

$conn->close();
?>

Open in new window

One thing to be aware of ... if you're using an older version of PHP, then the terminator for HereDoc (HTML; on line 48 above) has to start at the beginning of the line (no indentation for it). Later versions of PHP and you can indent it.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The following code is now working. I see where I went wrong - I made some typos and left out some script references from the initial code Julian sent (despite the code from Julian being very accurate and concise - as always), plus used php inside an already defined php tag
Thanks for pointing this out Chris
Just one final thing (sorry the code pasted does not have line numbers - not sure why) -
How is it the the line "echo '<div class="d-flex flex-wrap image-container">';" is accepted by php but the one in the while loop "<div class="d-flex flex-column">" has to be in the <<<HTML tag ?
Once again - sorry for my errors

<style>
.d-flex {
  display: flex;
}
.flex-column {
  flex-direction: column;
}
.flex-wrap {
  flex-wrap: wrap;
}
.text-center {
  text-align: center;
}
.image-container  > div {
  flex: 0 0 33.3333333%;
}
</style>

<?php
$servername = "localhost";
$username = "wp_etws8";
$password = "42nSCFBdr4ch#B6^";
$dbname = "wp_zj0qw";
$search= $_POST['xxx'];

//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);

//Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM  MV0vqu9WQ_nextend2_image_storage WHERE (image LIKE '%Dream%')";
$result = $conn->query($sql);

if($result->num_rows > 0):

    echo '<div class="d-flex flex-wrap image-container">';
    
    while($row = $result->fetch_assoc()):

        $imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);
        echo <<< HTML
            <div class="d-flex flex-column">
                <div class="text-center">
                <img src="{$imagePath}">
            </div> 
               </div> 
        HTML;

    endwhile;

    echo '</div>';

endif;

$conn->close();
?>

Open in new window

Hey there,

In PHP, you can echo out a one-line string:

echo "Hello Bill";

However, if your string spans mulitple lines, you can't just do:

echo "<h1>Hello Bill</h1>
<p>How are you today?</p>

That would error. In PHP, we have something called the HereDoc syntax. This allows us multilines, by telling PHP to treat everything UPTO the terminator as the string. By convention, we often use EOT (End Of Text) as the terminator, but you can use your own (HTM in your code)

echo <<<EOT
<div>
    <h1>Hello Bill</h1>
    <p>How are you today</p>
    <p>Everything upto the Terminator is considered part of the same string</p>
</div>
EOT;

Open in new window

You can also use that method for building content for variables, which is really nice when you're building complex SQL statements for example:

$sql = <<<EOT
    SELECT firstname, lastname
    FROM someTable a
    JOIN otherTable b
    ON a.id = b.id
    ORDER BY a.lastname
EOT;

$result = $db->query($sql);

Open in new window

And one last point - variables within a Heredoc will be parsed:

$name = "Bill";

echo <<<HTML
    <p>Hello $name</p>
    <p>How are you?</p>
HTML;

Open in new window

Ah ha - I don't think I got my head around the actual use of the HereDoc syntax
Got a better understanding now - I haven't used it enough up to now
Julian pointed me in the right direction on using it
Time to close off now - thanks so much all of you
Always really appreciated
I always feel so guilty when assigning points
Especially as the errors made in the above code were due to me not interpreting the code correctly, making typing errors and leaving out some important code
The FlexBox looks an awesome set of scripts for image handling
Hey Bill,

The points should really have been Julian's as he gave you the answer. I was just attempting to clarify an error in your implentation of his code.

I don't actualy know how to un-answer a question. Sorry @Julian :(
It also looks like the points I originally submitted were not the ones that were actually submitted
No idea what happened here
How do I see the points allocated?
It should show at the top, left of the question:

Me : 2100
Julian : 1200
Hain : 500
That is not what I actually selected and sent - Julian was the main contributor. That is totally incorrect. Maybe I can contact support to get things changed?
I have asked the EE Support to rectify
Thanks all