system/article.php
<?php
$sql = "SELECT articleTitle, articleSummary, articleContent FROM articles";
$result = $dbconnect->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["articleTitle"];
echo $row["articleSummary"];
echo $row["articleContent"];
}
} else {
echo "0 results";
}
include 'template/homepage.php';
retrieves articles from the article table.
I have included the homepage.php which is supposed to act as a template.
template/homepage.php
<?php include 'template/common/header.php'; ?>
<h1>Article Title here</h1>
<p>articleSummary</p>
<?php include 'template/common/footer.php'; ?>
How do I now pass the retrieved data to the homepage.php to display it on the browser ?
Edit
smarber pointed me to
In the first file:
global $variable;
$variable = "apple";
include('second.php');
In the second file:
echo $variable;
which works. But how do I implement the same with my problem up top?
You may do that via GET, Session or Post; But why don't you simply and efficiently define a function and pass those variables to it, just for example:
function displayArticle($title, $summary, $content) {
displayHeader(); // maybe some concepts you've used in template/common/header.php
echo "<h1>$title</h1><p>$summary</p><div>$content</div>";
displayFooter(); // again, what you've provided in footer.php
}
Well then, you may do the following:
change the template/homepage.php file to:
<?php
include 'template/common/header.php';
echo "<h1>$articleName</h1>";
echo "<p>$articleSummary</p>";
include 'template/common/footer.php';
?>
and change the system/article.php to:
<?php
global $articleName;
global $articleSummary;
global $articleContents;
$sql = "SELECT articleTitle, articleSummary, articleContent FROM articles";
$result = $dbconnect->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$articleName = $row["articleTitle"];
$articleSummary = $row["articleSummary"];
$articleContents = $row["articleContent"];
include 'template/homepage.php';
}
} else {
echo "0 results";
}
However, It's so better to create a cleaner and more reusable code using some facilities you have in the programming language, like using functions and classes :)
Related
I am new to PHP function. I think following problem can be solved using function. Here I am able to store html form data in database which is passed from ajax using following code. But I am little bit confused where to implement if condition. If Data has been submitted, I want to stop data replication.
My working php code
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
Now, I want to include above code in following else condition.
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
// insert...
}
}
When I try to merge code, I can't handle. Please help me
You have pretty much everything, you just need to wrap it in a function like this:
function insert() {
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
}
And then you call it like this:
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
insert();
}
}
I'm currently making a webpage which is meant to show all it's content from the database. So I made an SQL command which selects the data needed for only 1 particular field on the webpage.
Is it possible to make the SQL command so that it get's all the content for the page at once and that ill still be able to display it separately?
If so, how? Thanks
function dbGet() {
global $conn;
global $return;
$sql = SELECT * FROM testTable;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$return = $row["text"];
return $return;
}
}
else {
echo "0 results";
}
// $conn->close();
}
You can use in this way through which you can identify records has been there or not.
function dbGet() {
global $conn;
// I am not sure what is the datatype of $return here.
// if it's having a predefined format,
// please push the records into $return instead of creating as an array,
// which will be taken care by framework if any you are using.
// global $return;
$return = array('status' => false, records => []);
$sql = "SELECT text FROM testTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$return['status'] = true;
while($row = $result->fetch_assoc()) {
$return['records'][] = $row["text"];
}
}
// $conn->close();
return json_encode($return);
}
Just echo the results inside while loop instead of returning in whatever format you wish
If you are using php, you can try something like
echo $row["text"];
Hope it helps
Let me know if you require any further help
First you should fix your return code as #AbraCadaver mentioned :
$return[] = $row["text"];
Then you can use foreach in your html :
<?php
foreach($return as $r){
echo $r['text'];
}
?>
I think a Json encoding : json_encode will work well.
Try this: http://php.net/manual/pt_BR/function.json-encode.php
can help me?
I've a site url like:
http://www.example.com/episodio/ID
ID = row number from Database.
I want to display the page title.
I've this:
.htaccess file:
RewriteEngine on
RewriteRule ^episodio/(\w+)/?$ episodio.php?id=$1
php file:
$sql = "SELECT * FROM "episodios" WHERE serie = ".$id." AND temporada = ".$i." ORDER BY "episodio" ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row['episodio'] == 0) {
echo '<li><strong>Episodio doble:</strong> '.$row["nombre"].'<img src="http://www.example.net/img/play.png" class="img-play"></li>';
}else{
echo '<li><strong>Episodio '.$row['episodio'].':</strong> '.$row["nombre"].'<img src="http://www.example.net/img/play.png" class="img-play"></li>';
}
?>
<?php } ?>
You're using $_GET in your ID anywhere before this code?
I mean, $_GET['id'].
Most PHP versions (since 4...) doesn't catch the var just for its name.
I'd recommend getting all your variables from the DB first, and then printing out the HTML (perhaps from a template file). We assume that $row contains more than just an ID? Perhaps an "tÃtulo del episodio", also?
if ($result->num_rows > 0) {
$episodios = array();
$x = 0;
while($row = $result->fetch_assoc()) {
$episodios[$x]['id'] = $row['id'];
if ($x == 0) {
$PageTitle = $row['title'];
}
$x++;
}
Then your template can use $PageTitle (from the first episode), and you can loop through the $episodios array to construct the links for the other episodes.
Hello and Good Morning,
I am still learning PHP and for some reason my script will not post any data in my foreach loop. Any Idea why? The emailRow Echos out fine but I am going to remove My code is below:
<?php
include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
<?php echo $emailRow['fbID']; ?>
<?php echo $emailRow['firstName']; ?>
<?php echo $emailRow['lastName']; ?>
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
?>
<table>
<?php foreach($accountUser as $emailData) { ?>
<tr><td> <?php emailData['fbID']; ?> </td><td><?php emailData['firstName']; ?></td><td><?php emailData['lastName']; ?></td></tr>
<?php } ?>
</table>
You have constructed your SQL query in $emailQuery, but never executed it. Call mysql_query(), and pass its result resource to mysql_fetch_assoc().
$emailQuery = "SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0";
$result = mysql_query($emailQuery);
if ($result)
{
while($emailRow = mysql_fetch_assoc($result, $conn))
{
$accountUser[]=$emailRow;
}
}
else // your query failed
{
// handle the failure
}
Please also be sure to protect your database from SQL injection by calling mysql_real_escape_string() on $upgradeEmail since you're receiving it from $_GET.
$upgradeEmail = mysql_real_escape_string($_GET['currEmail']);
You don't actually echo anything.
as well as not running the query.
and there are some other methods to do things, much cleaner than usual uglyPHP.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$email = mysql_real_escape_string($_GET['currEmail']);
$data = sqlArr("SELECT * FROM users WHERE emailOne='$email' AND authLevel=0");
include 'template.php';
a template
<? include 'includes/header.php' ?>
<table>
<? foreach($data as $row) { ?>
<tr>
<td><?=$row['fbID']?></td>
<td><?=$row['firstName']?></td>
<td><?=$row['lastName']?></td>
</tr>
<? } ?>
</table>
YOU HAVE A SYNTAX ERROR. You can't open a new php tag within an existing php tag. You have to close the already open tag first.
As far as getting the query to work,
First you have to fetch data before printing it or echoing it...
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
then you may write statements..
echo $emailRow['fbID']; etc. code.
Secondly you have not fired a query, just written the query statement. Use mysql_query to fire it.
Your code would be something like this..
<?php include 'includes/header.php';
$accountUser = array();
$upgradeEmail = $_GET['currEmail'];
$emailQuery = mysql_query("SELECT fbID, firstName, lastName FROM users WHERE emailOne='".$upgradeEmail."' AND authLevel=0") or die (mysql_error());
while($emailRow = mysql_fetch_assoc($emailQuery, $conn))
{
$accountUser[]=$emailRow;
}
echo $emailRow['fbID'];
echo $emailRow['firstName'];
echo $emailRow['lastName'];
print '<table>';
foreach($accountUser as $emailData) {
print '<tr><td>'$.emailData['fbID'].'</td><td>'.$emailData['firstName'].'</td><td>'.$emailData['lastName'].'</td></tr>';
}
print '</table';
?>
Feel free to use this code, modifying it to fit your needs.
Why is this not working?
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
$result = mysqli_fetch_assoc($query);
$title = mysqli_real_escape_string($connect,trim($result['title']));
$message = mysqli_real_escape_string($connect,trim($result['message']));
while(($result = mysqli_fetch_assoc($query))){
echo $title;
echo '<br/>';
echo '<br/>';
echo $message;
}
?>
where as this works -
<?php
echo $title;
?>
SORRY TO SAY, BUT NONE OF THE ANSWERS WORK. ANY OTHER IDEAS?
If your mysqli query is returning zero rows then you will never see anything printed in your while loop. If $title and $message are not set (because you would want reference them by $result['title'] & $result['message'] if that are the field names in the database) then you will only see two <br /> tags in your pages source code.
If the while loop conditional is not true then the contents of the while loop will never execute.
So if there is nothing to fetch from the query, then you won't see any output.
Does you code display anything, or skip the output entirely?
If it skips entirely, then your query has returned 0 rows.
If it outputs the <br /> s, then you need to check your variables. I could be wrong, not knowing te entire code, but generally in this case you would have something like
echo $result['title'] instead of echo $title
If $title and $message come from your mysql query then you have to access them through the $result array returned by mysqli_fetch_assoc.
echo $result['title'];
echo $result['message'];
Also if your using mysqli you'd be doing something like this:
$mysqli = new mysqli("localhost", "user", "password", "db");
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print $row['title'];
}
$result->close();
}
Try this:
<?php
$result = mysql_query($query);
while($row = mysqli_fetch_assoc($result)){
echo $title.'<br/><br/>'.$message;
}
?>
Does this work;
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
while(($result = mysqli_fetch_assoc($query))){
echo $result['title'];
echo '<br/>';
echo '<br/>';
echo $result['message'];
}
?>
Basically I've made sure that it's not picking the first result from the query & then relying on there being more results to loop through in order to print the same message repeatedly.