(This has now been resolved - thanks #ChelseaStats)
I have built a web page in PHP. users log in and upload photos and stories, and the page displays the stories and photos immediately.
The problem is that the photos that the MySQL query and PHP return from the database are being displayed all over the place. I have printed them out in an id’d div but the CSS is having no control over their positioning.
Currently the query is like this:
$q1 = "SELECT * from images ORDER BY date ASC";
and they are displayed like this...
row1 = #mysqli_query($dbc, $q1);
echo '<div id = "pictures">';
while ( $fix1 = mysqli_fetch_array($row1) ) {
echo '
<img style = "border: 1px solid black; padding: 10px;" height = "80" width = "80" src = "data:image;base64,'.$fix1['image'].'"><br>'.$fix1['image_id'].'
';}
echo '</div id = "pictures">';
What I would like to do is store all the 'while loop' programming in a variable, then print that variable out elsewhere on the HTML page away from php script so that when the database query is run, I can use the results to fill/initialize the variable (e.g. $displayPics) which will then be printed out on the html page where I want it to appear.
I realise this may be impossible and I am open to suggestions...
...or I might be willing to run a query with a limit of 20 giving results in descending date order and then assigning ‘loop-free’ PHP code to a variable which I can then print out on the page elsewhere.
Code could look something like this:
row1 = #mysqli_query($dbc, $q1);
$fix1 = mysqli_fetch_array($row1);
$displayPics = '
<img style = "border: 1px solid black; padding: 10px;" height = "40" width = "40" src = "data:image;base64,\'.$row1[$fix1[\'image\']].\'"><br>\'.$row1[$fix1[\'image\']].\'
';
(Above code is a shot at how I imagine it will look). (I think the img src code and html has been filtered out by the forum possibly).
But maybe this code will be repeated 20x in the variable with row number changing for each subsequent repetition perhaps?
(I basically want better control over the positioning of the pics coming back from the database).
in a foreach you can assign to a variable like this
$bob = ''; // set it
foreach($row as $image) {
// append to it
$bob .= '<div id=""><img src="" /></div>'.PHP_EOL;
}
print $bob;
similar would work for you.
if you use Bootstrap- you can assign a display class as it is rendered. The following will display each image as follows (4 across on a medium to large viewport, 3 across on a small viewport, and two across on a mobile sized viewport). Also note the use of figcaption to provide the caption on each image.
row1 = #mysqli_query($dbc, $q1);
while ( $fix1 = mysqli_fetch_array($row1) ) {
echo "<div class='col-md-3 col-sm-4 col-xs-6'>
<figure>
<img style = 'border: 1px solid black; padding: 10px;' height = '80' width = '80' src = 'data:image;base64,".$fix1['image']."'/>
<figcaption>".$fix1['image_id']."</figcaption>
</figure>
</div>
";}
Simply write a function that returns all of the rows into an array of assoc arrays and loop through them when you need them elsewhere in the code and use conditional tests on the rows to have better control over where they go!
function getImages(){
$imgs = array();
while(($next = mysqli_fetch_assoc(...)){
array_push($imgs, $next);
}
return $imgs; //array of assoc arrays
}
Related
I'm trying to insert a div into a HTML page using a for loop and the appendChild method in PHP. The issue I'm running into is that the first div always ends up stuck inside the second div, which always ends up stuck in the third div and so on and so forth. So how do I end the div at the end of the for loop?
///The PHP Side
// Create an insertion point for the Projects element
$projectInsert = $doc->getElementById("projects");
// Create a project Box
for ($x = $row_cnt; $x > 0; $x--) {
$sql2 = "SELECT * FROM `$prjct` WHERE id=$x";
$result2 = mysqli_query($db,$sql2);
$row2 = mysqli_fetch_array($result2,MYSQLI_ASSOC);
//Insert a project Box
$projectBox = $doc->createElement('div');
$projectBox->setAttribute("class","projectBox");
$project_element_title = $doc->createElement('p', $row2["title"]);
$project_element_description = $doc->createElement('p', $row2["description"]);
$projectInsert->appendChild($projectBox);
$projectInsert->appendChild($project_element_title);
$projectInsert->appendChild($project_element_description);
}
//Here's where it's inserting in the HTML
<div class="projectBar" id="projectsBar">
<h4 style="height: 30%; width: 100%; margin: auto;">Projects</h4>
<p id="projects"></p>
</div>
Here's photos of what's happening vs what I want to happen
https://docs.google.com/presentation/d/1OgthPueXHzGXyUi6L3DmgWTtOr6gHpfj8LgGh5OG85Y/edit?usp=sharing
Since I'm new I can't embed images.
Thanks for any and all help!
Instead of appending childs($project_element_title and $project_element_description) to parent($projectBox) you are appending it to super-parent($projectInsert), that's the problem.
So change:
$projectInsert->appendChild($project_element_title);
$projectInsert->appendChild($project_element_description);
To
$projectBox->appendChild($project_element_title);
$projectBox->appendChild($project_element_description);
so basicaly my conundrum is folowing:
I have a database like this:
Word | imgUrl | imgSize
volvo | C:\Users\..| 15
And I have an array like this:
$cars = array("Volvo", "BMW", "Toyota");
I need PHP to compare what in the array with whats in the database column Word , then retrieve a corresponding value of imgURL for the column value and store it in a variable $img.
Then I have this functionality prepared to run the rest of my program:
$size = 100;
$lines = file_get_contents(basename($_FILES["fileToUpload"]["name"]), FILE_USE_INCLUDE_PATH);
$words = explode(" ", $lines);
$words = array_splice($words, 0, count($words));
$img = Database entry
foreach ($words as $x => $word) {
print '<div class="result" style="position: relative; float: left;
width:' . $size . 'px; margin: 5px; height:' . $size . 'px;
background-image:url('. $img .'); background-size: 100% 100%;">
<a id="word' . $x . '">' . $words[$x] . '</a></div>';
}
As you can see, I am trying to put each word of an array into a separate <div> and then display it. All works well, I just need to show the corresponding img to the word as the background of the <div>
Anyone has any idea ?
Any and all suggestions appreciated!
Cheers
You can do it without database.
Put all images to one directory(for example "Words")
Name all images corresponding to word they represent
(for example Volvo.png,BMW.png)
Go thought array and set images paths
Code sample
for($x=0;$x<Count($x);$x++)
{
echo'<div class="result" style="background-image:url("https://website.com/Words/'.$words[$x].'.png");background-size: 100% 100%;"><a id="word'. $x .'">'. $words[$x] .'</a></div>';
}
Notes
It is better solution, because don't need connect to database and will generate the page a bit faster.
Its downside is a space requirements to store all images.
Not knowing the type of database you are using, I assume mysql. This code should suffice:
// IP username password database
$mysqli = new mysqli('127.0.0.1', 'your_user', 'your_pass', 'sakila');
$sql = "select imUrl from tableName where word = '".$cars[0]."'";
$result = $mysqli->query($sql));
$car_img = $result->fetch_assoc();
//access image using $car_img['imgUrl'];
Hope that helps. If you have multiple images you can through a loop around this and run it as often as you want, provided you store the $car_img somewhere so it is not overwritten.
<?php
$con = mysqli_connect("localhost","root","","shady");
$query = "SELECT * fROM hall1 ";
$result = mysqli_query($con,$query) or die(mysqli_error());
echo "<form action='food.php' method='post'>";
echo "<table >";
$size = 0;
while($row = mysqli_fetch_array($result))
{
$imagewidth=200;
if($size > 900)
{
echo"<tr>";
}
echo'<td width='.$td3=100 .'px > </td>' ;
echo'<td width='.$td1=200 .'px> <label><input type="radio" name="radii" value='.$row[1].' checked> <img src="'.$row['image'].'" width="200" height="200" style="margin-top:10px;"> </label></td>' ;
echo"<td width=".$td2=200 ."px> Name  : " .$row[1] ."<br> Size     : ".$row[2] ."Person <br> Price    : ".$row[3] ." SDG <br> See More </td>";
$size+= $imagewidth+$td1+$td2+$td3;
if($size > 900)
{
echo"<tr>";
}
}
echo"</table>";
echo "<BR><BR><BR><CENTER><input type='submit' name='radiii' value='next' width='200PX' height='200PX' ></a> </CENTER></b>";
echo "</form>";
}
?>
There are many problems with your code:
It's unclear what the variable size does. I'm willing to bet it's unnecessary
You are using deprecated code. The width attribute on HTML elements is no longer supported, and if you insist on using it, you should only enter the width in pixels without the px like so: <td width="200">. The <center> tag is also deprecated.
Your <label> tag is pretty much useless. What are you trying to achieve with it?
It's a bad practice to set the widths on all rows, just set the widths on the first row's cells. Even better, do not use any style directly on the HTML tags and using CSS rules instead.
Lastly, i believe it would be much more readable code to NOT echo HTML and instead use the following approach to "plug in" your variables from PHP into HTML code :
<? $a = "Some variable"; $b = 123; $c = "http://example.com/img/1.png"; ?>
<p><strong>My variable a: <?=$a?></p>
<p><strong>My variable b: <?=$b?></p>
<p><strong>My img: <img src="<?=$c?>"></p>
In short, wrap your PHP logic in <? and ?> (be sure to have short_open_tag = On in your PHP settings or you'll need to use the alternative opening tag <?php like you did.
The write plain old HTML without all the echo. Whenever you want to echo something you simply write a new PHP opening tag like so :
<? echo $a ?>
OR, the shorthand version
<?=$a?>
Now your real problem is about designing the page. And i think you are starting in the wrong order. I would suggest you
1- Build a design that works using some IDE like Adobe Dreamweaver or a freeware alternative. With that tool, make the design for 1 item (1 iteration of your while loop).
The next step is to see how you're gonna repeat it. You seem to want a Horizontal list that wraps around lines at a certain width. One way you would do that is that you would wrap all the list items with a div element for which you will set a fixed width. And inside you will have the code you have for each item repeated for all items. If your outer div has a width of 900px and each element consumes 300px in width and you have 9 items, you would have a 3x3 grid.
Here is a summary code of what i explained. In your PHP file you would have:
<div class="grid">
<? while($row = .... ){ ?>
<div class="item">
<!-- The code for the image, label and whatever information you want to have for each item -->
</div>
<? } ?>
</div>
And a CSS file which you would link in your PHP file, containing:
.grid {
width: 900px;
}
.item {
width: 300px;
}
If the information your are displaying come from user input you should sanitize it and have some sort of logic that breaks long text, either with CSS or PHP.
In short, you seem to be doing all the math in PHP so that you jump into a new line once the total width exceeds your desired grid width. This is a design issue and not a logic / programming issue. Therefore you should tackle this with CSS and not PHP.
I strongly suggest you either follow a video tutorial (there are plenty online) or read some documentations on HTML, CSS, JavaScript, PHP and MySQL in that order.
Here is a link to get you started: Mozilla Developer Network
hi i wonder if anyone can help, not entirely sure this is possible but i have a div container called <div class="scroll">
inside div scroll is a sql query that echoes comments posted by users from the database. the div scroll is set to a width of 600px and so the comments will be arranged in this div left to right, theres two comment boxes on each line, each comment box is just under 300px each as to align next to each other.
the comments are listed like so:
<div class="scroll">
comment 1 | comment 2
comment 3 | comment 4
comment 5 | comment 6
</div>
the comments are encased in the div "comment_box"
now what i have done is put a background image to the div "comment_box" this image is a pointer arrow that points to the left and is positioned on the left hand side of the div, but i also want to have a second background image for the comment boxes that align on the right, so in this instance comments 2, 4 and 6 will have a different background image/an arrow that points to the right on the right hand side of the div.
is this possible?
thanks
comment box{
.wall_post_case_branch {
background-image:url(../img/effects/arrow_left.png);
background-repeat:no-repeat;
background-position: center;
height:90px;
width:290px;
position:relative;
border:#ccc 1px solid;
}
mysql:
<?php
if(mysql_num_rows($wallposts_set) > 0) {
while ($posts = mysql_fetch_array($wallposts_set)) {
$age = days_from_date($posts['date_added']);
?>
<div class="comment_box">
<?php echo "{$posts['content']}"; ?>
</div>
You can do it as below.
<?php
$i = 0;
while ($posts = mysql_fetch_array($wallposts_set))
{
$class = ' odd';
if ($i++ % 2 == 0)
{
$class = ' even';
}
echo '<div class="comment_box'.$class.'">';
}
?>
and in css
.odd { background-image:imageone.jpg; }
.even{ background-image:imagesecond.jpg; }
I would right before the while loop make the variable $i = 0;.
It would use that to define what background color it should use.
Then in the while loop I would use this code:
while ($posts = mysql_fetch_array($wallposts_set)) {
$i++;
$age = days_from_date($posts['date_added']);
echo "<div class=\"comment_box_$i\">
$posts['content']}
</div>";
if ($i == 2)
$i = 0;
}
Then the boxes will have 2 difference classes, the one of the left will have the class="comment_box_1" while the right box will have class="comment_box_2".
Then you can create your CSS for the difference boxes.
Enjoy
You can also do this simply with CSS by using:
:nth-child(even)
:nth-child(odd)
The fiddle illustrates with background colors instead of images.
http://jsfiddle.net/ingvi/CFMcA/
hope it helps
I have a bit of an issue...
Ive made a div, and normally, it expands to suit the height of its contents fine, however... Now i have a problem.
My content is being returned from a Sql statment, and its not expanding to suit its height, a working non dynamic version is
#commentblock {
min-height:50px;
width:90%;
margin:20px auto;
padding:10px;
border:1px solid #999;
}
My code is as follows (its in a for loop making a new div for each instance)
// Now lets query to grab the responses to this fault
$querytwo = "SELECT * FROM comments WHERE faultid=".$fid;
// execute query
$resulttwo = mysql_query($querytwo) or die ("Error in query: $querytwo. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($resulttwo) > 0) {
// print them one after another
while($row = mysql_fetch_row($resulttwo)) {
// lets make this render then
echo "<div id='commentblock'>";
echo "<div class='loggedby'>Logged By : <span>".$row[4]."</span><p class='contactno'>Entered : <span>".$row[3]."</span></p></div>";
echo "<div class='info'><span>".$row[2]."</span></div>";
echo "</div>";
}
}
// free result set memory
mysql_free_result($resulttwo);
// close connection
mysql_close($connection);
Thanks in advance :)
Got it, the content was in a span which was inheriting a floating attribute. Removed the float - now its all fine :)
It might not be to do with dynamic code, but invalid HTML.
You are using:
id='commentblock'
... in a loop, which create multiple, identical IDs on the same page, which is not valid.
You should change to:
class='commentblock'
and reference you CSS as:
.commentblock
... instead of:
#commentblock