So I am trying to pull HEADLINES.. that I have saved in a DB, they all have unique IDs.. I need a way to be able to call them but type or ID for instance.
$stmt = $con->prepare("SELECT * FROM news WHERE type = 'sports'");
$stmt->execute();
while($rfr=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="row">
<div class="col-lg-4">
<img src="<?php echo $rfr['folder'] . $rfr1['file'];?>.jpg" >
<h2><?php echo $rfr['headline'];?></h2>
<p>V.A. conducts study to determine effectiveness</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<div class="col-lg-4">
<img src="imgs/news/n4.jpg">
<h2><?php echo $rfr['headline'];?></h2>
<p>The Rev. Daniel Berrigan, a Roman Catholic priest and peace activist who was imprisoned for burning draft files in a protest against the Vietnam War, died Saturday. He was 94.</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<div class="col-lg-4">
<img src="imgs/news/n1.jpg">
<h2><?php echo $rfr['headline'];?></h2>
<p>President Barack Obama is getting one more chance to poke fun at fellow politicians, the press and himself at the annual White House Correspondents' Dinner.</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
<?php
}
?>
Every time I run this code though.. It just enters only the headline from ID 1 everytime. and it makes a ton of duplicate post..
I want it to select through all the headlines in that type.. thats why im using the WHILE()
Please try this:
$stmt = $con->prepare("SELECT * FROM news WHERE type = 'sports'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $rfr) {
?>
<div class="row">
<div class="col-lg-4">
<img src="<?php echo $rfr['folder'] . $rfr1['file'];?>.jpg" >
<h2><?php echo $rfr['headline'];?></h2>
<p>V.A. conducts study to determine effectiveness</p>
<p><a class="btn btn-primary" href="#" role="button">Read More »</a></p>
</div>
...
</div>
<?php } ?>
Why don't you just use a foreach? That way you don't have to worry about handling iterations and possible infinite loops that while loops have.
Also, I personally prefer not to make function calls and assignments in a while/foreach.. It's not that big of a deal to add 1 extra line just before the declaration. Will improve readability and make it easier to debug your code.
Related
I have facing big problem to auto count previous 6 months annoucement record in SQL put in the separate box. Is using loop to count the annoucement record? Anyone can guide me or give me an example to do it? If can, better using my code to edit and let me refer. Thanks a lot.
Below is my coding:
<?php
$sql_select = 'SELECT * FROM announcement where id = 20' ; //This I try to test id = 20 announcment to call out data
$query_select = db_conn_select($sql_select);
foreach ($query_select as $rs_select) {
$title = $rs_select['title'];
$date = $rs_select['posted_date'];
$contents = $rs_select['contents'];
}
?>
<div class="row">
<div class="col-md-12">
<div class="box box-success box-solid">
<div class="box-header with-border" style="text-align: center;" >
<h3 class="box-title" ><?php echo $title ?> (<?php echo $date ?>)</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-default btn-xs collapse-box" data-toggle="collapse" data-target="#collapseExample1" aria-expanded="false" aria-controls="collapseExample"><i class="fa fa-minus"></i></button>
</div>
</div>
<div id="collapseExample1" class="collapse" style="overflow: auto; text-align: center;">
<?php echo $contents ?>
</div>
</div>
</div>
</div>
Below is my database information (I want get the posted_date previous 6 months annoucement record to show):
My coding output show like the below:
Actually I want the output like below show auto count previous 6 months announcements put in the separate box :
There are two problems:
1) Your query will only return one record. You need to change it so it fetches a set of records from the last 6 months.
The general pattern for finding the last 6 months is easy to find online
yourdatecolumn >= CURDATE() - INTERVAL 6 MONTH
(credit to this answer specifically in this case, but there are dozens of examples available). N.B. You didn't specify, but I'm assuming your DBMS is MySQL, since that's most commonly used with PHP. If you have a different DBMS, you can find an equivalent answer online with a few seconds of searching.
2) you're ending your loop too soon. The current code is ok for one record, but will fail when there is more than one. It will loop over all the records, but then keep assigning their values the same variables, so after the loop finishes you end up with just the last record's values inside those variables. And you are not using a loop to create the HTML multiple times.
To fix that, just bring the HTML inside the loop. Here's the final version:
<?php
$sql_select = 'SELECT * FROM announcement where posted_date >= CURDATE() - INTERVAL 6 MONTH';
$query_select = db_conn_select($sql_select);
foreach ($query_select as $rs_select) {
$title = $rs_select['title'];
$date = $rs_select['posted_date'];
$contents = $rs_select['contents'];
?>
<div class="row">
<div class="col-md-12">
<div class="box box-success box-solid">
<div class="box-header with-border" style="text-align: center;">
<h3 class="box-title">
<?php echo $title ?> (
<?php echo $date ?>)</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-default btn-xs collapse-box" data-toggle="collapse" data-target="#collapseExample1" aria-expanded="false" aria-controls="collapseExample"><i class="fa fa-minus"></i></button>
</div>
</div>
<div id="collapseExample1" class="collapse" style="overflow: auto; text-align: center;">
<?php echo $contents ?>
</div>
</div>
</div>
</div>
<?php
}
?>
That way it will create the same HTML repeatedly for each record, and use the current values of your variables within each version.
Actually I am beginner programmer in HTML, CSS and PHP. I have simple website for add and register in courses. The user should be add course into website and the courses should be posted on the site.so users can browse and register.
Actually my problem is how to call the course name from database and how to format it with HTML code as I want.
This is the page of courses which is content the list of available courses in website ( please note it is only HTML code, I do that to see how the page will be )
Screenshot of page:
So as you see, the first page include many this HTML code to add course list into website with the following code:
<div class="card card-1">
<a href="http://127.0.0.1/project2/course details/course1.php">
<img src="http://127.0.0.1/project2/icons/coursepic.jpg" alt="Avatar" style="width:101% "></a> <div class="container">
<h4 class="textstyle"><b>Operating System</b> </h4>
<p class="textstyle">Free Course</p>
</div>
</div>
what i want do with PHP?
I want to write a PHP code to replace the P and h4 with the course name, cost of courses from my database for each available course.
Please note: the pic for each course it will be from my pc, no need to call the pic from database.
I tried to write PHP code like below:
<div>
<div class="card card-1">
<a href="http://127.0.0.1/project2/course details/course1.php">
<img src="http://127.0.0.1/project2/icons/coursepic.jpg" alt="Avatar" style="width:101% "></a> <div class="container">
<?php
include_once("db.php");
$result = mysqli_query(OpenCon(), "SELECT Course_Name,cost FROM `course`");
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<p>".$res['Course_Name']."</p>";
echo "<p>".$res['cost']."</p>";
}
?>
</div>
</div>
</div>
This is my result:
It's okay but I want the style to be like the first screenshot. each course should have picture.
After that when the user click on course name. I want move to another page which is content the course details ( for the same course that user clicked ) also it's called for my database
like this:
I hope any one help my to solve this problem only, I should solve this problem within 2 days only. and sorry if my explanation is bad.
Thanks in advance for everyone.
Put the code in a PHP loop.....
So, this
<div class="card card-1">
<a href="http://127.0.0.1/project2/course details/course1.php">
<img src="http://127.0.0.1/project2/icons/coursepic.jpg" alt="Avatar" style="width:101% ">
</a>
<div class="container">
<h4 class="textstyle"><b>Operating System</b> </h4>
<p class="textstyle">Free Course</p>
</div>
</div>
Becomes (after cleaning up the code a bit - I think you didn't mean to use two <p> in there, but I left them so you can see it. Note that using different lines for the segments makes it a lot easier to see what you have.)
include_once("db.php");
$result = mysqli_query(OpenCon(), "SELECT Course_Name,cost FROM `course`");
$count = 0;
while($res = mysqli_fetch_array($result)) {
$count ++;
// NOTE: Here is the LOOP! - not outside the query, but INSIDE it
// First you 'jump out' of PHP, going back to HTML
?> <!-- now you are in HTML (when you need PHP again, you 'jump in' and 'jump out' as needed - see the code below....) -->
<div class="card card-<?php echo $count;?>">
<a href="http://127.0.0.1/project2/course details/course<?php echo $count;?>.php">
<img src="http://127.0.0.1/project2/icons/coursepic.jpg" alt="Avatar" style="width:101% ">
</a>
<div class="container">
<h4 class="textstyle">
<b><p><?php echo $res['Course_Name'];?></p></b>
</h4>
<p class="textstyle">
<p><?php echo $res['cost'];?></p>
</p>
</div>
</div>
<?php // we are in PHP again....
}
That should do what you asked for - though I would go a step (well, more than one...) further and make as much of this dynamic as you can.
For this I will presume that:
your database table has a column called 'id' (if it doesn't, you should have) and it relates to the course number (you could make a course number column if they don't match up, but I'm keeping it simple)
you have all your pictures labeled 'coursepicX' where the X is the course number.
We'll use 'coursepic' as a default in case there isn't a picture yet...
Now, the code is more dynamic!
include_once("db.php");
$result = mysqli_query(OpenCon(), "SELECT id,Course_Name,cost FROM `course`");
while($res = mysqli_fetch_array($result)) {
// NOTE: Here is the LOOP! - not outside the query, but INSIDE it
// First you 'jump out' of PHP, going back to HTML
?> <!-- now you are in HTML (when you need PHP again, you 'jump in' and 'jump out' as needed - see the code below....) -->
<div class="card card-<?php echo $res['id']?>">
<a href="http://127.0.0.1/project2/course details/course<?php echo $res['id']?>.php">
<?php
$pic = "http://127.0.0.1/project2/icons/coursepic.jpg";
if(file_exists("http://127.0.0.1/project2/icons/course" . $res['id'] . ".jpg") {
$pic = "http://127.0.0.1/project2/icons/course" . $res['id'] . ".jpg";
}
<img src="<?php echo $pic; ?>" alt="Avatar" style="width:101% ">
</a>
<div class="container">
<h4 class="textstyle">
<b><p><?php echo $res['Course_Name'];?></p></b>
</h4>
<p class="textstyle">
<p><?php echo $res['cost'];?></p>
</p>
</div>
</div>
<?php // we are in PHP again....
}
Note that this is the basic 'shopping cart' sort of program - you will likely use it many (many) times in your career.
Happy Coding!
I am trying to consume an Amazon Product API and I choose to search for books alone base on the user search query. However after converting the response to an array, I am having problem looping through all the result without having to specify an index.
Below is my Code:
<div class="album py-5 bg-light">
<div class="container">
<div class="row">
<?php
foreach($formattedResponse as $response) {
?>
<div class="col-md-8">
<div class="card mb-4 box-shadow">
<img class="card-img-top" data-src="" alt="Card image cap">
<div class="card-body">
<p class="card-text"></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-secondary">Arthur: <?php echo $response['Item'][0]['ItemAttributes']['Author']; ?></button>
<button type="button" class="btn btn-sm btn-outline-secondary">Title: <?php echo $response['Item'][0]['ItemAttributes']['Title']; ?></button>
</div>
<small class="text-muted">Price: <?php echo $response['Item'][0]['ItemAttributes']['ListPrice']['FormattedPrice']; ?> </small>
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
Displaying the results works perfectly, the only drawback is, it fetches only the first index of the returned book response out of the thousands present because I used $response['Item'][0] if I take away the [0] from I get an error.. Below is the result
Arthur: Harry Boone Porter
Title: The Day of Light
Price: $8.00
My Question:
The array contains [0],[1],[2] to [1000] How can I fetch all the book results in the above format instead of the first index which I am using.
Here is my Array Code Snippet: https://pasteio.com/xlsoTVWJLGBO
Seems like formatted response is the named array and does not have to be iterated with foreach loop, if I'm not mistaken, you just need to:
Pass to the view not the $formattedResponse but $formattedResponse['item'] and not to iterate through it. Lets call it $items.
$items = $formattedResponse['item'];
// pass $items to the view.
In ['item'] element you have an indexed array with numbers. So iterate through it
<?php foreach ($items as $item): ?>
... html here
<?= htmlspecialchars($item['ItemAttributes']['ListPrice']['FormattedPrice']) ?>
<?php endforeach; ?>
Do not forget to escape output for your views. Use Twig, Blade or something like Html::encode($var) from Yii. How to escape output in PHP
To make debugging of multidimensional large arrays easier install larapack/dd from composer, and add
dd($largeArray)
in any place of your code. It's like var_dump, but a lot easier to look for human being ;)
I Just want to send passport number in the url on the next page. I know it will go into the url like this continue-to-pay.php?pno=$passportnumber".
But how will I post passport number on the next page.
<?php
include'connection.php';
$pno=$_GET['pno'];
$sql="SELECT * FROM user WHERE passportnumber='$pno'";
$query = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($query))
{
?>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-5 text-right" id="review">
<ul>
<li class="list">Passport Number </li>
</ul>
</div>
<div id="review2">
<ul>
<li class="list"><?php echo $row['passportnumber']; ?></li>
</ul>
</div>
<br><br>
<div class="col-xs-6 col-sm-12 col-md-12 col-lg-12" align="center"
valign="top">
<a href="e-visa-application.php?actionType=edit" class="btn btn-primary
btn-lg mgn-btm mgn-top ">Edit</a>
<a href="process.php" class="btn btn-primary btn-lg mgn-btm mgn-top
">Continue to pay</a>
</div>
if you got the PNO at your URL you can get it in a PHP file using $_GET :
<?php
if (isset($_GET['pno'])) {
echo $_GET['pno'];
}else{
// Fallback behaviour goes here
}
?>
You are probably searching for "The PHP session system" to keep the pno in the session while the user is going through the steps.
The PHP session system lets you store securely data in the $_SESSION global array. A example is to store the pno in the session.
session_start();
$_SESSION['pno'] = $pno;
Then, you can access that information on all other pages:
if (isset($_SESSION['pno']))
echo $_SESSION['pno'];
More info about sessions here
You can use $_REQUEST:
<?php
$_REQUEST['pno'] = $pno;
?>
you can use it to retrieve the pno in the continue-to-pay.php?pno=$passportnumber
I have the following html code:
<div class="media row-fluid">
<div class="span3">
<div class="widget">
<div class="well">
<div class="view">
<img src="img/demo/media/1.png" alt="" />
</div>
<div class="item-info">
Title 1
<p>Info.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
<div class="widget">
<div class="well">
<div class="view">
<img src="img/demo/media/2.png" alt="" />
</div>
<div class="item-info">
This is another title
<p>Some info and details go here.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
</div>
Which basically alternates between a span class with the widget class, and then the widget class without the span3 class.
What I wanted to know was if there was a way to have php "echo" or populate the details for and details under the "item-info" class. Would I need to use a foreach statement to get this done? I would be storing the information in a mysql database, and while I can get it to fill in the info one by one (repeatedly entering the and echoing out each image and item title) it's not practical when the content needed to be displayed is over 15 different items. I'm not well versed in foreach statements so I could definitely use some help on it.
If someone could help me perhaps structure a php script so that it can automatically output the html based on the number individual items in the database, that'd be greatly appreciated!
I'm wondering if the html + php (not including the foreach) would look like this:
<div class="span3">
<div class="widget">
<div class="well">
<div class="view">
<img src="img/<? $file ?>" alt="" />
</div>
<div class="item-info">
<?$title?>
<p>Info.</p>
<p class="item-buttons">
<i class="icon-pencil"></i>
<i class="icon-trash"></i>
</p>
</div>
</div>
</div>
EDIT:
I wanted to add some more information. The items populated would be based on a type of subscription - which will be managed by a group id.
I was initially going to use <? (if $_SESSION['group_id']==1)>
echo <div class="item-info">
$title
<p>$info</p>
</div>
so that only the subscribed items would populate. But, I would need it to iterate through all the items for group1 table and list it. Currently I know that I can do
<? (if $_SESSION['group_id']==1)
while ($row=mysql_fetch_assoc($sqlItem))
{
$itemInfo = $row['info'];
$image = $row['image'];
$title = $row['title'];
$url = $row['url'];
};
>
$sqlItem for now can only be assigned one thing (manually - as in: $sqlItem = '123'), unless I iterate through which is what I'm trying to figure out.
Just read that 'mysql_fetch_assoc' is being depreciated with 5.5, here is the new way and looks better, easier I think.. Hope this helps, was updated today.
I hope this helps http://php.net/manual/en/mysqli-stmt.fetch.php
replace the printf with echo '//then your html stuff
This will iterate through the rows in your database until their are no more matching records.
shouldn't a while be enough? It depends on the structure of your database and website (we didn't need so much HTML I think. Some more PHP maybe). Hope this helps.