PHP - Giving Links To The Items In A Database
I have a php page where I have posts about different topic.
I have a menu listing all this categories of topics . Some topics may belong to more than one category. So when i click on a particular menu item, the topic belonging to that category will be displayed. While displaying it is in this format---Topic Heading,Belongs to which all categories,date posted and the description. All this are taken from database. Now my actual issue is I am not able to give links to the categories dispalyed ,if the category exceeds more than 1. For eg: Global Warming Posted on March 11,2011 in News, Issue -----------description of global warming goes here. In the above eg: News and issue are the two categories,when i click on News it should display all the items in news category,and when i click on issue it should display all items of issue category. But I am not able to give this link to the categories. Code: [Select] while($row = mysql_fetch_array($q)) { if($row[6]=='News'){ $c='<a href="category_disp.php?category=news">News</a>'; } if($row[6]=='Issues'){ $c='<a href="category_disp.php?category=issues">Issues</a>'; } echo "<tr><td><p >$row[1]</p><br></td></tr>"; echo "<tr><td> <div >". "<p><span>$row[4]</span> <span>". "<a href='$row[6]' >$row[6]|<a href='$row[5]'> Post Comments</a></span></p>". "<p> </p></div><br></td></tr>"; echo "<tr><td><p >$row[2]</p><br></td></tr>"; echo "<tr><td><p ><a href='$row[3]' >Click Here to read more...</a></p></td></tr>"; echo "</div></td></tr>"; } echo" </table> Similar TutorialsI have a webpage where all the database items are displyes in a table format.The table also has a check box.Upon clicking the delete button i need to delete all the items whish has the checkbox checked. How will i do that Hey guys, I am just wondering what method is used to give my PHP loop lists there own page based on the same template for each one.
A perfect example of this is eBay, if you look at the listing pages they then link to the actual product pages. I am just wondering how I can do this?
Here is my code setup:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC)) { echo ' <div class="listing-container"> <h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3> <h3 class="price-listing">£'.number_format($row['Price']).'</h3> </div> <div class="listing-container-spec"> <img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/> <div class="ul-listing-container"> <ul class="overwrite-btstrp-ul"> <li class="diesel-svg list-svg">'.$row["FuelType"].'</li> <li class="saloon-svg list-svg">'.$row["Bodytype"].'</li> <li class="gear-svg list-svg">'.$row["Transmission"].'</li> <li class="color-svg list-svg">'.$row["Colour"].'</li> </ul> </div> <ul class="overwrite-btstrp-ul other-specs-ul h4-style"> <li>Mileage: '.number_format($row["Mileage"]).'</li> <li>Engine size: '.$row["EngineSize"].'cc</li> </ul> <button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked </button> <button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details </button> <button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive </button> <h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4> </div> '; } ?> </div>So as you can see I am using PDO to fetch this data from my database and sort the results to list every row of the SQL table into the HTML template I have made and is then looped. My question is how can I give each row in my SQL table it's own page just like the eBay example I mentioned? Does anyone know of any useful tutorials to achieve this or any examples of how this is done? Thanks I am trying to do something like this but the code I have doesn't seem to do what I want... Code: [Select] <?php while($item_rows = mysql_fetch_array($item_result)) { $output = " <tr bgcolor=\"#000000\"> <td align=\"center\"><p><img src=\"../images/".$item_rows['item_id'].".gif\" width=\"45\" height=\"45\" /></p> <p>".$item_rows['name']."<br /> Attack: +".$item_rows['attack']."<br /> <img src=\"../images/credit.gif\" width=\"17\" height=\"17\" />$".$item_rows['sell_price']."</p> <p>[Equipt|Destory]<br /> </p> </td>"; $remainder = $i % 5; echo ($remainder == 0 ? ($i == 0 ? "" : "\n</tr>")."\n$output " : $output); } $colspan = (4 - $remainder); $last_row = $colspan ? " <td ".($colspan? "colspan=$colspan" : "")."></td>" : ""; echo $last_row. " </tr> </table>"; ?> I want to retrieve items from the DB and seperate them using a comma... while i know how to actually do that, what i want is to automatically have stop adding comas at the last item... so if there are 4 items i want it to show a comma after each item except the last one (1, 2, 3, 4). Does anyone know of a function or can give me an example on how i can do this. I'm trying to make it so that someone can add an item to the shop based upon the current items within the database. How do I go about doing that? I know i have to change <input> to <select>, but beyond that, how do I code it so I can run an array to get all the current items from the table `items` and list them by their `name` field? Thanks in advance! Here is what I have so far: function addshopinv($id) { error_reporting(E_ALL); ini_set('display_errors', 1); if (isset($_POST["submit"])) { extract($_POST); $errors = 0; $errorlist = ""; if ($name == "") { $errors++; $errorlist .= "Name is required.<br />"; } else if ($errors == 0) { $dbh=dbconnect() or die ("Userlist read error: " . mysql_error()."<br>"); mysql_select_db("XXX"); $query = mysql_query("SELECT id FROM items WHERE name='$name'"); while ($result = mysql_fetch_array($query)){ $item_id = $result['id']; $query1 = mysql_query("INSERT INTO sale SET shop_id='$id', item_id='$item_id'"); } admindisplay("Inventory Item Added.","Add New Inventory Item"); } else { admindisplay("<b>Errors:</b><br /><div style=\"color:red;\">$errorlist</div><br />Please go back and try again.", "Add New Item to Shop"); } } $page = <<<END <b><u>Add New Inventory Item</u></b><br /><br /> <form action="admin_panel.php?do=addshopinv:$id" method="post"> <table width="90%"> <tr><td width="20%">Name:</td><td><input type="text" name="name" size="30" maxlength="255" value="" />*255 character max</td></tr> </table> <input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /> </form> END; $page = parsetemplate($page, $row); admindisplay($page, "Add New Inventory Item"); } I coded the following but some parts are not working (the "curveball" mentioned at the end). How would YOU do this? I have a page (A) displaying a form with a textarea field using a WYSIWYG interface. The user will enter a list of unordered items and upon submit the string will look something like this: This is my list of food items: <ul> <li> Lettuce </li> <li> Tomatoes </li> <li> Eggs </li> <ul> Upon submit, I need to give each list item an unique id and store this id along with the text next to it in a separate table: List_item_id List_item_text List_item_state food_1 Lettuce food_2 Tomatoes food_3 Eggs The user will then land in another page with a form displaying the list. The text is now in the page itself and not in a textarea. Instead of the bullets a dropdown list appears, and the user can select "buy" or "sell" for each list item. This page (B) looks something like this: <form> This is my list of food items: <br><select name="food_1"> <option value="buy">Buy</option> <option value="sell">Sell</option> </select> Lettuce <br><select name="food_2"> <option value="buy">Buy</option> <option value="sell">Sell</option> </select> Tomatoes <br><select name="food_2"> <option value="buy">Buy</option> <option value="sell">Sell</option> </select> Eggs <input type=submit value="submit"> </form> When the user hits "submit" the table with the list items will be updated with the values selected in the dropdown list: List_item_id List_item_text List_item_state food_1 Lettuce Buy food_2 Tomatoes Buy food_3 Eggs Sell The next time the user goes to Page B the list will remember the states. Here's the curveball: At any point the user may click on "EDIT LIST" on Page B so they may add more items (at the begining, middle or end of the string). On edit mode the list items should appear as bullets again inside the WYSIWYG interface. Keep in mind that some of the text in the string may not be a list item (ie, "this is my list of food...") Hi, What I'm trying to do is create a script that generates a random list of cars whenever it is run. I have a list of available cars in a MySQL database. I'm just not sure how to get php to generate a list of, say, 20 cars, that are randomly picked from the cars in the database. I may also want to add other statistics like MPG (also already in the database). Can anyone show me how to do this? And is it possible to format the returned data in a table or div format? Thanks in advance Unk This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=334480.0 I've been playing around with this code from http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart Objective: I'm trying to make the scripts work but without pulling the data from MySQL Database. Instead, I created an array and inserted some info there and trying to replicate the same results but getting confused. For example, on the Index.php file, I made the following changes: <?php // Start the session session_start(); // Include functions require_once('inc/functions.inc.php'); // Products multidimensional Array $products = array("book" => array( 'id' => '1', 'title' => 'Learn Your ABC\'s', 'author' => 'John Doe', 'price' => '14.95'), "video" => array('id' => '2', 'title' => 'Visual Guide to learn', 'author' => 'Adam Smith', 'price' => '21.38'), "puzzle" => array('id' => '3', 'title' => 'Can You Solve?', 'author' => 'Sara Brown', 'price' => '9.41'), "exam" => array('id' => '4', 'title' => 'Test Your Knowledge', 'author' => 'Kim Carver', 'price' => '11.15')); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php /* $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': $'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); */ ?> <?php $output[] = '<ul>'; foreach ($products as $product => $product_item) { // $flavor is the key and $piece is the value foreach ($product_item as $item => $piece) { if ($item == "id") { # Conditional logic defined to map specific keys to specified name value $row['id'] = $piece; // echo "The id is ". $id."<br />"; // set just to confirm value correct for variable } elseif ($item == "title") { # Conditional logic defined to map 1st key to price value $row['title'] = $piece; // echo "The title is ". $title."<br />"; // set just to confirm value correct for variable } elseif ($item == "author") { # Conditional logic defined to map 1st key to price value $row['author'] = $piece; // echo "The author is ". $author."<br />"; // set just to confirm value correct for variable } elseif ($item == "price") { # Conditional logic defined to map 1st key to shipping value $row['price'] = $piece; // echo "Price: ". $price."<br /><br />"; // set just to confirm value correct for variable } $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': $'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; $output[] = '</ul>'; echo join('',$output); } } ?> </div> </body> </html> And here's the original index.php before my edits which show the sql query to the db: <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo &#0183; Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': £'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); ?> </div> </body> </html> Also, I included the zipped file of the entire script setup. Again, I'm trying to figure out how to make the cart work with using an array for the product instead of MySQL database. My goal is to remove ALL SQL statements from the scripts but stuck with the looping portion to display the title, author, and price from the array as shown above. hello, i am hoping someone can help, i have a form that has a body and title fields and then sends to this function below. it all works fine, but when i add a image or a link it stores it in the text field of the db like this: <IMG alt=\"\" src=\"/public/images/231781538234094.jpg\" width=796></P> this is what it should be /public/images/231781538234094.jpg so when i view the image it doesent show it and i right click the image and goto image properties and i get this: http://test.cyberglide.co.uk/%22public/images/231781538234094.jpg/%22 Code: [Select] function content_update() { $title = mysql_real_escape_string($_POST['title']); $body = mysql_real_escape_string($_POST['body']); $page = mysql_real_escape_string($_POST['page']); $location = mysql_real_escape_string($_POST['location']); $id = mysql_real_escape_string($_POST['id']); $sql = "UPDATE content SET title = '$title', body = '$body', page = '$page', location = '$location' WHERE id = '$id'"; $res = mysql_query($sql) or die(mysql_error()); echo "<script>window.location='content.php'</script>"; } if i manually edit it on the db it works fine please help, many thanks. Hi there I've been working with some code to display a single record on page. This all works fine and I'm able to pull what I want from the database. My problems is trying to use that data and turning it into something else like a link. I have a field in the database called image url which contains rows of image urls. So here is the problem area of the code: Code: [Select] <?php //////Displaying Data///////////// $id=$_GET['id']; // Collecting data from query string if(!is_numeric($id)){ // Checking data it is a number or not echo "Data Error"; exit; } $fetch=mysql_query("select * from productfeeds where ProductID=$id "); $row=mysql_fetch_object($fetch); echo mysql_error(); echo "<table>"; echo " <tr><td><b>ProductID</b></td><td>$row->ProductID</td></tr> <tr><td><b>ProductName</b></td><td>$row->ProductName</td></tr> <tr><td><b>ProductPrice</b></td><td>$row->ProductPrice</td></tr> //problem area for me <tr><td><b>Image</b></td><td>$row->ImageURL</td></tr> echo "</table>"; I'm trying to edit this part of the code: <tr><td><b>Image</b></td><td>$row->ImageURL</td></tr> I've tried this: <tr><td><b>Image</b></td><td><a href='{$row['URL']}'> <img src='{$row['ImageURL']}'></a> and <tr><td><b>Image</b></td><td><a href='$row['URL']'> <img src='$row['ImageURL']'></a> //removed brackets but I'm just getting errors. Can you guys help please? Thank you very much. Hello to all phpfreaks out there I need help with sorting some database columns. I ve been searching all day but i didnt found something nice to implement (or my mind is too tired to think right at this specific time) I have a table and inside it i display a picture and some other data.Above the table i inserted a div and inside it i have 5 links which when clicking on them i want to change the display order of the data being displayed in the table, and if clicked again to change again the state for ASC to DESC and so on... Is there any short solution that do the trick? With an array maybe? PS:I have also a pagination which i would like to keep the sorted order from the above table so not to mess around with the results. Thanks in advance Hello Everyone, I am working on a project where I have to go in and grab the names of the fields in a table. I got it to work and for it to show me the field names but it also displays a lot more than what I would like for it to do. I keep getting the following error. It is repeated over my screen like 15 times. Quote Warning: mysql_field_name() [function.mysql-field-name]: Field 5 is invalid for MySQL result index 7 in C:\xampp\htdocs\CMS\admin\includes\get_table.php on line 44 This is the section of code that it is referring to. Line 44 is Quote $tablecolumn .= "<p>" . mysql_field_name($fieldnamesquery_result, $table_field) . "<input type='text' name='" . mysql_field_name($fieldnamesquery_result, $table_field) . "' id='" . mysql_field_name($fieldnamesquery_result, $table_field) . "'/>"; Code: [Select] $tablecolumn = "<form name='insert_table' id='insert_table' action='get_database.php' method='post' > <fieldset> <legend>table information</legend>"; for ($table_field = 2; $table_field < $fieldnamesquery_result; $table_field++) { $tablecolumn .= "<p>" . mysql_field_name($fieldnamesquery_result, $table_field) . "<input type='text' name='" . mysql_field_name($fieldnamesquery_result, $table_field) . "' id='" . mysql_field_name($fieldnamesquery_result, $table_field) . "'/>"; <-----This is line 44 } $tablecolumn .= " <p> <input type='submit' name='submit_info' id='submit_info' /> </p> </fieldset> </form> "; echo $tablecolumn; Hello everyone. I am wondering how can i give different id's to a html form? Code: [Select] <?php ... if ($numrows!=0) { // fetching data from the database to variable while ($row = mysql_fetch_assoc($query)) { $view_jam = $row['jamname']; $view_recipe = $row['jamrecipe']; $view_rating = $row['jamrate']; $view_owner = $row['owner']; $view_comments = $row['comments']; $view_count = $row['count']; $view_id = $row['id']; $view_count2 = $row['count2']; echo "Jam name: <b>" . $view_jam . "</b><br />"; echo "Jam recipe: " . $view_recipe . "<br />"; echo "Owner: " . $view_owner . "<br />"; echo "Comments: " . $view_comments . "<br />"; echo "Jam Rating: " . $view_rating . "<br />"; [b]echo '<form action="main.php?id=jams" method="POST">[/b] Choose rating <input type="text" name="jamrate" /> <input type="submit" name="submit1" value="Rate"> </form><br /><br />'; ... ?>As you can see, the form is inside a loop. I am trying to build a rating system. When there is only one row in a database then everything goes smoothly, but if there are more, then the rating applies to all rows. I suppose i need to give different id's to the form. How? Thank you Code: [Select] $Rep = htmlspecialchars($_GET["Rep"]); echo $Rep; The above will print "John Doe & Assoc." (without the quotes) Code: [Select] $result = mysql_query("SELECT RepName FROM Reps WHERE Repname = '".$Rep."'"); $repcount = mysql_num_rows($result); echo $repcount; The above code prints "0" If I delete the first block of code and replace it with Code: [Select] $Rep = "John Doe & Assoc." The second block of code will then return a "1" as it should. Why is one returning a 0 and one returning a 1 when the text in $Rep appears to be identical in both cases? This problem only appears to be occurring when the $Rep value contains an &. All, I'm getting the following error when I work with a class: Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /webspace/httpdocs/offers/form_key.php on line 5 The complete code for this is class is: <?php class Form_Key { protected $oldKey; public function __construct() { // Ensure we have an available session if ( NULL == session_id() ) { session_start(); } // Grab our former key for validation if ( isset( $_SESSION['form_key'] ) ) { $this->oldKey = $_SESSION['form_key']; } // Assign the new key $_SESSION['form_key'] = md5( uniqid( mt_rand(), TRUE ) ); } public function isValid() { return 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_POST['form_key'] ) && '' != trim( $_POST['form_key'] ) && '' != trim( $this->oldKey ) && $_POST['form_key'] === $this->oldKey; } public function getKey() { return $_SESSION['form_key']; } public function getOldKey() { return $this->oldKey; } public function render() { return '<input type="hidden" name="form_key" value="' . $_SESSION['form_key'] . '" />'; } public function __toString() { return $this->render(); } } ?> The line that is giving the issue is this line: protected $oldKey; Is it ok just to remove this line?? If I comment it out it gives me the same message but for line 7, which is this one: public function __construct() Anyone have any ideas? Thanks in advance. What I can Do: Code: [Select] function createDir($path = '/path/to/root/') What I Need To Do: Something like this Code: [Select] $server_root = $_SERVER['DOCUMENT_ROOT']; function createDir($path = $server_root) Or This Code: [Select] function createDir($path = $_SERVER['DOCUMENT_ROOT']) My code looks as follows: include('connectvars.php'); /* REGISTER FORM */ // check if submit button has been clicked if (isset($_POST['submit_signup'])) { // process and assign variables after post submit button has been clicked $user_email = strip_tags(trim($_POST['email'])); $firstname = strip_tags(trim($_POST['firstname'])); $lastname = strip_tags(trim($_POST['lastname'])); $nickname = strip_tags(trim($_POST['nickname'])); $password = $_POST['password']; $repassword = $_POST['repassword']; $dob = $_POST['dob']; $find_us_question = strip_tags(trim($_POST['find_us_question'])); // connect to database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $check_query = "SELECT * FROM users WHERE nickname = '$nickname'"; $check_connect = mysqli_query($dbc, $check_query); $check_count = mysqli_num_rows($check_connect); echo $check_count; die(); It's a register (sign up) page, and it's the beginning of the script, the rest of the script is just checking if all fields are a empty and if the input is in the allowed character length etc. I could it off at die(); because the rest doesn't matter. I want the script to check if the username already exists in the database, so I want mysqli_num_rows to tell me how many rows are already there with the same username, and then I want to continue doing an if statement saying if ($check_count != 0) { echo "Username already exists!" } But the mysqli_num_rows doesn't even print out how many rows there are availible, it gives me an error saying: Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in... The num_rows function worked in the login script the same way, but for some reason it's not working in the register script. Any ideas, what I'm doing wrong? For testing purposes I just want it to print me "1" when I'm entering a username that's already in the database. Hi all, Here's the code I'm using, after opening an IMAP stream to an inbox. The code previous to this opens the inbox, grabs the emails and iterates through them. This bit is checking an individual mail for attachments. Code: [Select] <?php $structure = imap_fetchstructure($mbox, $email_number); $parts = $structure->parts; $fpos=2; for($i = 1; $i < count($parts); $i++) { $message["pid"][$i] = ($i); $part = $parts[$i]; if($part->disposition == 'ATTACHMENT') { // Save the attachment locally to the server // Find the file extension // Save the attachment to DB code here $fpos+=1; } } ?> When I run the script, I get a load of the following reply: Notice: Undefined property: stdClass::$parts in /var/www/html/site/public_html/cron/cron_email_import.php on line XXX Would this mean that there are no actual attachments in the email being processed? Has anyone ever dealt with this function before? All input appreciated. WoolyG |