I am learning php and made a simple application to save peoples names to a database then pull all the saved names into a list lower down on the page.
this is the code that is getting the names: echo "<div class=\"results\"> $row[Name] </div>";
I put a div with the class of results so that I could style it. At this point all I wanted to do was center the results. After styling it with css to be centered, looking at the page source each name that was echo'ed has a div around it with the class of results. They are all centered like I wanted which is good but this does not seem like the best way to do it because there will be a new div created for every new name in the database (right now there are 18 divs. Way too many!).I was hoping only one div would be created but I was obviously wrong about that.
So, is it possible to pre-create a div in the html markup with nothing in and echo the names into the div? Or do you think there would be a way to make it all output at once so it was all within the one div?
Here is the rest of the code so you get an idea of whats happening:
<?php
$connect = mysql_connect("localhost","user","0123");
if(!$connect){
die("Failed to connect: " . mysql_error());
}
if(!mysql_select_db("Test")) {
die("Failed to select database: " . mysql_error());
}
$results = mysql_query("SELECT * FROM Friends");
while($row = mysql_fetch_array($results)){
echo "<div class=\"results\"> $row[Name] </div>";
}
if ($_POST[name] !="") { $sql="INSERT INTO Friends
(name) VALUES('$_POST[name]')";
if (!mysql_query($sql,$connect))
{
die('Error: ' . mysql_error());
}
echo "<div id=\"added\"> $_POST[name] added to the database </div>";
}
else die("")
?>
Since you output the div inside your while loop, you will get a new div for each result. Just move the div outside the loop:
echo "<div class=\"results\">";
while($row = mysql_fetch_array($results)){
echo $row['Name'];
}
echo "</div>";
Note that you should always quote your keys. Use $row['Name'] instead of $row[Name] (obviously not if Name is a defined constant).
i think it's better to have some variable to store the output:
$out .= "<div class=\"results\">";
while($row = mysql_fetch_array($results)){
$out .= $row[Name]."<br />";
}
$out .= "</div>";
echo $out;
Don't let php output html tags. It looks bad in code and your editor will not recognise it as html and make a big mess in colouring it. Generally I would advise to do all your php processing first and then make the HTML with pieces of php output in it. Something like this:
Note that I replaced your div with an ul, as your list of persons seems better suited as an ul than a div. Obviously you can use any tag you'd like in the HTML
<?php
// do all php stuff here
$persons = /* get collection from database here */
?>
<html>
<head>
</head>
<body>
<ul id="ListOfPersons">
<? foreach ($persons as $person): ?>
<li>
<?= $person["Name"] ?>
</li>
<? endforeach ?>
</ul>
</body>
</html>
You can separate the div creation from the results echoing :
echo '<div class="results">';
while($row = mysql_fetch_array($results)){
echo $row['Name'].'<br/>';
}
echo '</div>';
and if you don't want the div if there are no results (no friends) you can use mysql_num_rows
Related
So I've written some PHP/SQL code and that side of things works. When the code retrives a new article however, I want it to also create a div called content, for which I have created a CSS class. I was reccomended to do this elsewhere as the following:
$mydiv = '<div name="content">';
$mynew = '</div>';
if ($result->num_rows > 0) {
//Output data of each row
while($row = $result->fetch_assoc()) {
echo $mydiv . "<h1>Title: " . $row["title"] . " <br /></h1><h2>Summary: " . $row["summary"] . " <br /></h2><h5>Author: " . $row["author"] . " </div><br />" . $mynew ;
}
} else {
echo "Cannot find content.";
}
?>
Dreamweaver seems to think there's no syntax problems, but when I launch the page on my server a new div is not created, and the text/background doesn't change in accordance with the class?
Kind of new here but seems like a great community, any help would be awesome!
You might find it easier while you are still learning, to de complicate the string concatenation, so it is easier to follow.
Also you need to be careful to create well formed HTML i.e. open and close tags in the right order i.e. the <h5> tag
Also to remove some of the start and stop in the string literal building, if you wrap an array referenced variable in {} you can use it in a double quoted string just like you would a scalar variable like $title
And finally, make sure that you can see the message saying there is no data in the result set from the database by adding[temporarily] a big highlight to it.
// just a test
echo '<div style="font-size:20px; color:red">Rows to process: = ';
echo $result->num_rows;
echo '</div>';
if ($result->num_rows > 0) {
//Output data of each row
while($row = $result->fetch_assoc()) {
echo '<div name="content">';
echo "<h1>Title: {$row['title']}<br /></h1>";
echo "<h2>Summary: {$row['summary']}<br /></h2>";
echo "<h5>Author: {$row['author']} </h5><br />";
echo '<div>';
}
} else {
echo '<div style="font-size:20px; color:red">Cannot find content.</div>';
}
JSFiddle here, with unfunctionaing PHP obviously, but on the local host it pulls through the information just fine.
I am trying to append data in a loop into a specific set of tags, inside a di of a certain class.
For example, for every row in the the table, add a div with the class "card" and append "Title" into a H2, "description" into a P tag etc.
Anyone know how I could go about doing this? I'm googling but finding it hard to phrase my question right.
Div "Card" markup:
<div class="card">
<h2>Health and Wellbeing</h2>
<p>Sometimes you just did too much sitting not enough jumping go go go.</p>
</div>
PHP pull:
$sql = "SELECT title, description, count FROM relevant_topics";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<b>Title: </b>" . $row["title"]. " - Description: " . $row["description"]. " " . $row["count"]. "<br>";
}
} else {
echo "0 results";
}
You can echo the div markup into the PHP code like this:
while($row = $result->fetch_assoc()) {
echo'<div class="card">
<h2>'.$row["title"].'</h2>
<p>'.$row["description"].'
</div>';
}
Not sure where you want the Row['count'] though.
Also you might wanna use PDO instead of mysql, Since mysql is outdated: How can I prevent SQL injection in PHP?
check this
if ($result->num_rows > 0) {
// output data of each row
while($row = $result-> mysql_fetch_array()) {//if not works change mysql_fetch_array() to fetch_assoc()
echo'<div class="card"><h2>';
echo '.$row["title"].';
echo '</h2><p>';
echo '.$row["description"].';
echo '</P></div>';
}
I would like to insert masonry into a php form that retrieves images from a MySQL database. I can retrieve the images, but when I try to put in masonry, the whole thing doesn't work at all.
Here is my code
$result = mysqli_query($con,"SELECT * FROM img");
while($row = mysqli_fetch_array($result)) {
echo "<script src="/path/to/masonry.pkgd.min.js"></script>"
echo "<div id="container">"
echo "<img class='item' src='" . $row['path'] . "' />";
echo "</div>"
}
mysqli_close($con);
?>
You have 3 issues with that code:
First of all, you don't really have to include your script for every new <div>. Just include your script once in the <head> section, as follows:
<html>
<head>
<script src="/path/to/masonry" />
...
</head>
Secondly, you need to differentiate between " as a string container in your PHP code and as a character that should appear in your final HTML code. When using it as the latter, you need to escape it by adding a backslash (like so: \"), or simply replace it with an apostrophe:
$result = mysqli_query($con,"SELECT * FROM img");
while($row = mysqli_fetch_array($result)) {
echo "<div id='container'>";
echo "<img class='item' src='" . $row['path'] . "' />";
echo "</div>";
}
mysqli_close($con);
?>
And finally, as presented in the example, you forgot the semicolon terminator at the end of your lines of code inside the while loop.
I have a posts table which contains a field for the posts. Let's say I have 10 posts that i want to show in 10 divs. How should I proceed in doing that? I've managed to get the full contents using a while loop, but that only shows the full contents in one place, and I want to have individual divs (so i can use different background colors) for each individual post.
Help me out please, I hope it makes sense. Just think at the way facebook displays posts for example. Each post has it's own box. I want something similar.
Snippet of the code I have to get the posts is available here:
<?php
require_once("includes/database.php"); // Get the database connection
$get_post = "SELECT full_post FROM posts";
$show_post = mysqli_query($connection, $get_post);
if (!$show_post) {
echo "Could not load post. " . "(" . mysqli_error($connection) . ")";
}
while ($post = mysqli_fetch_assoc($show_post)) {
echo $post["full_post"] . "<br />";
}
mysqli_free_result($show_post);
?>
The easiest method of doing this is creating the divs from the while function that's showing your posts and adding CSS classes to them.
Example:
while ($post = mysqli_fetch_assoc($show_post)) {
echo '<div class="blue">';
echo $post["full_post"] . "<br />";
echo '</div>';
}
I imagine you are looping through the individual posts using the while-loop. You can start a new div every round.
while($post = mysqli_fetch_assoc($result)) {
print '<div>';
print $post->content;
print '</div>';
}
Here is my code, works fine and prints out everything I want it to. But on the end of each cell I would like a form that makes a button which will allow the user to configure the item that the row in the table describes. I want to know how I can escape out of php to use html again, I've tried double quotes but this does not work, I was wondering if anyone could explain to me how to do this.
<?php
$data = mysql_query("SELECT * FROM basestation WHERE email_address ='$email'")
or die(mysql_error());
Print "<table border = 1>";
while( $info = mysql_fetch_array( $data ) ) {
Print "<tr>";
Print "<th>Name:</th> <td>".$info['base_station_id'] . "</td>";
Print "</tr>";
Print "<tr>";
Print "<th>Serial Number:</th> <td>".$info['serial_no'] . "</td> ";
Print "</tr>";
}
Print "</table>";
?>
PHP code will only being executed between the opening <?php and the closing ?> php tags. However you are free to use multiple php sections per file.
So, you can just close the PHP section using ?> . Then after writing HTML content you can open <?php again.
Here comes a little example. It creates a couple of <a> achors from an imaginal array $links:
<?php
foreach($links as $link) { ?>
<?php echo $link['title'];?>
<?php }
Note that this mostly leads to unreadable code. But it is possible and can be used.
Also not that there is short syntax available for shorter echo syntax. But you'll have to make sure that it is enabled in your php configuration. Using the shorter syntax, may example from above could look like this:
foreach($links as $link) { ?>
<?=$link['title'];?>
<? }
You'll find a good documentation on the PHP website
You are already using the PHP delimiters <?php and ?>. Use these to switch back to HTML within the document also.
<?php
function foo(bar) {
return bar == 1 ? 'bar' : 'nobar';
}
?>
<h1>Heading with just HTML</h1>
<div class="<?php print foo(1); ?>">This is a div with a dynamic class.</div>
<?php
// and php again
?>
Just make a link to a page with the id in the url
Print "<tr>";
Print "<th>Edit:</th><td>Edit</td> ";
Print "</tr>";
Then on edit.php you can get the id ($_GET['id']) and query the database.
<?php
$data = mysql_query("SELECT * FROM basestation WHERE email_address ='$email'")
or die(mysql_error());
Print "<table border = 1>";
while( $info = mysql_fetch_array( $data ) ) {
Print "<tr>";
Print "<th>Name:</th> <td>".$info['base_station_id'] . "</td>";
Print "</tr>";
Print "<tr>";
Print "<th>Serial Number:</th> <td>".$info['serial_no'] . "</td> ";
?>
<-- form here --->
<?php
Print "</tr>";
}
Print "</table>";
?>