I am creating a dummy online store to illustrate some real world functionality which one of them is to search the website for items i.e.
I have written PHP code to deal with this scenario but it does not work properly. Wchat it does dough is it matches the results and the number of results but it does not display them which I of course wont it to do.
Been trying to look for answers on GOOGLE but didn't find corresponding solution or a tip to my problem.
Here am gonna list the code I am using:
PHP code (search.php):
<?php
session_start();
include('connect_mysql.php');
$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';
if (isset($_POST['keyword']))
{
$search = $_POST['keyword'];
if (!empty($search))
{
$query = "SELECT product_name FROM products WHERE product_name='$search'";
$query_search = mysql_query($query);
echo mysql_num_rows($query_search);
if (mysql_num_rows($query_search) >=1)
{
echo 'Results found: <br>';
while ($query_row = mysql_fetch_row($query_search))
{
echo $query_row['product_name'];
}
while($rows = mysql_fetch_array($query_search))
{ ?>
<table id='display'>
<tr><td><?php echo "<img src=$rows[$product_image] class='grow'>" ?></td></tr>
<tr>
<th></th>
<th><strong>Avalible</strong></th>
<th><strong>Price</strong></th>
<th><strong>Description</strong></th>
</tr>
<tr>
<td width='290px'><?php echo "$rows[$product_name]" ?></td>
<td width='290px'><?php echo "$rows[$product_qua]" ?></td>
<td width='290px'><?php echo "£ $rows[$product_price]" ?></td>
<td width='290px'><?php echo "$rows[$product_des]" ?></td>
</tr>
<tr>
<td><p>Please Login To purchase this item </p><br />Login</td>
</tr>
</table>
<?php
}
} else {
echo 'NO results found.';
}
}
}
?>
HTML code (index.php):
<form action="search.php" method="post">
<input type="text" name="keyword" size="20" placeholder="Search for products...."/>
<input type="submit" value="Search >>" />
</form>
Print screen of current result:
As you have have noticed it also says 3 results have been found which is correct considering i have searched for ever which is a common name of my product but drows up only two tables moreover they are empty.
website url: http://studentnet.kingston.ac.uk/~k1024026/index.php
finally my product table consists of : product_id product_name product_qua product_price product_image product_des product_type attrebiutes/columns
anyone can spot where i might be going wrong with this....?
First, try removing this
while ($query_row = mysql_fetch_row($query_search))
{
echo $query_row['product_name'];
}
I also noticed a few bad typo in your code :
table id="display" an id should be unique. If you iterate over it and still want it to be an id, put display-n instead, n being the unique id of the product for example. (or use class="display" instead of id)
You should take a look at sql injection and how to defeat them.
I might rather do this:
$query = "SELECT product_name FROM products WHERE product_name LIKE %" . $search . "%";
Hope it will help. Then use a foreach loop to run through the result like:
foreach ($search as $key => $result){
echo $result . '<br />';
}
mysql_fetch_row( $query_search) returns a plain array not an associative array but you are trying to access its values using keys - $query_row [ 'product_name' ]. Rather use _fetch_array
There are lots of syntactical errors. There is a space between function name and list of parameters.
Don't use mysql_. They are deprecated (read: dead). Use PDO instead.
Related
I'm trying to bind the id from a row to the href output. that is getting a url something?id=*** in order to use $_GET and bring the id on the next page.
I need to be the id on the same row that is clicked on a table I'm displaying.
If I try to bind it by stating href=" wahtever?id=<php echo $row['id'] ?> the id will return as empty. If I use a loop it works but give me all the id's on the table.
I tried different solutions I found on internet like stating echo '<td> <a href="****?id='.$row['id'].' </a></td>' or making a new selection using php code on the href link... nothing seems to work.
I'm confused, how can I make a link on a table that will include the id of the clicked row?
My code looks like this now:
<td bgcolor="#FAB1CA"><a href="view_topic.php?id=<?php $sql="SELECT * FROM forum_question ORDER BY id DESC";
$result = mysqli_query($link, $sql);
while($rows = mysqli_fetch_assoc($result){
echo $rows['ID'] ; ?>">
Just to make it clearer, it is a simple table displaying 4 columns with different data using a loop, the first column is the id and the second one would be the topic, where I trying to build the links.
It sounds like you have 5 columns in a database table and you want to show them on the page, and link the topic cell to the topic page and pass the id of that topic.
I cleaned your code up a little and gave an example of how to do that. Keep in mind, I'm using an associative array so you'll need to be sure it matches what the columns are called in your database.
<table>
<tr>
<th>ID</th>
<th>Topic</th>
<th>Answers</th>
<th>Views</th>
<th>Date</th>
</tr>
<?php
$sql="SELECT * FROM forum_question ORDER BY id DESC";
$result = mysqli_query($link, $sql);
while($row = myslqi_fetch_assoc($result)) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td bgcolor="#FAB1CA">
<a href="view_topic.php?id=<?php echo $row['id']; ?>">
<?php echo $row['topic']; ?>
</a>
</td>
<td><?php echo $row['answers']; ?></td>
<td><?php echo $row['views']; ?></td>
<td><?php echo $row['theDate']; ?></td>
</tr>
<?php endwhile; ?>
</table>
I cant see $row variable in your code
you can use myslqi_fetch_assoc for get $row variable
i think this answer its true
<?php
$sql="SELECT * FROM forum_question ORDER BY id DESC";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result)){
?>
<td bgcolor="#FAB1CA"><a href="view_topic.php?id=<?php echo $row['id']?>go to view_topic</a></td>
<?php
}
?>
I want to create a PHP page to display the results of a query in a MySQL database under the format of a table. By spending quite some time on different forums, I ended with something that is somehow satisfying me but that is strongly affecting the design and the layout of my webpage. Due to the fact that I wrote the code by a test-fail strategy, it is far from being straightforward and I am sure it is possible to shorten and simplify it and, therefore, make it more compatible with the format of my webpage. Could anybody have a look at it and give some suggestions of general interest about how to solve this kind of issues?
<div id="main">
<?php
require_once('../mysqli_connect.php');
$response = $db->query("SELECT * FROM metabolite");
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">
<tr><td align="center"><b>Metabolites</b></td>
<td align="center"><b>KEGG Id</b></td>
<td align="center"><b>Synonyms</b></td></tr>';
while ($data = $response->fetch())
{
?>
<tr><td align="left">
<?php echo $data['Metabolite_name']; ?></td>
<td align="left">
KEGG: <?php echo $data['Synonyms']; ?></td>
<td align="left">
<?php echo $data['Synonyms']; ?></td>
</tr>
<?php
}
$response->closeCursor();
?>
</div>
I thank you in advance for all your effort and your help.
Tom.
There's no way we can improve the design and layout of your webpage with the code you've given us. What I can do is write 'better' readable code.
<?php
function tableCell($content)
{
echo '<td align="left">'.$content.'</td>';
}
// database access
require_once('../mysqli_connect.php');
// get all records from the metabolite table
$response = $db->query("SELECT * FROM metabolite");
// start main division
echo '<div id="main">';
// start the table
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">';
// walk through all the metabolite records
while ($data = $response->fetch())
{
// start a row
echo '<tr>';
// create the cells
tableCell($data['Metabolite_name']);
tableCell('KEGG: '.$data['Synonyms']);
tableCell($data['Synonyms']);
// finish a row
echo '</tr>';
}
// close the table
echo '</table>';
// close main division
echo '</div>';
// close query
$response->closeCursor();
But this is not worth much, the output should remain the same.
if ($response->num_rows > 0) {
while($data = $response->fetch_assoc()) {
echo "<tr><td>" . $data["Metabolite_name"]. "</td></tr>" . ;
}
}
else {
echo "0 results";
}
Im sorry if this has been answered before but I am new to PHP and MySQL and I can't figure this out.
Pretty much every time I alter my code to include an array I get a fatal error. What I am trying to do is display all the data in 3 columns from my table.
I have my site set up where you log in and I store that user's name as a "code" in a session. I have a table that has multiple user form entries that are differentiated by the user's code because in my form, I grab the code as a hidden field and add it to the entry in the table.
So far I have been able to isolate those entries by the users code, in one column I have the sum of all of the user's numerical data and I am able to echo this as a total.
I want the other 3 columns to display all the values in their columns and for each value have a line break in between them. And I am trying to print or echo these results in specific parts on a confirmation page.
I have seen examples with PDO using fetch_all and other examples of storing arrays but I can't seem to figure it out with my existing code.
Here is my existing code:
<?php
$user = *****;
$pass = *****;
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
$stmt = $dbh->prepare("SELECT sum(price),part_number,location,price FROM products WHERE code = :usercode");
$stmt->bindParam(':usercode', $_SESSION['MM_Username']);
if ($stmt->execute()) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
And here is where I want to display the results:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
</tbody>
</table>
Try like this:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><? echo $user['part_number']; ?></td><!--all column values-->
<td><? echo $user['location']; ?></td><!--all column values-->
<td><? echo $user['price']; ?></td><!--all column values-->
<td><? echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
There are a few things in your question that jumped out at me.
It looks like you're attempting to display both raw data (each row) and aggregate data (the sum of prices). It can be simpler to fetch the information separately instead of in the same request.
You had mentioned fetch_all in PDO, but the method is fetchAll.
Instead of working with PDO within the HTML (like iterating through while calling fetch), write code so that you're simply iterating over an array.
Based on your description of the problem, it sounds like you want to separate the total price from the raw data, so you can reduce your table down to three columns and use the table footer to show the total price.
Based on those, I have the following solution that
Separates the calls to get data into descriptive functions
Use money_format to better display prices
Removes any database-specific manipulation from the view itself.
<?php
function getTotalPriceForUser(PDO $database_handler, $user_code)
{
// If no rows are returned, COALESCE is used so that we can specify a default
// value. In this particular case, if there aren't any products that would
// match, we'd still get a result with a value of 0.
$sql = 'SELECT COALESCE(SUM(price), 0) FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// This fetches the first row of the result; the result is given as an array with numerical keys.
$result = $stmt->fetch(PDO::FETCH_NUM);
// [0] refers to the first column
return $result[0];
}
function getProductsForUser(PDO $database_handler, $user_code)
{
$sql = 'SELECT part_number, location, price FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// fetchAll returns all rows, with each row being an associative array (where part_number, location and price are the keys)
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Set up the database information
$user = '*****';
$pass = '*****';
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
// money_format to use the below money formatting; this makes sure there's a dollar sign to represent USD, for example
setlocale(LC_MONETARY, 'en_US.UTF-8');
// Store $_SESSION['MM_Username'] in a local variable
$user_code = $_SESSION['MM_Username'];
// Get the list of products associated with this user code
$products = getProductsForUser($dbh, $user_code);
// Get the total cost of the products
$total_cost = getTotalPriceForUser($dbh, $user_code);
?>
<table style="margin:0 auto;" cellspacing="7" width="100%">
<thead>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Cost</th>
</tr>
</thead>
<tfoot>
<tr>
<td style="text-align: right" colspan="2">Total:</td>
<td style="text-align: right; border-top: 1px solid #999"><?= money_format('%.2n', $total_cost) ?></td>
</tr>
</tfoot>
<tbody>
<?php foreach($products as $product): ?>
<tr>
<td><?= $product['part_number'] ?></td>
<td><?= $product['location'] ?></td>
<td style="text-align: right"><?= money_format('%.2n', $product['price']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Change to this
<? echo
to
<?php echo
Try this:
...
$keys = array_keys($user);
foreach ($keys as $k) :
?>
<td><?= $user[$k]?></td>
<?php endforeach?>
<table>
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
I am working on a basic ecommerce website using PHP/MYSQL. I just need to know how I can upload multiple images for a product and then display them in the products page.
as for uploading multiple images, I don't want to use uploadify or open source codes like that. i rather have 3-4 extra fileupload fields if possible at all!
And I cannot get my head around the displaying the images (multiple images for 1 product). I really don't understand how it should work! so any advice on simple terms would be appreciated.
Currently I can only upload 1 image per product.
Here is what I have so far, please ignore the mysql queries in the first file as this is a not going live yet until I have converted the mysql to mysqli. Just need to get functions sorted first:
upload.php
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {
$product_name = mysql_real_escape_string($_POST['product_name']);
$price = mysql_real_escape_string($_POST['price']);
$quantity = mysql_real_escape_string($_POST['quantity']);
$category = mysql_real_escape_string($_POST['category']);
$details = mysql_real_escape_string($_POST['details']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT id FROM products WHERE product_name='$product_name' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
$sql = mysql_query("INSERT INTO products (product_name, price, quantity, details, category, date_added)
VALUES('$product_name','$price','$quantity','$details','$category',now())") or die (mysql_error());
$pid = mysql_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: add.php");
exit();
}
?>
product.php <<< this is the page that displays the product details and image.
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
include "config/connect.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = "SELECT * FROM products WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$quantity = $row["quantity"];
$category = $row["category"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
<table width="900" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="300" rowspan="5" align="right" valign="top" style="padding-top:10px;"><img src="inventory_images/<?php echo $id; ?>.jpg" width="300" height="450" alt="<?php echo $product_name; ?>" /></td>
<td width="126" height="106"> </td>
<td width="274"><h3 style="font-family:Times New Roman; font-size:1.8em;"><?php echo $product_name; ?></h3></td>
</tr>
<tr>
<td height="120"> </td>
<td><?php echo $details; ?></td>
</tr>
<tr>
<td height="110"> </td>
<td style="font-family:Times New Roman; font-size:1.8em;">Price: £<?php echo $price; ?></td>
</tr>
<tr>
<td height="50"> </td>
<td style="font-family:Times New Roman; font-size:1.8em;">Quantity Left: <?php echo $quantity; ?></td>
</tr>
</table>
Thanks
Well the way you are currently doing it isn't really setup for multiple photos since you aren't storing a reference to the photo in the database. You are simply renaming the image to the primary key of the product. So you will need to either do something like 1_1.jpg 1_2.jpg or you will need to create a database table that stores the filename and the product id so you can have a one to many relationship.
As for uploading more images just add more file inputs to your form.
And for displaying you will need to either pull records from the photo db table or use glob() to find all the files that start with the primary key + '_'.
Also FYI mysql functions should no longer be used as they are deprecated.
I'm creating a form where users can view and edit their account information and I'd like to streamline this as much as possible since there are a lot of form fields. I've selected all the customer's data without specifying the column names, but I'm having trouble displaying in the correct place in an HTML table without having to call each one individually.
I've used mysql_fetch_array in the code below, but it would be quite cumbersome to do for 300+ fields. I know that mysql_fetch_assoc can be used, but I haven't figured out how to then print in the correct place.
mysql_fetch_assoc (Pardon my ignorance, but I couldn't get this to work without using WHILE and FOREACH)
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $key=>$value){
echo "$key: $value<br />\n ";
}}
This works but requires specifying each field individually
<?php
//Database connection and Open database
require_once('config.php');
$result = mysql_query("SELECT customer_info.*, style.* FROM customer_info, style WHERE customer_info.user_id = style.user_id AND customer_info.user_id=$user_id ") or die(mysql_error());
$row = mysql_fetch_array($result );
?>
<table border="0" cellspacing="2" cellpadding="2">
<tr><td name="fname">First Name: <?php echo $row['fname']; ?></td>
<td name="lname">Last Name: <?php echo $row['lname']; ?></td>
<td name="email">Email: <?php echo $row['email']; ?></td>
<td name="colors_love">Colors Love: <?php echo $row['colors_love']; ?></td>
</tr></table>
Is there a way to essentially reverse the way I achieve this with my INSERT INTO code? if so, I'm assuming that will simplify my next task (allowing users to edit their information)
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.($value).'\',';
}
$result = mysql_query('INSERT INTO taste ('.$fieldlist.') VALUES ('.$vallist.')');
Leaving out the fact that using the mysql library is a terrible idea, you're actually most of the way there:
<table>
<?php while ($row = mysql_fetch_assoc($result)): ?>
<tr>
<?php foreach($row as $key=>$value) {
echo "<td>$key: $value</td>\n ";
} ?>
</tr>
<?php endwhile; ?>
</table>
You obviously would want to clean this up for a real form, since echoing db field names isn't exactly user-friendly.
kind of this?
<?php
//Database connection and Open database
require_once('config.php');
$result = mysql_query("SELECT customer_info.*, style.* FROM customer_info, style WHERE customer_info.user_id = style.user_id AND customer_info.user_id=$user_id ") or die(mysql_error());
$row = mysql_fetch_assoc($result );
?>
<table border="0" cellspacing="2" cellpadding="2">
<tr><?php foreach($row as $field => $content): ?>
<td><?php echo $field; ?>: <?php echo $content; ?></td>
<?php endforeach; ?></tr>
</table>