PHP - Is A Way To Execute Php Code Which Is Stored In Mysql Database?
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! Similar TutorialsHi Guys, I have a webpage which has subsequent pages stored in a database e.g. index.php?id=1 The problem being, is that id=1 has it's data pulled from a database. This was fine & dandy until I started to insert PHP...I am trying to get the below to executre <?php $rater_id=1; $rater_item_name='Rate This'; include("rater.php");?> However nothing shows & nothing happens, I know eval can be used but have not been succesfull in implementing this, can someone please help! How can I run php code that is stored in a database? I have my pages created by grabbing the contents of a pageBody mySQL table cell, but some pages require further php to be able to display correctly. For example, I have a players page, which will list all players, and some information about them. The players and information is all saved in a players table in my database (separate to the pages table where pageBody is stored). I use simple php to grab all the players and format all of their information so it can be displayed on the page. This is the flow of information that I would like: User clicks on players page browser loads content page (this is a template page), and grabs the pageid from $_GET browser then reads pages table in database to get the pageBody associated with the pageid The pageBody will contain more php, which will run the players script to retrieve the list, and display Doing it the above way will make it much easier to extend the website to include more types of pages that has to run additional php scripts. The only way I can think of this working is by doing this: user clicks on players page browser loads content page, grabs pageid from $_GET browser checks the pageid for the one associated with players (hard coded into the php script) browser then loads the players.php script instead of going to the database This above way means that I will need to edit the index.php page everytime I add a new list type (example, coaches, volunteers etc). Anyone have any suggestions? I know my question is long, but I was finding it hard to explain it in an easy to understand way, but I'm still not sure if I have :S. Cheers Denno Hey guys, I have been banging my head against a wall here with this. I am saving my sessions in my database via session_set_save_handler(). So let me walk you through what I have here, what works, and what the issue seems to be. basically, the problem is the $_SESSION array is empty on page load. common.php: I have the open / close / read / write / destroy / and gc functions. These all work properly as when i use a session variable it stores into the database and i can see all of the information in there.. inside of common.php i have session_start().. I am positive that the session_start() is running becasue common.php is included into index.php and i tried adding session_start() to index.php again and i got an E_NOTICE saying the session already began. (yes, for the read function i am returning a string... i included that below). for the table itself, i have set the session_data as both text and blob, same issue with both. index.php: includes common.php. I know it's included as other aspects of the file are included and work properly. if i call var_dump($_SESSION) i get an empty array. and i prited out the session_id() and it matched my session id in the database. and the values that are stored in there are correct. i have for example: count|i:0 now with that value actually in the database and when calling session_id() and i get the ID that matches in the table. so i will get an E_NOTICE of an undefined index.. i was trying something like: if(!isset($_SESSION['count'])) $_SESSION['count'] = 0; else $_SESSION['count']++; echo $_SESSION['count']; Everytime the page is reloaded, count is reset to 0.. I can tell that it is reset to 0 as the expired time changes in the database after every load of the page (which is part of the write function). I double checked that it wasn't a problem for some reason with the ++ by adding in a variable that sets to 1 when in the if, and 0 if in the else, and it always outputs a 1. i have included here my read function since that apparently is the issue.. function sess_read($sess_id) { global $DB; $sql = "SELECT `session_data` FROM `sessions` WHERE session_id = '".$sess_id."' AND session_agent = '".$_SERVER["HTTP_USER_AGENT"]."' AND session_expire > '".time()."';"; $query = $DB->query($sql); if($DB->num_rows($query) > 0) { $r = $DB->fetch($query); return settype($r['session_data'], 'string'); } return ''; } I tried also with removing the agent and expire check to see if it was an issue there but same problem. I probably have missed something really dumb but i can't for the life of me figure it out and I have googled around for a similar issue. The actual output of the page is correct.. all of the HTML and CSS information loads properly.. no errors are reported (and i have E_ALL on). 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."; ?> I put together the following blocs of code for uploading pictures into a database and displaying them on a webpage. The pictures are supposed to be displayed on the member's only page of a website I'm working on, upon logging in, and they are supposed to be the member's uploaded picture. I created several members and and used one of my existing member accounts to test the uploading process. The picture upload process appeared to have been successful when I checked on myphpadmin. Yet, when I login with this account, no picture is displayed, instead, a tiny jpg icon is displayed at the top left corner of the box in which the picture was supposed to be displayed. Same thing when I login with the other accounts with which I haven't yet uploaded a picture. I'll start with the code that installs the table in the database $query = "CREATE TABLE images ( image_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , member_id INT UNSIGNED, like_id INT UNSIGNED, image LONGBLOB NOT NULL, image_name varchar(255) NOT NULL, image_type varchar(4) NOT NULL, image_size int(8) NOT NULL, image_cartegory VARCHAR(20) NOT NULL, image_path VARCHAR(300), image_date DATE )"; Then here is the code which allows the member to upload his pictu <form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer"> <input name="MAX_FILE_SIZE" value="102400" type="hidden"> <input name="image" accept="image/jpeg" type="file"> <input value="Submit" type="submit"> </form> And here is the insertimage.php which inserts the image into our database: Note that I have to authenticate the user in order to register his session id which is used later on in the select query to identify him and select the right image that corresponds to him. <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Make sure the user actually // selected and uploaded a file if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { // Temporary file name stored on the server $tmpName = $_FILES['image']['tmp_name']; // Read the file $fp = fopen($tmpName, 'r'); $data = fread($fp, filesize($tmpName)); $data = addslashes($data); fclose($fp); // Create the query and insert // into our database. $query = "INSERT INTO images (member_id, image_cartegory, image_date, image) VALUES ('{$_SESSION['id']}', 'main', NOW(), '$data')"; $results = mysql_query($query); // Print results print "Thank you, your file has been uploaded."; } else { print "No image selected/uploaded"; } // Close our MySQL Link mysql_close(); } //End of if statmemnt. ?> On the page which is supposed to display the image upon login in, I inserted the following html code in the div that's supposed to contain the image: <div id="image_box" style="float:left; background-color: #c0c0c0; height:150px; width:140px; border- color:#a0a0a0;border-style:outset;border-width:1px; margin:auto; "> <img src=picscript.php?imname=potwoods> </div> And finally, the picscript.php contained the select query: <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //include the config file require('config.php'); $image = stripslashes($_REQUEST[imname]); $rs = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND cartegoty = 'main' "); $row = mysql_fetch_assoc($rs); $imagebytes = $row[image]; header("Content-type: image/jpeg"); print $imagebytes; ?> Now the million dollar question is, "What is preventing the picture from getting displayed?" I know this is a very lengthy and laborious problem to follow but I'm sure there is someone out there who can point out where I'm not getting it. Thanks. Hi, I am trying to store a sql query in a database, but every time I try to read it, it shows all the code as text. eg just print ' . $parts_row['part_number'] . ' Here is the code on the page: $parts_sql = "SELECT * FROM parts WHERE part_cat = " . $category_row['cat_id'] . " ORDER BY CAST(part_a AS DECIMAL(10,2))"; $parts_result = mysql_query($parts_sql); if(!$parts_result) { echo '<tr><td>The parts could not be displayed, please try again later.</tr></td></table>'; } else { while($parts_row = mysql_fetch_array($parts_result)) { $pageformat_sql = "SELECT * FROM category_pages WHERE catpage_number = " . $category_row['cat_page'] . ""; $pageformat_result = mysql_query($pageformat_sql); if(!$pageformat_result) { echo 'Error'; } else { while($pageformat_row = mysql_fetch_assoc($pageformat_result)) { $data = $pageformat_row['catpage_table']; echo '<table class="table2 centre" style="width:750px"> ' . $pageformat_row['catpage_tabletitle'] . '' . $data . ''; } } }}And this is what is stored in the database table: <tr> <td class="cell left">' . $parts_row['part_number'] . '</td> <td class="cell centre">' . $parts_row['part_a'] . ' mm</td> <td class="cell centre">' . $parts_row['part_b'] . ' mm</td> <td class="cell centre">' . $parts_row['part_c'] . ' mm</td> <td class="cell centre">' . $parts_row['part_d'] . ' mm</td> <td class="cell centre">' . $parts_row['part_e'] . ' mm</td> <td class="cell centre">' . $parts_row['part_imped100'] . '</td> <td class="cell centre"><a href="datasheets/' . $parts_row['part_datasheet'] . '.pdf"><img border="0" src="images/pdf.jpg" alt="Download"</a></td></tr>I would be very grateful to anyone who can help me with this. Hi Everyone, I have a program that generates 200 unique images keeping the first image static in each run.The images keep scrolling on to the screen pause for 3 seconds and scroll off I'm able to generated all 200 unique images without repetition, everything is working well except for the lase two images the last two images are scrolling on to the screen but are not been displayed in the database, Moreover The last image is a duplicate of 197th image.I don't know what is happening..... Here is MY code.......... <?php session_start(); $sid = $_SESSION['id']; $_SESSION['imageDispCnt'] = 0; $myQuery = "SELECT * from image"; $conn = mysql_connect("localhost","User","Passwd"); mysql_select_db("database_Name",$conn); $result = mysql_query($myQuery); $img =Array(); $id =Array(); $i =0; $imagepath = 'http://localhost/images/'; while ($row = mysql_fetch_array($result)) { $img[$i] = $imagepath.$row['img_name']; $id[$i] = $row['imageid']; $i = $i + 1; } ?> </head> <script language="JavaScript1.2"> var scrollerwidth='800px'; var scrollerheight='600px'; var scrollerbgcolor='white'; var pausebetweenimages=3200; var s; var sec; var d; var j; var imgid; var milisec = 0; var seconds = 0; var flag = 1; var ses_id = '<?php echo $sid;?>'; var count = 0; var i = 0; var imgname; var imgid; var k =0; var slideimages=new Array(); var img_id = new Array(); var index; <?php $l =0; $count = array(); $j = rand(0,199); while($l < 200) { while(in_array($j, $count)) { $j = rand(0,199); } $count[$l] = $j; $l++; }?> <?php $k = 0; for($k = 0;$k<count($count);$k++){ ?> index = <?php echo $k;?>; <?php $indx = $count[$k];?> if(index == 0){ slideimages[0] = '<img src="http://localhost/images/hbag044.jpg" name="r_img" id="0"/>'; img_id[0] = '<input type="hidden" value="0" id="imgId" />'; } else if(index > 0) { slideimages[<?php echo $k?>] = '<img src="<?php echo $img[$indx]?>" name="r_img" id="<?php echo $id[$indx]?>"/>'; img_id[<?php echo $k?>] = '<input type="hidden" value="<?php echo $id[$indx]?>" id="imgId" />'; } <?php } ?> Can Any one plese help me Appreciate your help... Thanks this is the line in my script that I have to show the image: Code: [Select] $output .= "<img>{$row['disp_pic']}</img></br>\n"; As you can see I added the image tag, but it wont show the actual image. IE shows it as a small square with another small square picture icon in the middle of it (i'm sure you guys know what i mean). 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? Good afternoon all!! I have a very specific issue that, in my opinion, is quite complicated. In words, here is what I wish to achieve. I would like a page which displays users from the database. Each individual user has their own Div hidden below their name. Within this div, there is a form. The form is full of radio buttons. Once the user's name is clicked and form submitted, I wish to write the form data to the database for the specific user that was selected. See below example for better understanding: Dale Gibbs Chris Hansen Steve Jobs If I click Chris Hansen, the following happens Dale Gibbs ============== Chris Hansen HIDDEN DIV FORM CONTENT HIDDEN DIV FORM CONTENT HIDDEN DIV FORM CONTENT HIDDEN DIV FORM CONTENT HIDDEN DIV FORM CONTENT Submit Button ============== Steve Jobbs So as of now, the display is correct. I am seeing exactly what I want to see from my database. Also, my div IDs work just fine as well as the Javascript toggleSlidebox function. The only issue is for some reason, whenever I submit the form (no matter which user I select from my list), I can only write to the last inputted ID. So for example, if the last ID entered into the database was 6, then thats the only ID that will be returned when my form is submitted and the only place data will be written to, even if I select a user with ID 2. Please see below code for more information Code: [Select] <?php $staff_display_query = "SELECT staff_info.id, staff_info.fname, staff_info.lname FROM staff_info, staff_projects WHERE staff_info.id = staff_projects.staff_id AND staff_projects.proj_id = '$c_project_id'"; $staff_display_sql = mysql_query($staff_display_query) or die (mysql_error()); while ($row = mysql_fetch_array($staff_display_sql)) { $current_staff_id = $row['id']; $staff_fname = $row['fname']; $staff_lname = $row['lname']; $list_staff .= ' ' . $current_staff_id . '<br /> <a href="#" onclick="return false" onmousedown="javascript:toggleSlideBox(' . $current_staff_id . ');">' . $staff_fname . ' ' . $staff_lname . '</a> <div class="hiddenDiv" id="' . $current_staff_id . '" style="border:#FFF 2px solid; width:553px;"> <!--TASK 1--> <div id="task_1_permissions" class="task_permissions"> <input name="permissions_1" type="radio" value="1"/> <input name="permissions_1" type="radio" value="2" /> <input name="permissions_1" type="radio" value="3" /> <input name="permissions_1" type="radio" value="0" /> </div> <!--TASK 2--> <div id="task_2_permissions" class="task_permissions"> <input name="permissions_2" type="radio" value="1"/> <input name="permissions_2" type="radio" value="2" /> <input name="permissions_2" type="radio" value="3" /> <input name="permissions_2" type="radio" value="0" /> </div> <!--TASK 3--> <div id="task_3_permissions" class="task_permissions"> <input name="permissions_3" type="radio" value="1"/> <input name="permissions_3" type="radio" value="2" /> <input name="permissions_3" type="radio" value="3" /> <input name="permissions_3" type="radio" value="0" /> </div> <!--TASK 4--> <div id="task_4_permissions" class="task_permissions"> <input name="permissions_4" type="radio" value="1"/> <input name="permissions_4" type="radio" value="2" /> <input name="permissions_4" type="radio" value="3" /> <input name="permissions_4" type="radio" value="0" /> </div> <input name="submit_user_permissions" type="submit" value="Submit Permissions" /> </div> </div> <br /><br /> '; } if (isset($_POST['submit_user_permissions'])) { $permissions_1 = $_POST['permissions_1']; $permissions_2 = $_POST['permissions_2']; $permissions_3 = $_POST['permissions_3']; $permissions_4 = $_POST['permissions_4']; $query = "UPDATE staff_projects SET task_1='$permissions_1', task_2='$permissions_2', task_3='$permissions_3', task_4='$permissions_4' WHERE proj_id='$c_project_id' AND staff_id='$current_staff_id'"; $sql = mysql_query($query) or die (mysql_error()); echo 'Permissions set successfully.<br />'; } After this PHP I have my standard HTML. Below is the javascript function I use for the slide box: Code: [Select] <script src="js/jquery-1.5.js" type="text/javascript"></script> <script language="javascript" type="text/javascript"> function toggleSlideBox(x) { if ($('#'+x).is(":hidden")) { $(".hiddenDiv").slideUp(200); $('#'+x).slideDown(300); } else { $('#'+x).slideUp(300); } } </script> Javascript works just fine by the way. Below is the form I have in the HTML of the code. Code: [Select] <form action="" method="post" enctype="multipart/form-data"> <?php echo "$list_staff"; ?> </form> This is of course wrapped around body tags and all the other necessary HTML. The view of the form is working right, the functions within the form are also working correctly. I just cant seem to separate the variables for each individual user. If I am in Chris Hansen's div, it should be his ID number that is being referenced for the database, not the ID number of the last person entered into the system. Any ideas? As always, thanks in advance guys!!! Bl4ck Maj1k i am developing online test ,after succesful completion of the test i want to display the correct answe,in databse i have stored corect answer as radio button values(ex 1,2,3,4,) i want to display the coreect answer with a right mark,how can i achive this?could anybody help?
here is my code
<?php $testid=$_GET['testid']; include_once("header.php"); ?> <html> <head> <body> <?php include_once('connect.php'); $sqltest="select testname from test where testid='$testid'"; $sqltestresult=mysql_query($sqltest) or die(mysql_error()); while($result=mysql_fetch_array($sqltestresult)) { $testname=$result['testname']; } ?> <!--pass test name and time left --> <table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td width="50%" valign="middle"> <h1 style="margin-left:0;"><?php if(isset($testname)) { echo $testname ; } ?></h1> </td> <td width="50%" align="right" valign="middle"> <ul class="tabs" id="tabs"> <li id="showtime" style="font-weight:bold; color:#FF0000; bottom:5px; font-size:16px; float:right"></li> </ul> </td> </tr></table> <div class="div-tabs-container" class="div-tabs-container" style="width:79%;margin-left:3%" > <table cellpadding="0" cellspacing="0" border="0" id="questiontable" > <tr> <?php include_once('connect.php'); $sql="select * from testquestions where testid='$testid'"; $result=mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($result)>0) { $data = array(); // create a variable to hold the information while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false) { $data[] = $row; // add the row in to the results (data) array } //shift off the first value array_shift($data[0]); $merge = call_user_func_array('array_merge', $data); $size=sizeof($merge); $newdata=array(); $num=1; $correctanswerarray=array(); $selctedanswers=array(); /* echo "<form action='fetchquestion.php' method='post' id='formsubmit' onsubmit='return out()' name='test'>"; */ foreach ($merge as $key => $value ) { $sql2="select qid, question,option1,option2,option3,option4,correct_answer from question where qid='$value' "; $result2=mysql_query($sql2) or die(mysql_error()); while($row2=mysql_fetch_assoc($result2)) { $questionid=$row2['qid']; $question=$row2['question']; $option1=$row2['option1']; $option2=$row2['option2']; $option3=$row2['option3']; $option4=$row2['option4']; $correctanswer=$row2['correct_answer']; #array to store the correct answer. $correctanswerarray[] = $questionid.$correctanswer; #$newdata[]=$row2; echo " <table class='bix-tbl-container' cellspacing='0' cellpadding='0' border='0' width='100%' id='questiontable'><tr> <td class='bix-td-qno jq-qno-2413' rowspan='2' valign='top' align='left'>$num</td> <td class='bix-td-qtxt' valign='top'><p>$question</p></td> </tr> <tr> <td class='bix-td-miscell' valign='top'><table class='bix-tbl-options' id='tblOption_2413' border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td nowrap='nowrap' class='bix-td-option bix-td-radio' width='1%' id='tdOptionNo_A_2413'> <input type='radio' class='result-option cls_2413' name='option_$questionid' value='1' id='disable'/> </td><td class='bix-td-option' width='1%'>A.</td> <td class='bix-td-option' width='48%' id='tdOptionDt_A_2413'><table border='0' cellpadding='0' cellspacing='0'> <tr> <td class='bix-inner-td-option'>$option1</td> <td id='tdAnswerIMG_A_2413' class='jq-img-answer' valign='middle'style='display:none;padding-left:10px;'> <img src='/_files/images/website/accept.png' alt='' /> </td> </tr> </table></td></tr><tr><td nowrap='nowrap' class='bix-td-option bix-td-radio' width='1%' id='tdOptionNo_B_2413'> <input type='radio' class='result-option cls_2413' name='option_$questionid' value='2' id='disabble'/> </td><td class='bix-td-option' width='1%'>B.</td> <td class='bix-td-option' width='48%'id='tdOptionDt_B_2413'><table border='0' cellpadding='0' cellspacing='0'> <tr> <td class='bix-inner-td-option'>$option2</td> <td id='tdAnswerIMG_B_2413' class='jq-img-answer' valign='middle' style='display:none;padding-left:10px;'> <img src='/_files/images/website/wrong.gif' alt=''/> </td> </tr> </table></td></tr><tr><td nowrap='nowrap' class='bix-td-option bix-td-radio' width='1%' id='tdOptionNo_C_2413'> <input type='radio' class='result-option cls_2413' name='option_$questionid' value='3' id='disable'/> </td><td class='bix-td-option' width='1%'>C.</td> <td class='bix-td-option' width='48%' id='tdOptionDt_C_2413'><table border='0' cellpadding='0' cellspacing='0'> <tr> <td class='bix-inner-td-option'>$option3</td> <td id='tdAnswerIMG_C_2413' class='jq-img-answer' valign='middle' style='display:none;padding-left:10px;'> <img src='/_files/images/website/wrong.gif' alt='' /> </td> </tr> </table></td></tr><tr><td nowrap='nowrap' class='bix-td-option bix-td-radio' width='1%' id='tdOptionNo_D_2413'> <input type='radio' class='result-option cls_2413' name='option_$questionid' value='4' id='disable'/> </td><td class='bix-td-option' width='1%'>D.</td> <td class='bix-td-option' width='48%' id='tdOptionDt_D_2413'><table border='0' cellpadding='0' cellspacing='0'> <tr> <td class='bix-inner-td-option'>$option4</td> <td id='tdAnswerIMG_D_2413' class='jq-img-answer' valign='middle' style='display:none;padding-left:10px;'> <img src='/_files/images/website/wrong.gif' alt='' /> </td> </tr> </table></td></tr></table> \n <input type='hidden' name='count' value='$num' id='count'> <input type='hidden' name='queId[]' value='$questionid' id='queId'> </td> </tr> </table> "; $num++; } } echo " </tr> </table> "; #array of correct answrer #echo "array of correct answer<br/>"; #print_r($correctanswerarray); #echo "size of the coreect answer array"; $size1=sizeof($correctanswerarray); echo "<br/>"; } else { echo " no questions available for selected test"; } ?> </div> <!-- add div right side --> <div style="height:500px;width:150px;float:right;margin-top:-500px;border:1px solid #99CCFF"> </div> <div style="height:30px"> </div> <!-- add div bottom --> <div style="height:125px;border:1px solid #99CCFF"> </div> <?php include('footer.html'); ?> </body> </html> Edited by mac_gyver, 25 October 2014 - 10:05 AM. code tags around code please 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? 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 Hi guys, I have a file location stored in mysql. when i populate the table i need this file location to be a hyperlink to the file itself, so the visitors can click like a normal link and open the file in word and pdf (both formats stored). example of file location as in db "_private/Incident_Reports/Incident%20-%20Applecross%20-%2017%20December%202010%20-%20Website.doc" example of php code Code: [Select] echo $row['word_document']; any ideas would be really appreciated. Hi all, I've got a website for an event, each team have their details on a page which are recalled from a SQl database. But I'm wanting to create a password input box for each team, so when they enter the correct password they are taken to a page containing forms where they can edit the team details. Here is the page with the users details on where they anter the password: http://www.wharncliffenetwork.co.uk/wrc/entered/team.php?id=8 I'm not sure how to code it, Can an IF statement be used? Anyone got any pointers? I'f been unsuccessful in finding a tutorial or something similar. Hope that makes sense :S Cheers. 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. sorry if i have posted this in the wrong place, wasnt sure wether to post here or mysql. I have made a php calendar, and i am now wanting it to show if there is an event on that day and if so show it in a tool tip. the tool tip is populated by what is in the title="" of the link so i need my events to be shown in there. I have figured out how to show the event but now i am stuck on how to show all events if there is more than one one that day, how i have set it seems to only the second event, probably as the second variable overwrote the first variable. this is the code i have at the minute .............. $result = mysql_query("SELECT * FROM events WHERE day='$day_num' AND month='$fullmonth' AND year='$year'") or die(mysql_error()); $rows= mysql_num_rows($result); if ($rows !="false"){ while($rowout = mysql_fetch_array($result)) { $todayis = $rowout['day'] ."-". $rowout['month'] ."-". $rowout['year'] ."<br>"; $title= $rowout['event'] ."<br><br>";} $firstl = "<a href='' title='". $todayis . $title ."'>"; $lastl = "</a>";} else {$firstl = ""; $lastl = "";} then to display the day and links ................. Code: [Select] <td><? echo $firstl; ?><? print $day_num; ?><? echo $lastl; ?></td> could some one be so kind and help me write it so that it displays all events? here is a link to the calendar, incase its needed. http://www.scripttesting.htmlstig.com/calendar/index.php Many thanks Carl I have a number of PHP helper scripts that are stored outside the root directory of my websites. Those scripts may be used by one or more of my websites. Let's say I have two websites Website A uses PHP 7.0 Website B uses PHP 7.3Will the helper scripts be potentially executed using different versions of PHP? In other words, if Website B calls a helper script using a require statement, does that helper script execute as PHP 7.3? But if Website A calls the script, it would be executed as PHP 7.0. Hi Please take a look at my code snippet. I don't know how to get the number of rows returned from a MySQL stored procedure so that I can handle it accordingly. Any ideas please? Thanks |