I tried my best but I stuck on this problem. Sorry for my bad english.
So here is the situation:
I am trying to make a little shopping site. My database table looks like this:
id pic titel desc price
1 gta5.png Grand Theft Auto 5 A open world game... 49.99
2 cod.png Call Of Duty: MW A Ego-Shooter game... 59.99
3 play4.png Playstation 4 Next-Gen Console... 249.99
4 contr.png Ps4 Controller Next-Gen Equipment... 69.99
On the Database Class file I have some function where I get the column information from the table:
public function getImg(){
while($row = mysqli_fetch_row($this->query)){
return $row[1];
}
}
public function getTitel(){
while($row = mysqli_fetch_row($this->query)){
return $row[2];
}
}
...
With getImg() I will get every information on the pic column like: gta5.png, cod.png etc.
My problem is starting here. I want to print out every column with a for loop on the index.php file. But I can't see any information. Here is the index.php file:
<ul>
<li>
<div class="container">
<div class="content">
<?php
for($i = 0; $i < $database->getTableLength(); $i++){
?>
<img src="image/<?php echo $database->getImg(); ?>"></img>
<h4><?php echo $database->getTitel(); ?></h4>
<h5><?php echo $database->getDesc(); ?></h5>
<h2><?php echo $database->getPrice(); ?>€</h2>
<input type="button" name="submit" value="Buy">
<?php
}
?>
</div>
</div>
</li>
</ul>
But as I said there is nothing. The getTableLength() function is the length of the table (In this case 4). I also tried to print it out one by one like this:
<ul>
<li>
<div class="container">
<div class="content">
<?php
for($i = 0; $i < $database->getTableLength(); $i++){
echo $database->getImg() . "<br>";
}
?>
</div>
</div>
</li>
</ul>
But again failed.. I can see even the br tag but not the information that I want to print out. When I put the echo line before the for loop, then I can see the first index of the column (gta5.png), but I want to have all columns.
Hope to see some solutions. Thanks for any kind of help!
EDIT:
It is working when I write 5 instead of the length function:
for($i = 0; $i < 5; $i++){
echo $database->getImg();
}
But I still want to use that function. The getTableLength() function isn't working as I expected. There is nothing to see when I insert the function. The getTable function looks like this:
public function getTableLength(){
$sql = "SELECT COUNT(*) AS num FROM `$this->table`";
$this->query = mysqli_query($this->connect, $sql);
if($this->query){
$row = mysqli_fetch_assoc($this->query);
return $row['num'];
}
}
When I call it on the index.php file like:
$database->getTableLength();
I can see nothing and everything is gone. It's like buggy.
Fixed. It was to complicated. Think simple and do it better..
Here is the solution:
<?php
$table = $database->getTableName();
$sql = "SELECT * FROM `$table`";
$connect = $database->getConn();
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<form method="post" action="index.php?action=add&id=<?php echo $row["id"] ?>">
<ul>
<li>
<div class="container">
<div class="content">
<img src="image/<?php echo $row["bild"]; ?>"></img>
<h4><?php echo $row["titel"]; ?></h4>
<h5><?php echo $row["beschreibung"]; ?></h5>
<h2><?php echo $row["preis"]; ?>€</h2>
<input type="hidden" name="hidden_name" value="<?php echo $row["titel"]; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row["preis"]; ?>">
<input type="submit" name="add_to_cart" value="Kaufen">
</div>
</div>
</li>
</ul>
<?php
Related
This question already has answers here:
PHP SQL STMT SELECT multiple LIKE ? is it possible?
(2 answers)
Closed 2 years ago.
I'm building an online shop (not a real one) using PHP. I have a search results page and a full specs page, the full specs page is working perfectly however when I created a shopping cart page that also works perfectly the search results page no longer returns anything. I have found when commenting out the if statement and while statement the "no items found" message does work but cannot get it to return anything if this is a valid search. After a couple of days, I still cannot figure out what the problem is. I will include the adding to basket and form code as the form is also included on the full specs page which does work. If you can point me in the right direction it would be greatly appreciated.
**Search Bar code**
<?php
global $ConnectingDB;
if (isset($_GET["SearchButton"])) {
}
?>
<form class="mt-5" method="GET" action="searchResults.php" style="width: 100%;">
<div class="form-group">
<input class="form-control mb-2" type="text" name="Search" placeholder="Search for Item" value="">
<button class="btn btn-success" name="SearchButton" style="width: 100%;">Search</button>
</div>
</form>
Search Results Code
$db = mysqli_connect("localhost", "root", "", "computerStore") or die (mysqli_error());
require_once("includes/functions.php");
require_once("includes/sessions.php");
include("addingToBasket.php");
?>
<html>
<head>
<title>Search Results</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<?php
include("navbar.php");
?>
<div style="height: 15%;"></div>
<div class="container mt-5">
<?php
echo ErrorMessage();
echo SuccessMessage();
?>
<div class="row">
<div class="col-lg-12">
<?php
if (isset($_GET["productNumber"])) {
$Search = $db->real_escape_string($_GET["Search"]);
$sql = $db->query("SELECT * FROM products WHERE productName LIKE '%$Search%' OR productNumber LIKE '%$Search%' OR briefProductInfo LIKE '%$Search%'");
$result = new mysqli($db, $sql) or die("bad query: $sql");
$row = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
echo $count;
//stmt = $db->query($sql);
//$row = $stmt->fetchAll();
//echo count($row).' rows selected';
if ($sql->mysqli_num_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$ProductName = $row["productName"];
$ProductNumber = $row["productNumber"];
$ProductType = $row["productType"];
$BriefProductInfo = $row["briefProductInfo"];
$FullProductInfo = $row["fullProductInfo"];
$Image = $row["image"];
$Price = $row["price"];
$Quantity = $row["quantity"];
include("form.php");
}
} else {
?> <div class="container"><h2><?php echo "Item has not been found, please try another search"; ?></h2></div>
<?php
}
}
?>
</div>
</div>
</div>
</body>
</html>
Adding to Basket Code
<?php
if (!(isset($_SESSION['cart']))) {
$_SESSION['cart'] = array();
} else {
echo "";
}
if (isset($_GET['clear'])) {
$_SESSION['cart'] = array();
}
if (isset($_GET['productNumber']) && isset($_GET['quantity'])) {
$ProductNumber = $_GET['productNumber'];
$Quantity = $_GET['quantity'];
if ($Quantity > 0) {
if(isset($_SESSION['cart'][$ProductNumber])) {
$_SESSION['cart'][$ProductNumber] += $Quantity;
} else {
$_SESSION['cart'][$ProductNumber] = $Quantity;
$_SESSION["SuccessMessage"] = "Item has been successfully added to your basket, feel free to continue shopping if there are more items to wish to purchase. However if you
do wish to buy now, amend the item quantity or you added the item by mistake and wish to remove it, please select the view basket link.";
}
}
}
?>
The Form
while ($row = mysqli_fetch_assoc($result)) {
?>
<h2 class="mb-5"><?php echo $row["productName"] ?> - <?php echo $row["briefProductInfo"] ?></h2>
<p class="text-center mb-5"><?php echo $row["productNumber"] ?></p>
<img class="img-fluid mx-auto d-block mt-5 mb-5" src="images/<?php echo $row["image"] ?>" alt="Product Image">
<p style="text-align: justify;"><?php echo $row["fullProductInfo"] ?></p>
<h1 class="mt-5 mb-5" style="color: red;">£<?php echo $row["price"] ?></h1>
<p style="text-align: center;" id="numberAvailable"><?php echo $row["quantity"] ?> Available</p>
<form method="get" action="<?php $_SERVER["PHP_SELF"] ?>">
<div class="row mt-5 mb-5">
<div class="col-lg-2">
<p style="font-size: 170%;" id="numberRequested">Quantity</p>
</div>
<div class="col-lg-2 mt-1">
<select class="pt-2 pb-2" name="quantity" class="form-control" id="numberRequestedPulldown">
<?php
if ($row["quantity"] >= 5) {
for ($i = 1; $i <= 5; $i++) {
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
} else {
for ($i = 1; $i <= $row["quantity"]; $i++) {
?> <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
?>
</select>
<input type='hidden' name='productNumber' id='productNumber' value='<?php echo $row['productNumber'] ?>'>
</div>
<div class="col-lg-4 mt-1">
<input type="submit" class="btn btn-success btn-block" id="addToBasketLink" value="Add to Basket">
</div>
<div class="col-lg-4 mt-1">
Return to Items List
</div>
</div>
</form>
<?php
}
?>
Your SQL statement for the search may not be formatted correctly:
$sql = $db->query("SELECT * FROM products WHERE productName LIKE '%$Search%' OR productNumber LIKE '%$Search%' OR briefProductInfo LIKE '%$Search%'");
I can tell you from experience that just placing a double apostrophe(") at the start and including the wildcard(%) in your statement may be the wrong way to go try this:
$sql = $db->query('SELECT * FROM products WHERE productName LIKE "%'.$Search.'%" OR productNumber LIKE "%'.$Search.'%" OR briefProductInfo LIKE "%'.$Search.'%"');
This separates the wildcard(%) from the search term that the SQL is looking for. By including the % inside of the statement the SQL statement may run but come up with zero results and move onto your next statement because it is looking for '%book%', when it should be just looking for 'book'. This would give you the "no items found" message, because it moves to the next statement.
This is new information 10/30/2020
You are using the search as your name in this input:
<form class="mt-5" method="GET" action="searchResults.php" style="width: 100%;">
<div class="form-group">
<input class="form-control mb-2" type="text" name="Search" placeholder="Search for Item" value="">
<button class="btn btn-success" name="SearchButton" style="width: 100%;">Search</button>
</div>
</form>
You are not carrying over the productNumber though that I see to get start the statement.
if (isset($_GET["productNumber"])) {
Maybe try doing something like this instead:
$Search = filter_input(INPUT_GET, 'Search');
/*use the preg_replace to remove any special characters*/
$Search = preg_replace('/[^a-zA-Z0-9]/', '', $Search);
echo $Search; /*Just to see if it appears*/
/*instead of if (isset($_GET["productNumber"])) { use */
if($Search != ''){
$sql = $db->query('SELECT * FROM products WHERE productName LIKE "%'.$Search.'%" OR productNumber LIKE "%'.$Search.'%" OR briefProductInfo LIKE "%'.$Search.'%"');
continue with code
This is some Bootstrap HTML where I need to create multiple blocks like a table but it just grabs the first item in the DB and prints 50 of them. I'm having trouble figuring out how to mingle the php code and html code so it works correctly.
<section id="latest-news" class="latest-news-section">
<div class="container">
<?php
include_once ('mysql.inc.php');
$ix = $_POST['i'];
$sql = "SELECT * from deposits WHERE d_userid = '$ix' ORDER BY _productionid ASC";
$query = #mysql_query($sql);
$outcome = #mysql_fetch_array($query);
foreach ($outcome as $result1){
?>
This part comes out nicely formatted, but the only data is the first item in the DB, and there are 50 copies made
<div class="col-md-4 col-sm-4">
<div class="latest-post">
<img src="assets/images/<?php echo $outcome['d_picture'] ?>" class="img-responsive" alt="">
<h4>Your ST1 <?php echo $outcome['d_firstname'] ?></h4>
<p>Prod ID <?php echo $outcome['d_productionid'] ?></p>
<p>Color: <?php echo $outcome['d_color'] ?><br />
Equip: <?php echo $outcome['d_equip'] ?><br />
Custom: <?php echo $outcome['d_custom'] ?></p>
<a class="btn btn-primary">View More</a>
</div>
</div>
<?
}
#mysql_close;
?>
</div>
</section>
You should use $result1 and not $outcome
ex: $result1['d_picture']
I'm trying to generate dynamic contents fill from mysql db
here is my php code:
<?php
include 'header.php';
error_reporting(1);
$user = "root";
$pass = "";
$dbName = "haimi";
mysql_connect('localhost', $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($dbName);
$sql = "SELECT * FROM Projects ";
$result = mysql_query($sql);
?>
<?php
while ($line = mysql_fetch_array($result)) {
?>
<li class="filter" data-filter=".cat<?php echo $line['Category'];?>"><?php echo $line['Category'];?></li>
<?php
}
?>
The li displays correctly, but the following does not:
<div class="row projects m0">
<?php
while ($line = mysql_fetch_array($result)) { ?>
<div class="project mix catHouses">
<div class="tint"></div>
<a href="images/projects/".<?php echo $line['ProjectImage1']; ?> data-
lightbox="project" data-title="Central Hospital (building)">
<img src="images/projects/".<?php echo
$line['ProjectImage1']; ?> alt="<?php echo $line['ProjectTitle'];?>"
class="projectImg"> </a>
<div class="projectDetails row m0">
<div class="fleft nameType">
<div class="row m0 projectName"><?php echo $line['ProjectTitle'];?></div>
<div class="row m0 projectType"><?php echo $line['ProjectType'];?></div>
</div>
<div class="fright projectIcons btn-group" role="group">
<a href="images/projects/<?php echo $line['ProjectImage1']; ?>" data-lightbox="project" data-title="Central Hospital (building)" class="btn btn-default">
<i class="fa fa-link"></i></a>
<i class="fa fa- search"></i>
</div>
</div>
</div>
<?php
}
?>
</div>
It data in the divs doesn't appear.
You're making a single call, but trying to loop through it twice. To do so, you need to reset the pointer back to the beginning:
//Add this after the first loop, but before the second
mysql_data_seek( $result, 0 );
The way you have it now, it's while($line = mysql_fetch_array($result)), but the second loop is never entered since it has already reached the end. Since the loop is ended, it never displays the contents.
Important Note
The mysql_* functions are deprecated, and is removed in PHP 5.5. You should use Mysqli or PDO. They have better protections against mysql injections (see Bobby Tables).
You have some HTML mistakes here:
<a href="images/projects/".<?php echo $line['ProjectImage1']; ?>
First, there is no need to use . operator (as you are in HTML, not PHP),
Also you shoud put your <?php ?> tag inside the href quotations, here is the correct code:
<a
href="images/projects/<?php echo $line['ProjectImage1']; ?>"
data-lightbox="project"
data-title="Central Hospital (building)"
>
<img
src="images/projects/<?php echo $line['ProjectImage1']; ?>"
alt="<?php echo $line['ProjectTitle']; ?>"
class="projectImg"
>
</a>
You will get older fast writing code like that ;)
How about this:
while ($line = mysql_fetch_array($result)) {
$category = $line['Category'];
echo <<< LOB
<li class="filter" data-filter="$category">$category</li>
LOB;
}
Like what Mr #matthew said
I was making a single call, and I was trying to loop through it twice.
The problem solved with this code before the while loop:
$result = mysql_query($sql);
This is a very basic problem but I am very new to PHP.
I need to show results in such scenario that only three records in same line then add <br /> and then on next line, same thing should happend. I am unable to make its logic and in a great trouble :(
Right now, I am just using the simple way i.e.
while($data = mysql_fetch_array($res_set)) {
?>
<div><?php echo $data['name']?><img src="images/<?php echo $data['image']?>" /></div>
<?php
}
this is my code
$cnt = 0;
while ($prd = mysql_fetch_array($res)) {
?>
<div class="imageRow">
<?php
$cat_id = $prd['cat_id'];
$sql = "select * from tbl_category where id = $cat_id";
$cat_res = mysql_query($sql);
$cat_data = mysql_fetch_array($cat_res);
$cat_name = $cat_data['name'];
?>
<div class="set">
<div class="single first">
<img src="<?php echo $ru ?>admin/product_images/<?php echo $cat_name ?>/large/<?php echo $prd['thumb_img'] ?>" style="height: 100px; width: 100px;" /><br />
Choose
</div>
</div>
</div>
<?php
$cnt = $cnt++;
if($cnt%3 == 0) {echo "<br />";}
}
//echo $cnt;
?>
any help will be appreciated.
Thanks
<div class="imageRow">
<?php
$i = 0;
while($data = mysql_fetch_array($res_set)) { ?>
<div>
<?php echo $data['name']; ?><img src="images/<?php echo $data['image']; ?>" />
</div>
<?php
$i++;
if($i % 3 == 0) {
echo '</div><div class="imageRow"><br />';
}
}
?>
</div>
Explanation:
Set the variable $i to a number, which will then be used to keep track of how many items you've written.
Then, within the while loop, increment $i ($i++), which is the same as $i = $i + 1; By doing this, you always know which item you're on - whatever the value of $i is. Some people choose to set it to 1 initially then increment at the very end - other like to set it to 0, and set it near the beginning - either is completely fine - whatever you need it to do / whichever way you like better.
Lastly, check if $i is evenly divisible by 3 (kind of like remainder - it's called "mod" and is represented by the percent symbol). If it is, then echo a line break.
Try this
<?php
echo "<div>";
while($data = mysql_fetch_attay($res_set)) {
?>
<div style="width:30%; float:left"><?php echo $data['name]?><img src="images/<?php echo $data['image']?>" /></div>
<?php
}
echo "</div>";
?>
Output
<div>
<div>1</div> <div>2</div> <div>3</div>
<div>1</div> <div>2</div> <div>3</div>
<div>1</div> <div>2</div> <div>3</div>
</div>
That's some super ugly code you have there. This will do what you need, and is cleaner.
<?php
$i=1;
while($data = mysql_fetch_attay($res_set)) {
$frame = '<div><img src="%s" /></div>';
printf($frame, $data['image']);
if($i % 3 == 0) { echo '<br />'; }
$i++;
}
Also, <img> elements are already block elements to begin with, you really don't need to wrap another <div> around them.
I have two tables listed (on screen) in PHP and the left should be hyperlinked so when click on it the right table will show a query. So at the beginning it should be empty then when clicked refresh the page with the selected listname's result.
unfortunately I have no experience with these things so i don't know the concept of it yet, but I am happy to learn:)
<form method="post" action="test.php">
<div id="left"><table>
<?php
$left="SELECT * FROM groups";
$resultleft=mysql_query($left);
while ($resultleft=mysql_query($left)) {
echo "<tr><td>".$left['id'].'</td><td>'.$left['listname']."</td></tr>";
}
?>
</table></div>
<div id="right"><table>
<?php
$right="SELECT * FROM grouplink WHERE grouplink.group_id= ";
$resultright=mysql_query($right);
while ($resultright=mysql_query($right)) {
echo "<tr><td>'.$right['people_name']."</td></tr>";
}
?>
</table></div>
<?php
if (isset($_POST('???'))){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
?>
</form>
any help would be appreciated
Can for example link to table.php?gid=n, where n would be the group id. You can then check if $_GET['gid'] isset, and if it is, take that id and put it in your query.
if(isset($_GET['gid']))
$right = sprintf("SELECT * FROM grouplink WHERE grouplink.group_id=%u", $_GET['gid']);
You need mysql_fetch_assoc
instead of mysql_query
in:
while ($resultleft=mysql_query($left)) {
echo "<tr><td>".$left['id'].'</td><td>'.$left['listname']."</td></tr>";
}
and also in:
$resultright=mysql_query($right);
while ($resultright=mysql_query($right)) {
echo "<tr><td>'.$right['people_name']."</td></tr>";
so this will be:
while ($left=mysql_fetch_assoc($resultleft)) {
echo "<tr><td>".$left['id'].'</td><td>'.$left['listname']."</td></tr>";
}
and similar issue with right
Thanks to Svish here is my new working code:
<?php include("db_con1.php");?>
<html>
<head>
</head>
<body>
<form method="post" action="test.php">
<div id="left">
<?php
$queryl = $pdo->prepare('SELECT id, name FROM test1 ORDER BY name ASC');
$queryl->execute();
?>
<ul>
<?php foreach ($queryl as $i => $rowl) { ?>
<li>
<?php if ($i)?>
<input name="checkbox_add[]" id="test_<?php echo $i ?>" type="checkbox" value="<? echo $rowl['id']; ?>"/>
<label for="test_<?php echo $i ?>"><?php echo $rowl['name']; ?></label>
</li>
<?php } ?>
</ul>
</div>
<div id="right">
<?php
if(isset($_GET['gid'])) {
$gid=$_GET['gid'];
$queryr = $pdo->prepare('SELECT test3.name FROM test1, test2, test3 WHERE test1.id=test2.groupid AND test3.id=test2.peopleid AND test1.id='.$gid.' ORDER BY test3.name ASC');
$queryr->execute();
}
?>
<ul>
<?php foreach ($queryr as $i => $rowr) { ?>
<li>
<?php if ($i)?>
<input name="checkbox_del[]" id="test_<?php echo $i ?>" type="checkbox" value="<? echo $rowr['id']; ?>"/>
<label for="test_<?php echo $i ?>"><?php echo $rowr['name']; ?></label>
</li>
<?php } ?>
</ul>
</div>
</form>
</body>
</html>