PHP - Storing And Retrieving Php Code In Mysql Database
I am working on a kind of CMS for my own website which no one else will be using but me as a way of improving my php skills, and am having problems with retrieving data from the database that holds both text and php code. I have searched the web and found that i should be using eval() for the code to be executed before it is send to the browser but cannot get it to work and can't find my mistake(s).
the php code will always be the same, and is supposed to retrieve the id number of a page to use in a link (and works fine when tested by loading the code directly without retrieving it from the database) this is an example of data stored in the database Code: [Select] The <a href="page_builder.php?id=<?php echo $page->id('mines_DwarvenMines') ?>">Dwarven Mines</a> have a great selection of Ores,... Of course when I leave it like this, hovering over the link in my page will show exactly that and lead to nowhere Code: [Select] localhost/page_builder.php?id=<?php echo $page->id('mines_DwarvenMines') ?> Most of these links appear in tips given at the end of the page and are processed as followed Code: [Select] $questtips = $quest->getQuestTips(); $tips = ""; if ($questtips == "none") { $tips = "/"; } else { foreach($questtips as $tip) { $tips .= "<li>"; $tips .= $tip->getTip(); $tips .= "</li>"; } } and finally put on screen by the presentation layer as followed Code: [Select] <h2>Tips & Extra Info</h2> <div class="tipsList"> <ul> <?php echo $tips ?> </ul> </div> I have tried all sorts to get the code to be executed when retrieved from the database before being send to the browser so that this particular link would say "localhost/page_builder.php?id=57" but I cannot get it to work, though I suspect it is fairly easy. I suspect I would have to store the data in a different format in the database? And how exactly do I use the eval() function in my case? Could someone please adjust my code so that it does work? Thanks Similar TutorialsI need some help with this. A user fills out a form, one of the fields is a zip code field. I need to retrieve that value from MySQL store as a session var and set that value as a variable to use with a weather display API. The ID is being stored from the form page. Here is what I have so far, after the values are submitted into the DB. <?php session_start(); $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Profile WHERE id='{$_SESSION['id']}"); while ($row = mysql_fetch_assoc($result)) { $_SESSION['id'] = $row['id']; $_SESSION['zip'] = $row['zip']; } mysql_close($con); ?> and then for the weather API, I need to set the stored variable to something $zip = 'stored zip code value'; Basically i have a folder with 100+ images they are NOT all the same extension, what im wanting to do is use PHP to find all the images and put them all in a database. how would i go about doing this? thanks I've got an array like this: $firstquarter = array('January', 'February', 'March'); Then I'm adding it to a MySQL DB as follows: $insert = "INSERT INTO sometable (months) VALUES ('$firstquarter') "; $insertresult = mysql_query($insert) or die ('Error in Insert query: ' . mysql_error()); When I use PHPMyAdmin I see a this value stored in the DB: 'Array' Can I retrieve the values, by index, from this database field?? Hello everyone,
I have a card database and everything works perfectly besides one thing..
I can't store
'in my database via my form, i however do can store them into the database via PHPMyAdmin. I dont know what i've been doing wrong and it really bothers me. If any of you guys could help me out. Here's all the code you would need to find the issue. This is the form file <!doctype html> <html> <head> <meta charset="utf-8"> <title>Edit Page</title> </head> <body> <h1 align="center"> Add Cards</h1> <form action="insert.php" method="POST"> <input type="text" name="name" placeholder="Name" /> <input type="text" name="color" placeholder="Color" /> <input type="text" name="type" placeholder="Type" /> <input type="text" name="subtype" placeholder="Sub Type" /> <input type="text" name="power" placeholder="Power" /> <input type="text" name="toughness" placeholder="Toughness" /> <br> <input type="text" name="manacost" placeholder="Converted Mana Cost" /> <input type="text" name="rarity" placeholder="Rarity" /> <input type="text" name="expansion" placeholder="Expansion" /> <input type="text" name="foil" placeholder="Foil" /> <input type="text" name="stock" placeholder="Stock" /> <input type="submit" value="Save" /> </form> </body> </html>This inserts it into my database. <?php ($GLOBALS["___mysqli_ston"] = mysqli_connect("", "", "", , ))or die("cannot connect"); ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE e_industries"))or die("cannot select DB"); $name = $_POST['name']; $color = $_POST['color']; $type = $_POST['type']; $subtype = $_POST['subtype']; $power = $_POST['power']; $toughness = $_POST['toughness']; $manacost = $_POST['manacost']; $rarity = $_POST['rarity']; $expansion = $_POST['expansion']; $foil = $_POST['foil']; $stock = $_POST['stock']; $sql="INSERT INTO Osiris (Name, Color, Type, Subtype, Power, Toughness, Manacost, Rarity, Expansion, Foil, Stock) VALUES ('$name', '$color', '$type', '$subtype', '$power', '$toughness', '$manacost', '$rarity', '$expansion', '$foil', '$stock')"; $result=mysqli_query($GLOBALS["___mysqli_ston"], $sql); if($result){ echo "Successful"; echo "<BR>"; echo "<a href='add.html'>Back to main page</a>"; } else { echo "ERROR"; } ?>If anyone could help me out that would be great! Edited by OsirisElKeleni, 05 October 2014 - 12:29 PM. The subject could be a bit vague, but my problem is simple. (I think so) So I made a php test site that is quite similar to a forum. Where you see a title or a subject and when you click on it you will see more details about that subject. I made my database and script for inserting data into my mySQL database. I also did my output aswell, so every topic is posted on a webpage "archive" where you can see all the subjects. But now I want to see the full details of that type of subject by clicking on it. I have no idea how to make that happen googled it but didn't find any results...just wondering if it's even possible to do that. I'm a new guy here! i have a dictionary - THIS IS obviously a python dictionary an this has approx 8 000 lines with records [/CODE] $ python printer.py {'url': 'http://www.site1_com' 'cname': 'butcher', 'name': 'cheng', 'email': 'mail1@hotmail.com'} {'url': 'http://www.site2_com' 'cname': 'dilbert', 'name': 'James', 'email': 'mail2@hotmail.com'} [code=auto:0]i have a mysql-db up and runing in my opensuse there i have created a db with the fields url cname name i use the import MySQLdb i studied this documentation he http://stackoverflow...abase-in-python but i think this goes a bit over my head. - well how can i get the data ( in other words the dictionary) into the database? love to hear from you greetings helllo dear php-commmunity new to Ruby - i need some advices - i plan to do some requests in osm-files. (openstreetmap) Question - how can i store the results on a Database - eg mysql or - (if you prefer postgresql) - note: my favorite db - at least at the moment is mysql here the code require 'open-uri' require "net/http" require 'rexml/document' def query_overpass(object_type, left,bottom,right,top, key, value) base_url = "http://www.overpass-api.de/api/xapi?" query_string = "#{object_type}[bbox=#{left},#{bottom},#{right},#{top}][#{key}=#{value}]" url = "#{base_url}#{URI.encode(query_string)}" resp = Net::HTTP.get_response(URI.parse(url)) data = resp.body return data end overpass_result = REXML::Document.new(query_overpass("node", 7.1,51.2,7.2,51.3,"amenity","restaurant|pub|ice_cream|food_court|fast_food|cafe|biergarten|bar|bakery|steak|pasta|pizza|sushi|asia|nightclub")) overpass_result.elements.each('osm/node') {|x| if !x.elements["tag[@k='name']"].nil? print x.elements["tag[@k='name']"].attributes["v"] end print " | " if !x.elements["tag[@k='addr:postcode']"].nil? print x.elements["tag[@k='addr:postcode']"].attributes["v"] print ", " end if !x.elements["tag[@k='addr:city']"].nil? print x.elements["tag[@k='addr:city']"].attributes["v"] print ", " end if !x.elements["tag[@k='addr:street']"].nil? print x.elements["tag[@k='addr:street']"].attributes["v"] print ", " end if !x.elements["tag[@k='addr:housenumber']"].nil? print x.elements["tag[@k='addr:housenumber']"].attributes["v"] end print " | " print x.attributes["lat"] print " | " print x.attributes["lon"] print " | " if !x.elements["tag[@k='website']"].nil? print x.elements["tag[@k='website']"].attributes["v"] end print " | " if !x.elements["tag[@k='amenity']"].nil? print x.elements["tag[@k='amenity']"].attributes["v"] print " | " end puts } look forward to hear from you again - i would love to store it on a mysql - database - if possible. If you would prefer postgresql - then i would takte this one.... ;-) look forward to hear from you again - i would love to store it on a mysql - database - if possible. If you would prefer postgresql - then i would takte this one.... ;-) well - i guess that the answer to this will be the same no matter what language we are using. If the db is a sql database we need to design the database schema and create the tables in the database. The first step in accessing a db in our code is to get a connection to it. If ruby is our choice of language, a search for "ruby sql connector" will give us lots of options to read about. Well - we also can do it in PHP. What do you think!? Next, based on the schema we have designed, we need to create queries suitable for storing the data. We will likely need to consider our transactional model. Again, searching "ruby sql transactional model" will give us plenty of food for thought. Finally, we may want or need to close the connection to the database. Hello all, I'm currently working on a project and it is the first time I have had to store/retrieve an array with PHP and MySQL. Basically its a website that has a list of discounts/coupons on it. People can register and submit their discounts and such. I am storing an array for who is eligible for the discount, as well as which categories the discount falls under. I did some googling and there seems to be tons of thoughts on the best way to do this. Some say to use implode/explode, some say to serialize/unserialize, I was just wondering if there is a common, concrete way to do this? I will need to be able to search the array for its contents. So if children are eligible for the discount, I need to be able to store that in a database, retrieve it later, and search it for only "Children" so I can display the discounts available only to children. If someone could please advise the best way to do this and post some examples, it would be greatly appreciated. I learn best with examples that are explained properly. Hi, just a very simple question: I have an array as follows: $langList = array('English', 'French', 'German', 'Dutch'); What's the easiest way to store this array in an external file, so that multiple php scripts can access its contents? And what is then the php line I need to retrieve the array from the external file? Thanks! I'm trying to use php code that is stored in the sql database, but It doesn't seem to be executing the code. when I see the page source, its there but the server is not executing the command how do I accomplish this. Here is a simple code snippet to show what I am trying to do. $result = mysql_query("select * from data"); $row = mysql_fetch_array($result); echo $row['code']; In the code field in data table this is whats there. <?php echo "testing."; ?> the below code as I understand should insert a new record into my database, but it's not. <?php $notes = $_POST['notes']; $cnamedb = $_POST['cname']; $username = $_SESSION['username']; mysql_query("INSERT INTO `ccccomma_eve`.`corps` (`id`, `name`, `ticker`, `alliance`, `ceo`, `tax`, `members`, `hq`, `apidate`, `notes`, `notedate`, `updatedby`) VALUES ('', '$cnamedb', '', '', '', '', '', '', '', '$notes', NOW(), '$username'"); echo $cnamedb." Updated"; ?> Any ideas why? Hi! I was wondering if there is a way to execute php code which is stored in mysql database using php. At the minute I am using a echo to try and run php code stored in a mysql database but this just displays the code and does not run the php code. Thanks for any help! Code: [Select] <?php require "db/config.php"; $fname = $_POST['fname']; $lname = $_POST['lname']; $country = $_POST['country']; $state = $_POST['state']; $city = $_POST['city']; $zcode = $_POST['zcode']; $address = $_POST['address']; $ppemail = $_POST['ppemail']; $pnumber = $_POST['pnumber']; $cemail = $_POST['cemail']; $url = $_POST['url']; $price = "$5.00"; $query = "INSERT INTO custpackage1000( id, FirstName, LastName, Country, State, City, ZipCode, Address, PayPalEmail, PhoneNumber, PrimaryEmail, WebsiteURL) VALUES ( '1', '$fname', '$lname', '$country', '$state', '$city', '$zcode', '$ppemail', '$pnumber', '$cemail', '$url')"; mysql_connect($host, $user, $pass) or die("<br /><br /><h1>Fatal error. Please contact support if this persists.</h1>"); mysql_select_db($dbname); mysql_query($query) or die ("could not open db".mysql_error()); sleep(2); ?> Why won't the code insert into my database upon submission of data? What am I doing wrong? Code: [Select] $query = mysql_query("SELECT a.*, b.* FROM friendlist a INNER JOIN friendlist b ON (a.friendemail=b.friendemail) INNER JOIN users c ON (b.friendemail = c.EmailAddress) WHERE a.email = 'asdf@gmail.com' AND c.Username LIKE '%carol%' GROUP BY a.id ORDER BY count(*) DESC"); Code: [Select] while ($showfriends = mysql_fetch_array($query)) { echo $showfriends['Username']; } and I would get nothing. It produces the correct number of <div> so i know it's getting through, but it's having trouble displaying the entries? 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. Hey all, I've written a php search feature for a mysql database. The search returns a file name like sample.gif, how would I go about displaying the actual image instead? Since the images all have the same location could I have the search return the string into a variable then make the whole thing a link? Thanks. I have my database set to insert the current time stamp when an entry is made into the table, I am then trying to retrieve via the following code: $select_view_idea="SELECT * FROM $tbl_name5 WHERE message_number='$message_number'"; $result_view_idea=mysql_query($select_view_idea); while($row_view_idea=mysql_fetch_assoc($result_view_idea)){ extract($row_view_idea); } date_default_timezone_set('US/Eastern'); $date=date('l, F jS Y h:i:s A T', $date); echo $date; The above is outputting: Wednesday, December 31st 1969 07:33:31 PM EST the database contains: 2011-11-18 00:47:56 I have two tables. Table Name:Users Fields: User_name user_email user_level pwd 2.Reference Fields: refid username origin destination user_name in the users table and the username field in reference fields are common fields. There is user order form.whenever an user places an order, refid field in reference table will be updated.So the user will be provided with an refid Steps: 1.User needs to log in with a valid user id and pwd 2.Once logged in, there will be search, where the user will input the refid which has been provided to him during the time of order placement. 3.Now User is able to view all the details for any refid 3.Up to this we have completed. Query: Now we need to retrieve the details based on the user logged in. For eg: user 'USER A' has been provided with the referenceid '1234' during the time of order placement user 'USER B' has been provided with the referenceid '2468' during the time of order placement When the userA login and enter the refid as '2468' he should not get any details.He should get details only for the reference ids which is assigned to him. |