I'm new to this site and wondering if somebody could help. I'm creating a website using bootstrap. I added some products in my DB and have used a while loop to display them on the page.
If you click on one of the products it takes you too a new page which should display all the information from only that product.
if ($select_db) {
$SQL = "SELECT * FROM products";
$result = mysql_query($SQL);
?>
<?php
$c = 0;
$id = -1; // The counter
$n = 3; // Each Nth iteration would be a new table row
while ($db_field = mysql_fetch_assoc($result)) {
$itemName = $db_field['name'];
$itemDescription = $db_field['description'];
$itemPrice = $db_field['price'];
$myPic = $db_field['image_name'];
if ($c % $n == 0 && $c != 0) { // If $c is divisible by $n...
echo '<div class="row" ></div>';
}
$c++;
$id++;
?>
<div class="col-md-4 col-sm-4" style="background-color:lavender;" id = 1>
<a href="productInfo.php">
<p> <?php echo $c ?> </p>
<h2> <?php echo $itemName ?> </h2>
<p><img class="img-responsive" img src= '<?php echo $myPic ?>' alt="Oops, Image cannot be found!" height="300" width="300"/></p>
<h3><?php echo $itemDescription ?></h3>
<p><?php echo $itemPrice ?></p>
<div id="selector" class="btn-group">
<button type="button" class="btn btn-primary" id="<?php $id ?>">Add</button>
</div>
<?php
$productsArray[] = array(
"id" => $id,
"itemName" => $itemName,
"itemDescription" => $itemDescription,
"price" => $itemPrice
);
//$_SESSION['sessionArray']=$productsArray;
?>
</a>
</div>
<?php
Now when I click on one of the columns it takes me to productInfo.php. I'm stuck as to how to display the product that is clicked?
I have added a variable $id which is the same as the array, example array [0] has id of 0, array [1] has id of 1. I think I'm trying to say if ID = 0 then display the results in the array at place [0]. I'm not sure if this helps?
I tried to display just the $id for now on productInfo.php but it only shows the last $id in the array
<?php
session_start();
if (isset($_SESSION["id"])) {
$newID = $_SESSION["id"];
echo $newID;
}
?>
I know this because it doesn't know which one I'm selecting. Am I making this too complicated?
Any help would be appreciated greatly!
Within your while loop I would add:
View More
This would concatenate the value of $id++ into the href under each item. Then all you need to do is create a landing page for product_page.php, define the $id on that page again and pull the data for that product from the db. You can do this without using any arrays.
Edit:
You would define $id on your product_page.php using $_GET['id'], as it is in the url, supplied by your href above ^
A good practice to get into whilst in the development stages would be to echo $id; to see if it is echoing the correct data from your while loop. If it echo's the correct $id then you can send the $id to the url through the href.
Let me know if this works or not.
Pulling data from db of your ID:
$sql = "SELECT * FROM table WHERE id='".$myID."'";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$data1 = $row['whatever'];
echo $data1;
Related
I am trying to create a small website to sell items on and learn php. I have a index.php which links to a chairs.php page and then from there to a viewItem.php page depending on which item they choose.
I have in my database 4 items. On the chairs.php a while loop runs to display on the page all items in that database.
I would like to use the id of the item to link to the next page but I think the while loop is always going to assign to the variable that I am using the very last entry in that while loop.
Can someone point me in the direction of how I would resolve this? I would like the user to select a Chair 1 on my Chairs.php page with ID 1 in my db to link to the corresponding page. Currently all links on the chairs.php would link to the last item in my while loop which is then assigned to the $_SESSION['output_id'] = $output_id variable.
Thank You
<?php
$query = "SELECT * FROM `chairs_table";
$queryChairs = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($queryChairs)) {
$output_id = $row["ID"];
$output_img = $row["Image"];
$output_name = $row["Name"];
$output_desc = $row["Desc"];
$output_price = $row["Price"];
$_SESSION['output_id'] = $output_id;
$_SESSION['output_img'] = $output_img;
$_SESSION['output_name'] = $output_name;
$_SESSION['output_desc'] = $output_desc;
$_SESSION['output_price'] = $output_price;
?>
<div class="itemContainer" onclick="location.href = 'viewItem.php?id=<?php echo "{$output_id}" ?>'" style="cursor:pointer;" >
<div> <img src = "img/<?php echo "{output_img}" ?>"> </div>
<div class="itemTextTitle"><?php echo"{$output_name}" ?></div>
<div class="itemTextDesc"><?php echo"{$output_desc}" ?></div>
<div class="itemTextPrice">cop <?php echo"{$output_price}"?></div>
</div>
<?php
}
?>
</div>
sqlQueryImage ThisWhatIgetinPHP
i have tried this but it keeps displaying me just the first image of every article i don't know how display multiple image for one article
$result = $db->prepare("SELECT article.titreArticle, article.textArticle,
article.idArticle, article.dateArticle, GROUP_CONCAT(images.images) AS IMG
FROM article LEFT JOIN images
ON article.idArticle = images.idArticle
GROUP BY article.idArticle");
for ($i = 0;
$row = $result->fetch();
$i++){
?>
<h1 style="text-align: center"><?php echo $row['idArticle']; ?></h1>
<hr>
<img style="width: 300px" src="images/<?php if($row ['IMG'] !=null ) {
$value = $row['IMG'];
}
$values = explode(",", $value);
echo $values[0];
?>">
The aim of GROUP_CONCAT is to return each value within each GROUP, concatenated in the same field.
You expect to have several images for certain groups, however you only display one image, the first one encountered : echo $values[0];
If you want to display all images of a group, you have to make a second loop on your array of images, to print each element.
So you have your main loop on row, and a second loop on images.
Try this:
<?php
$result = $db->prepare("SELECT article.titreArticle, article.textArticle,
article.idArticle, article.dateArticle, GROUP_CONCAT(images.images) AS IMG
FROM article LEFT JOIN images
ON article.idArticle = images.idArticle
GROUP BY article.idArticle");
// FIRST LOOP ON ROWS
for ($i = 0; $row = $result->fetch(); $i++){
?>
<h1 style="text-align: center"><?php echo $row['idArticle']; ?></h1>
<hr>
<?php
$images = ""; // we will store all our images for this row here (if any)
if($row ['IMG'] !=null ) {
$value = $row['IMG'];
$values = explode(",", $value);
// SECOND LOOP ON IMAGES
foreach($values, $imgsrc){
$images .= '<img style="width: 300px" src="images/'.$imgsrc.'">';
}
echo $images; // output all images
}
?>
I am fairly new to PHP and mySQL and have small issue I am busy trying to create a 4 column layout with using echo and currently I have managed to achieve this with with a mySQL database but the last column requires and additional style in the div class. With my Limited knowledge I thought of trying a count using one of the solutions I found on the forum, but I think I may be using it wrong. my idea is to echo the database array, then do a count and echo the same content block but the with additional css element in div class. Your help is greatly appreciated. if this question has been asked before please accept my apologies I am just under a lot of pressure to get it resolved.
SEE CURRENT PHP Code Below
<?php
$conn = mysqli_connect('localhost', 'root', 'password')
or die ( mysql_error());
$rs = mysqli_select_db($conn, 'database name' ) or die
( mysql_error());
$query = "SELECT * FROM database name";
$rs = mysqli_query( $conn, $query ) or die
( mysql_error());
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH))
{
$id = $row['id'];
$image = $row['image'];
$product = $row['product'];
$code = $row['code'];
$material = $row['material'];
$sizes = $row['sizes'];
echo "
<div class='percent-one-fourth'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
$i = 0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH)){
if($i++ % 4 == 0) {
echo "
<div class='percent-one-fourth column-last'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
}
mysqli_close($conn);
?>
As you're new to PHP, it's really important that you understand why your code isn't working properly. So, let's step over it and describe it in brief, simple English:
Connect to MySQL
Run a database query which has multiple rows as its response
Whilst there are more rows to go..
Output every row
Whilst there are more rows to go.. [!] Always false - we already used them all up
Output every 4th result [!] Vars like $image also aren't defined here
So, because of the way how mysqli_fetch_array works, you can hopefully see that we need to loop using it only once. This is also great for you, because it fits with the DRY (don't repeat yourself) principle.
Edit: You were also mixing MySQL API's; mysql_error is very different from mysqli_error.
So instead, during our one loop, we'll check if we're on the 4th row, and react differently. That results in something like this:
<?php
// 1. Connect to MySQL
// (this should be in a separate file and included so you don't repeat it)
$conn = mysqli_connect('localhost', 'root', 'password')
or die ( mysqli_error()); // <-- *mysqli*
$rs = mysqli_select_db($conn, 'database name' ) or die
( mysqli_error());
// 2. Run the query which has multiple rows as its response:
$query = "SELECT * FROM database name";
$rs = mysqli_query( $conn, $query ) or die
( mysqli_error());
// 3. Whilst there are more rows to go..
$i=0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH))
{
// Get easier references to various fields:
$id = $row['id'];
$image = $row['image'];
$product = $row['product'];
$code = $row['code'];
$material = $row['material'];
$sizes = $row['sizes'];
// Start outputting this row:
echo "<div class='percent-one-fourth";
// The important part! We check here in this single loop:
if($i++ % 4 == 0){
// Every 4th row - output that extra class now!
echo " column-last";
}
// Output everything else:
echo "'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
// Tidy up:
mysqli_close($conn);
?>
Your code is echoing only for the 4th column. For columns 1, 2, and 3, you need to add an else clause.
Optional: Besides instead of echoing you could close the php tag (?>) and write the html directly.
...
$i = 0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH)){
if($i++ % 4 == 0) {
echo "html for the 4th column";
}else{
echo "html for column 1, 2, and 3";
}
}
i am developing a web application,which has 3 pages.
first is index.php
which has search bar on which user searches.
second is search.php
which displays the search results like result_1,result_2,result_3 with info(title,description,url) when user click on any result it send the user to final page i.e show.php
and third page is show.php
on which info is displayed for the result which user has clicked.
for eg(corresponding url content will be displayed using iframe)
i tried using two dimensional session array,which is working not correctly.
when user click on any result,some other result's info is displaying on show.php
i check the session array content by print_r,it had unnecessary content.
someone help me in this i am sharing my code snippet.
search.php
<?php
session_start();
$id = 1;
while($row = mysqli_fetch_array($sql))
{
$title = $row['title'];
$description = $row['description'];
$url = $row['content_url'];
$icon = $row['thumb_icon_url'];
$_SESSION['result'][] = Array('title' => $title,'description'=> $description,'content_url' => $url,'icon' => $icon,'id'=> $id);
?>
<li name="id" >View doc</li>
<?php
$id++;
?>
show.php
<?php
if(isset($_GET['id']))
{
$id = $_GET['id'];
?>
<div>
<iframe class="embed-responsive-item item" src="<?php echo $_SESSION['result'][$id]['content_url'];?>"></iframe>
</div>
when i tried to check $_SESSION['result'] i got this
this array should have contain only query results.Help me to fix it
you're not setting the key of your array:
$_SESSION['result'] = Array();
$_SESSION['result'][$id] = Array('title' => $title,'description'=> $description,'content_url' => $url,'icon' => $icon,'id'=> $id);
add session_start(); in your show.php
If I understand correctly, your problem is that you have unwanted results.
This is basically because your are always adding results to the $_SESSION['results'] across all your queries.
Every time that you run search.php you will keep adding items to $_SESSION['result'], breaking the correspondence of the $id and the position of the array.
I would initialize the $_SESSION['result']
<?php
session_start();
$id = 1;
$_SESSION['results'] = [];
while($row = mysqli_fetch_array($sql)){
//...
}
How can i add a pagination system to this simple item display? And how i can add pagination for the results from filter? I just get lost that part and i cant figure it out!
I want to apply CSS on the menu too!
Here's the code:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$result = mysql_query("SELECT * FROM products");
}
while($row=mysql_fetch_assoc($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
?>
EDITED:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$start=0;
$limit=6;
if(isset($_GET['id']))
{
$id = $_GET['id'];
$start = ($id-1)*$limit;
}
$result = mysql_query("SELECT * FROM products LIMIT $start, $limit");
}
while($row = mysql_fetch_array($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
echo "</ul>";
$rows = mysql_num_rows(mysql_query("SELECT * FROM products"));
$total = ceil($rows/$limit);
if($id>1)
{
echo "<center><a href='?id=".($id-1)."' class='button'>Anterior</a></center>";
}
if($id!=$total)
{
echo "<center><a href='?id=".($id+1)."' class='button'>Próximo</a></center>";
}
?>
You should have something like this:
// declare a base query
$q = "SELECT * FROM products";
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
// append filter to query
$q += "where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
// check for "page" URL parameter, if not available, go to first page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// check for "pageSize" URL parameter, if not available, fall back to 20
$pageSize = isset($_GET['pageSize']) ? $_GET['pageSize'] : 20;
// append the pagination to your query
$q += sprintf("LIMIT %d,%d;", ($page-1)*$pageSize, $pageSize);
// execute the constructed query
$result = mysql_query($q);
Note that the code is "pseudoish", not tested, but should give you the base idea.
Also, you can check this SO post about pagination with MySQL.
UPDATE
In PHP if you use an uninitialized variable, then it will have a context-dependent default value. See the documentation about this here. Here is an extract:
It is not necessary to initialize variables in PHP however it is a
very good practice. Uninitialized variables have a default value of
their type depending on the context in which they are used - booleans
default to FALSE, integers and floats default to zero, strings (e.g.
used in echo) are set as an empty string and arrays become to an empty
array.