I want to grab data from a mysql database by using php. The data looks something like this:
apple 3
orange 2
banana 4
I want to take the data and put it in a html table and use css to make it look pretty, but I dont want to deal with it inside <?php ?>
After I grab the
$result = mysql_query("SELECT * FROM Table");
can I reference the result variable outside the <? php ?> tags?
No. PHP can only be done in <?php ... ?> or <?= ... ?>. Use a template engine such as Smarty if you want substitution in this manner.
in short, no you cant, it is a php variable (technically a resource in this case) so you have to parse it through the php engine, which requires the php tags
echo '<table>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr><td>'.$row['fruit'].'</td><td>'.$row['id'].'</td></tr>';
}
echo '</table>';
Short answer is no. HTML cannot deal with dynamic content.
If you want to cut down the amount of echo statements within your code you can store the html within a given variable and then make reference to it.
I find it better to do the following:
<table>
<?php foreach($result as $row): ?>
<tr>
<td><?php echo $row['fruit']?></td>
<td><?php echo $row['id']?></td>
</tr>
<?php endforeach; ?>
</table>
This provides clarity and minimizes concatenation.
Related
So I have a html table that is automatically generated after passing a query to my database. I want to create a hyperlink within my html table to a page that will pull more detailed information from a Second Table.
I was thinking of using the Tablecell creator that pulls from the First Table, and modifying so that it would encompass the table's contents with hyperlink tags. I was thinking it would look like this.
foreach(new TableRow(new AutoArrayMaker($stmt->fetchAll()) as $rowend => $row){
echo <a href = "the reusable HTML Page">;
echo $row;
echo </a>;
}
Is my idea sound from a coding standpoint?
Firstly, echo's need to be in quotation marks " So that code wouldn't fire.
There are a few ways you can output HTML. The first is using echo's:
echo "Google";
Notice how I put a back-slash before hand? This is what is known as an escape. This puts the character after into a letter depending on what it escapes to. See php docs: http://php.net/manual/en/regexp.reference.escape.php (as my description of it was poor)
The other option would be to run out of php then join back on so to speak:
<?PHP
foreach(new TableRow(new AutoArrayMaker($stmt->fetchAll()) as $rowend => $row){
?>
<a href="abc">
<?PHP echo $row; ?>
</a>
<?PHP
}
However, this is not advised.
Edit:
Also, you can make your own table very simply:
<table>
<?PHP
foreach($stmt as $row){
?>
<tr>
<td>
<a href="abc"><?PHP echo $row[id]; ?>
</td>
</tr>
<?PHP
}
?>
</table>
See https://www.w3schools.com/html/html_tables.asp for more info.
I am learning php. I see that people recommend to separate html and php or logic and markup. But in some specific occasions I am not sure how to do it. For readability and maintainability I try to put all the php in a separate file but now I have to download a title from a database and the only way I see is to put this with the rest of the html and with this html and php mixed. In this specific case, is there a more clean and organized way? is ok to put this peace of php in the "design" file? can or should I put this php code with the rest of the php?
<?php
include("../../externs/includes/connexio.php");
$result = mysqli_query($con, "SELECT * FROM myTable");
while ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$title = $row["title"];
$subtitle = $row["subtitle"];
?>
<div class="title" id="<?php echo $id; ?>"><?php echo $title; ?> </div>
<div class="subtitle"><?php echo $subtitle;?> </div>
<br>
<?php
}//end while items
?>
First of all I would recommend to read about MVC (Model-View-Controller), you can start at this Wikipedia article:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
For a simple case as the one fro you question, your solution is, in my opinion, the best. Anything else would be to add unnecessary complexity.
That being said, I will try to use that simple case and offer one possible way to separate logic from presentation with the hope that some basic concepts will become clear from it.
my_controller.php
include("../../externs/includes/connexio.php");
$result = mysqli_query($con, "SELECT * FROM myTable");
$myList = array();
while ($row = mysqli_fetch_array($result))
{
$myList[] = $row;
}
// Now load the view.
include "my_view.php";
my_view.php
<?php foreach ($myList as $row ) : ?>
<div class="title" id="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></div>
<div class="subtitle"><?php echo $row['subtitle'];?></div>
<br>
<?php endforeach; ?>
As you see, I just took your code and separated it in what would be business logic and presentation.
The idea here is that data to be presented should be generated outside the View. The View should know nothing about how the data was "generated".
In this example, the View only knows about the variable $myList containing the fields: id, title and subtitle. If you ever change databases or decide to fetch data from a file or even a Web service; you would not have to touch the View at all.
At the same time, the controller doesn't care about how the View shows the data. Regardless of the source: database, Web service, file, etc; it will always produce an array containing at least the fields expected by the View.
The next step to MVC would be to move data manipulation from controller to a model. I won't go there in detail, but this is how the controller would look like:
include "my_model.php";
$myList = fetchData();
include "my_view.php;
The fetchData() function inside the my_model.php file would basically do the same as my_controller.php above.
A very debatable and indeed debated issue is whether having any PHP code inside the View is a good practice. Some argue that other templating languages such as Smarty should be used. My opinion is that changing the syntax by adding another language doesn't change the inevitable fact that you need some logic in the View, otherwise you would be unable to introduce dynamism to your applications.
As you feel more comfortable reading PHP code, you will be able to look into the several frameworks around and see how they do it. One thing they all have in common is that they all have some logic in the presentation layer, whether it is PHP or something else.
Following are the best practices you can follow while mixing PHP with markup.
(Not a best practice)
1) if for example you have a logic on the top and you wish to generate markup, one not so good way you can do is:
<?php
$query = mysql_query("SELECT id,name FROM table");
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$name = $row['name'];
?>
<div>ID:<?php echo $id;?></div>
<div>NAME:<?php echo $name;?></div>
<?php
}
?>
In the above code you have to keep track of the ending curly brace, if your application is complex it can create a problem especially in more then one level of iteration.
2) Good way to do is to make use of PHP tags such as
<?php if(count($array)):?>
<?php foreach($array as $result):?>
<div><?php echo result;?></div>
<?php endforeach;?>
<?php else:?>
<div>NO results found</div>
<?php endif;?>
Your code has no presentation issues but if it is a complex application then you need to follow best practices.
<?php
$array = array();
$query = mysql_query("SELECT id,name FROM table");
while($row = mysql_fetch_assoc($query)):
$array[] = $row;
endwhile;
?>
Outside of PHP tag check the count of $array, if there is count then generate markup.
<?php if(count($array)):?>
<?php foreach($array as $result):?>
<div>ID<?php echo result['id'];?></div>
<div>ID<?php echo result['name'];?></div>
<?php endforeach;?>
<?php else:?>
<div>NO results found</div>
<?php endif;?>
Using this kind of formatting you can achieve pleasing results. Try to separate or avoid mixing too much PHP with markup. If you want your presentation logic to be separated from business logic then I recommend you to use MVC model as it increases readability and maintainability.
I am a beginner and somehow made to get the query (php & Mysql) I want and using echo i got the output as few lines without difficulty. But now I want the output inside the cell of a table. I tried something like this:
This does not work:
<tr>
<th>subject</th>
<th>grade</th>
</tr>";
echo "<tr>";
echo "<td>".$Row['name1']."</td>;
echo "<td>".$Row['subject1'].</td>";
echo "</tr>";
echo "</table>";
Whereas this work:
echo $line['name1']."<tr></td>"."";
echo $line['subject1']."<tr></td>"."";
The echo $line statement echoes the value of name1 and subject1 without any difficulty. but the echo Row is not showing the output. As my data has only one row I dont have to use any loop. I actually want two fields in first row (name1 and subject1) and then in next row the fields of name2 and subject2 and till name7, subject7. It looks like the format inside the table is wrong. Could someone help me plz?
First of all replace
echo "<td>".$Row['name1']."</td>;
with
echo "<td>".$Row['name1']."</td>";
you are missing (") at the end before (;)
Updated with the missing table tag. Try this
<?php
echo '<table>';
echo '<tr>';
echo '<th>subject</th>';
echo '<th>grade</th>';
echo '</tr>';
echo "<tr>";
echo "<td>".$Row['name1']."</td>";
echo "<td>".$Row['subject1']."</td>";
echo "</tr>";
echo "</table>";
?>
Just to expand the current answers, I'd suggest you use a single echo and concatenate the strings or even better, just use one single string and concatenate only the necessary variables:
<?php
echo '
<table>
<tr>
<th>subject</th>
<th>grade</th>
</tr>
<tr>
<td>'.$Row['name1'].'</td>
<td>'.$Row['subject1'].'</td>
</tr>
</table>';
?>
This of course works better if the amount of PHP code is greater than the amount of HTML code. But if you were to write more HTML than PHP, it'd make more sense to just open and close <?php?> tags and echoing the variable you want.
I used an answer instead of a comment for the sake of the example. Feel free to try this approach when you are dealing with several html elements and need to insert your values within them.
So I got the following: I'm creating dynamic pages (based on the page ID (obtained through $_GET)). My page consists of a $_get check (the html may only be shown if a $_GET variable is set) and the echo'ing of a page with html tags + php variables. Things like:
<table>
<tr>
<td>Name:</td>
<td>myFunction('foo');</td>
</tr>
</table>
etc etc etc.
I include this code above myincludedfile.php into my main file with functions include and isset($_get) .
echo include 'myincludedfile.php';
This, however, not seems to work. Altough the html gets shown, the variables and functions remain text and don't get executed.
Can anyone help me out?
Change it like this:
<table>
<tr>
<td>Name:</td>
<td><?=myFunction('foo');?></td>
</tr>
</table>
That way you are actually opening a small PHP block in the template. <?= is a shorthand notation for <?php echo, although it depends on your server configuration if the shorthand is enabled.
If the function doesn't return a value, but echos it instead, you can leave out the = as well and just execute the function like this: <? myFunction('foo'); ?> or the long notation: <?php myFunction('foo'); ?>.
In general, you don't need <?php at the start of your file. It's just that everything inside <?php .. ?> tags is executed as php and the rest is considered static output.
B.t.w. you don't need to use echo when you include a file.
Here is another alternative
$myfunction = myFunction('foo');
echo <<<CODE
<table>
<tr>
<td>Name:</td>
<td>$myFunction</td>
</tr>
</table>
CODE;
include 'myincludedfile.php';
This is called the heardoc syntax http://php.net/manual/en/language.types.string.php#example-75
You will have to include the file like this:
include 'myincludedfile.php';
What you are doing, is echo'ing the php file
Look:
<?php
$html="<h1>Hello</h1>";
function hello()
{
echo "<h1>Hello</h1>";
}
function hello2()
{
?>
<h1>Hello</h1>
<?php
}
?>
All these does the same thing.
to use them, you can do the following:
<?php
hello(); // Hello
hello2(); // Hello
echo $html; // Hello
?>
I don't think i get what you need, but try to be more specefic.
<?php
for($i=0;$i<=100;$i++)
{
?> // why this
<tr>
<td> <?php echo $i; ?></td>
<td><?php echo "tên sách $i"; ?></td>
<td><?php echo "noi dung sach $i";?></td>
</tr>
<?php
}
?>
So that is the scenario I'm looking to understand. Thanks
The <?php opens a php script sequence so it is saying that inside this is php code. ?> closes that sequence and says that I am not longer using php code.
In your case the php opens up and starts a for loop. Inside of the for loop a table is made but it is done using html not php. Then in each table piece, php is being used to echo (write something to the screen) some content into the table. Then finally at the end the php for loop must be finished with a closed bracket. I hope that makes sense.
The meaning of that syntax, is essentially telling the server to stop processing PHP. What follows in the page, is HTML code. That is <?php tells the server process this as PHP script and the ?> says stop processing PHP script.
Normally, you'll not see HTML outputted in this manner, but instead using PHP's echo to write the HTML
<?php
for($i=0;$i<=100;$i++)
{
echo "
<tr>
<td>{$i}</td>
<td>\"tên sách {$i}\"</td>
<td>\"noi dung sach {$i}\"</td>
</tr>
";
}
?>
?> is the end tag of PHP much like </td> is an end tag of a table cell.
The PHP parser lets you enable and disable parsing by including the PHP start and end tags <?php and ?> in your document. These two samples have the same output:
One
-------------------
echo '<td>' . $foo . '</td>';
Two
-------------------
?>
<td><?php echo $foo; ?></td>
<?php
As far as which is easier to read, well, that's a matter of preference I suppose.
See also: the shortcut tag <?= for echoing a value.
You can come in and out of php execution any time you like. If text is not between php tags, it will be output rather than executed.
<?php // start executing
if($test){ ?> <!-- start a php if statement -->
<p>This will only be output if the php test is true</p>
<?php } ?> <!-- don't forget to close the if statement -->
<p>This will always be output</p>
PHP allows you to min PHP code and HTML markup in the same file, so it needs a way to tell them apart.
If you don't enclose your PHP code between <?php and ?>, it won't be processed, and will be output as HTML.
You should read a minimum of documentation before start a project (and ask basic questions).
First part (l.1 to 4) is PHP code, here you start a for loop.
Second part (l.5 to 9) is HTML code, which is include in the loop.
Third and last part is here to close the loop.
You can do the same with :
<?php
for($i=0;$i<=100;$i++)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>tên sách".$i."</td>";
echo "<td>noi dung sach".$i."</td>";
echo "</tr>";
}
?>
This is a way to embed the HTML code without having to use the php print or echo function. using
?>
Another way to get at the same result would be this:
";
echo " $i ";
echo " tên sách $i ";
echo " noi dung sach $i ";
echo "";
}
?>