PHP - Php Method To Retrieve File From Xml
What php method is good for getting file from a .xml sheet ?
Similar TutorialsHi, I want to be able to let user upload XML form, and then in the action page it needs to extract that so that I can add it to the database. Here is the upload form: Code: [Select] <html> <head></head> <body> <form method='post' action="uploadFileToDB.php" enctype="multipart/form-data"> <p> <label> Upload image<input type='file' name='imageFileType' id='imageFileType' /> </label> </p> <p> <input type='submit' value='Upload this image' name='upload' id='upload' /> </p> </form> </body> </html> Here is the uploadFileToDB.php: Code: [Select] <?php require("PHP_xml_parsing_via_DOM.php"); //NB: this script does the actual shreddering (XML to SQL) //IF User uploaded dir or XML file successful, then: if(isset($_POST['upload'])) { //SHRED NOW //NB: how to retrieve the uploaded xml file $_filePath=?? $node=basename($_filePath); $dom=new DOMDocument(); $dom->load($node); $labelPath=array(); mysql_connect("localhost","root"); mysql_select_db("dummydpev7"); $isXdocExist=mysql_query("SELECT file_Path,file_Name FROM xdocument WHERE file_Path='$_filePath' AND file_Name='$node'"); $docId=0; if(mysql_num_rows($isXdocExist)==1) { print "Entry already exists!"; $docId=mysql_next_id("xdocument")-1; } else { mysql_query("INSERT INTO xdocument (file_Path,file_Name) VALUES ('$_filePath','$node')"); $docId=mysql_next_id("xdocument")-1; } print "<br />".$docId; writeXMLtoDBViaDOM($dom->documentElement,$labelPath,$docId,$_filePath); } //ELSE else //Please upload Valid XML print "Problem with XML file being uploaded."; ?> The question in point is how do I extract the file I uploaded to set to $_filePath?? in the script so that I pass it to my function writeXMLtoDBviaDOM?? Please any help much appreciated! Hello, I am new to the forum and somewhat new to php, nice to meet you all. This is the first time I have ever really scripted with PHP so I'm still learning about all the tools I have and what I have to call things in PHP. I have a list of urls and as I loop through each one, I'd like to be able to get information from the webpage. The <title> would be a good start. I also want to know the best way for me to compare data I have. I'll show the basic code below, but I successfully go through each url in this text file. I put it in a <ul><li> list just fine. So if $url == http://www.youtube.com/file how is the normal way to check and see if the word "youtube" is in $url? I found preg_match() but I think I'm approaching the whole thing wrong because I get no output. I am an intermediate to somewhat advanced scripter in other languages similar to php, I just need to learn how you do the normal things in PHP. So I'd like to compare a string "youtube" to a variable '$url'. And I would like to be able to grab the title or other info from the file $url. Here is what I have so far. (Recent research showed me how I should do this with an XML file so I will probably change the .txt to .xml) Can you please tell me what to look for as I have been searching and can't really find a comprehensive answer. I changed the whole page to an echo trying to fix something last night. Before it was written like.. Code: [Select] <?php if ($true) { $var = value ?> <html code>The value is <?php $var ?> .</html code> <?php } ?> Code: [Select] /index.php <?php include 'include/header.html'; echo "<div id='wrapper'> <div id='left'> <div class='article'> <br /> <p>"; echo "Today is " . date("l") . ", the " . date("jS") . " of " . date("F") . "."; $lines = file('data/news.txt'); if ($lines){ foreach ($lines as $line_num => $line) { $url = htmlspecialchars($line); //Now I have url. I want to check the url and get the <title> & misc. data. //if youtube is in $url {html code to embed youtube}; //my attempt was $x = file($url); but I got a lot of 404 and 403 errors. //now I fill html. echo "<ul id='menu1' class='auroramenu'> <li><a href='#'>Story ".$line_num."</a> <a style='display: none;' class='aurorashow' href='#'></a> <a style='display: inline;' class='aurorahide' href='#'></a> <ul> <br /> <p>".$url."</p><br /> <li style='text-align:right;'><a href='".$url."' target='_blank'>Read the story.</a> </li> </ul> </li> </ul>"; } } echo "</p><br /> </div> </div> <div id='right'>"; include 'include/sidebar.html'; echo "</div><br class='clr' /></div><br />"; include 'include/footer.html'; ?> Thank you for your help. I am trying to retrieve an xml file from a webservice. I cant use the original server since it gags on non latin characters, unicode?, that is what the LOC says. The other server does work with non latin characters BUT it is too slow with file_get_contents, takes a minute to get anything, so slow you cant even use it in the program. YET, retrieves the xml fast in the browser window. So, what can I do that will work fast like it should? Code: [Select] //original database server, file_get_contents is faster, about 3 to 10 seconds //$request= 'http://z3950.loc.gov:7090/voyager?version=1.1&operation=searchRetrieve'.$query.$test2.'&startRecord='.$offset.'&maximumRecords=20'; //new one that can handle non latin characters //file_get_contents is SLOW, so slow to be unusable, about a minute or more $request='http://lx2.loc.gov:210/LCDB?version=1.1&operation=searchRetrieve'.$query.$test2.'&startRecord='.$offset.'&maximumRecords=20'; $raw_xml = file_get_contents($request); $filename = dirname(__FILE__)."/loc.xml"; $fp = fopen($filename, "w"); fwrite($fp, $raw_xml); fclose ($fp); Have page#1 with thumbs view_thumbs.php , when a thumb is clicked thumb link goes to page#2 which is the video_play.php page(which must play embed codes from xml sheet) Using GET method to identify incoming link from page#1. QUESTION is how can i retrieve file(embed code) from xml to play on page#2 with incoming GET info from page#1? (embeds not you only from you tube, so no youtube solutions only, just retrieve file) I somehow have to fill play video div on page#2/video_play.php according to GET data from page#1/view_thumbs.php
My script has 3 classes (that are relevant to this discussion): DB, User and Validate. They are all in independent files and loaded automatically, when required, by an autoloader.
The error messages I am getting a Any pointers as to what I am doing wrong, or what I should be doing, would be most welcome. Hi, I am not very good with php but this code was kindly given to me by mdjamato, except I added a variable $markGradeSum to add all the $markGrade. Problem is that I will get notice saying undefined variable $markGradeSum because the $markGradeSum is in the foreach loop which it needs to be in for the right calculation but where I want to output the variable is in the while loop in this line: Code: [Select] $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong> <strong>Grade</strong> <br><strong>Year:</strong> {$row['Year'] $markGradeSum}</p>\n"; Below is whole code: Code: [Select] <?php if($num ==0){ echo "<p>Sorry, No Records were found from this Search</p>";} else{ function outputModule($moduleID, $moduleName, $sessionData) { if(!count($sessionData)) { return false; } $markTotal = 0; $markGrade = 0; $weightSession = 0; $markGradeSum = 0; $grade = ""; $sessionsHTML = ""; $courseHTML = ""; foreach($sessionData as $session) { $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} <strong>Session Mark:</strong> {$session['Mark']}</strong> <strong>Session Weight Contribution</strong> {$session['SessionWeight']}%</p>\n"; $markTotal += round($session['Mark'] / 100 * $session['SessionWeight']); $weightSession += ($session['SessionWeight']); $markGrade = round($markTotal / $weightSession * 100); $markGradeSum = round($markGrade); if ($markGrade >= 70){ $grade = "A";} else if ($markGrade >= 60 && $markGrade <= 69){ $grade = "B";} else if ($markGrade >= 50 && $markGrade <= 59){ $grade = "C";} else if ($markGrade >= 40 && $markGrade <= 49){ $grade = "D";} else if ($markGrade >= 30 && $markGrade <= 39){ $grade = "E";} else if ($markGrade >= 0 && $markGrade <= 29){ $grade = "F";} } $moduleHTML = "<p><br><strong>Module:</strong> {$moduleID} - {$moduleName} <strong>Module Mark:</strong> {$markTotal} <strong>Mark Percentage:</strong> {$markGrade} <strong>Grade:</strong> {$grade} </p>\n"; return $moduleHTML . $sessionsHTML; } $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong> <strong>Grade</strong> <br><strong>Year:</strong> {$row['Year'] $markGradeSum}</p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; } } ?> How can I retrieve the variable so it doesn't come up with the notice but be able to display $markGradeSum to the places I want them in (one in foreach loop for calculation and other in while loop for output). Thank You Hello, I have a booking system which has time and date fields and if someone tries to book, for example, on 01/01/2011 at 09:00, when this slot is already taken, an error would be produced - which is fine. However I'm not sure in telling them what hours are available. There are 9 available times: 09,10,11,12,13,14,15,16,17:00. I will need to perform an sql query to gather all the times on the inputted date, I'm guessing a for loop would be the most efficient way? The only way I could think of is using multiple IF queries, for example: Code: [Select] <?php $sql = "SELECT `Hour` FROM `jobs` WHERE `Hour` = '09:00:00' AND Day ='$Day' AND Month ='$Month' AND Year ='$Year'"; $result = mysql_query($sql); if(mysql_num_rows($result) > 0){ $09Available = 'n'; // Time not available }else{ $09Available = 'y'; } $sql = "SELECT `Hour` FROM `jobs` WHERE `Hour` = '10:00:00' AND Day ='$Day' AND Month ='$Month' AND Year ='$Year'"; $result = mysql_query($sql); if(mysql_num_rows($result) > 0){ $10Available = 'n'; // Time not available }else{ $10Available = 'y'; } $sql = "SELECT `Hour` FROM `jobs` WHERE `Hour` = '11:00:00' AND Day ='$Day' AND Month ='$Month' AND Year ='$Year'"; $result = mysql_query($sql); if(mysql_num_rows($result) > 0){ $11Available = 'n'; // Time not available }else{ $11Available = 'y'; } ?> etc. etc.. How would I go about creating a more efficient method? Thank you, Jack. I have a variable $form in the code below what I cant figure out how do it is call it and get the information it has out so I can display the errors: Code: [Select] function login($subuser, $subpass, $subremember){ global $database, $form; //The database and form object /* Username error checking */ $field = "user"; //Use field name for username if(!$subuser || strlen($subuser = trim($subuser)) == 0){ $form->setError($field, "* Username not entered"); } else{ /* Check if username is not alphanumeric */ if(!preg_match("^([0-9a-z])*$^i", $subuser)){ $form->setError($field, "* Username not alphanumeric"); } } if ($database->usernameBanned($subuser)) { $form->setError($field, "*Your Account has been banned"); } /* Password error checking */ $field = "pass"; //Use field name for password if(!$subpass){ $form->setError($field, "* Password not entered"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } /* Checks that username is in database and password is correct */ $subuser = stripslashes($subuser); $result = $database->confirmUserPass($subuser, md5($subpass)); /* Check error codes */ if($result == 1){ $field = "user"; $form->setError($field, "* Username not found"); } else if($result == 2){ $field = "pass"; $form->setError($field, "* Invalid password"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } I have a form that ask user to enter other details but the primary key as this is automated and when they click on Submit button it takes the user to different form. now on this form I would like to retreive the primary that has just been added to the table. How can I do this? I have this code which uoploads and resizes the images into a folder without a problem. My problem is I am unable to view the Thumb or Full image which has uploaded to the folder and the database with the other data. How do i correct this problem code below. Thanks upload form and script Code: [Select] <?php //database properties $dbhost = 'localhost'; $dbuser = 'user'; $dbpass = 'pass'; $dbname = 'DB'; // make a connection to mysql here $conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error()); mysql_select_db ($dbname) or die ("I cannot select the database '$dbname' because: " . mysql_error()); /******** start function ********/ function errors($error){ if (!empty($error)) { $i = 0; echo "<blockquote>\n"; while ($i < count($error)){ echo "<p><span class=\"warning\">".$error[$i]."</span></p>\n"; $i ++;} echo "</blockquote>\n"; }// close if empty errors } // close function // ----------------Create Smaller version of large image--------------------- function createthumbfull($src_filename, $dst_filename_full) { // Get information about the image list($src_width, $src_height, $type, $attr) = getimagesize( $src_filename ); // Load the image based on filetype switch( $type ) { case IMAGETYPE_JPEG: $starting_image = imagecreatefromjpeg( $src_filename ); break; case IMAGETYPE_PNG: $starting_image = imagecreatefrompng( $src_filename ); break; case IMAGETYPE_GIF: $starting_image = imagecreatefromgif( $src_filename ); break; default: return false; } // get the image to create thumbnail from $starting_image; // get image width $width = imagesx($starting_image); // get image height $height = imagesy($starting_image); // size to create thumnail width $thumb_width = 600; // divide iwidth by specified thumb size $constant = $width/$thumb_width; // round height by constant and add t thumb_height $thumb_height = round($height/$constant, 0); //create thumb with true colours $thumb_image = imagecreatetruecolor($thumb_width, $thumb_height); //create thumbnail resampled to make image smooth imagecopyresampled($thumb_image, $starting_image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); $ran = rand () ; $thumb1 = $ran.".jpg"; global $thumb_Add_full; $thumb_Add_full = $dst_filename_full; $thumb_Add_full .= $thumb1; imagejpeg($thumb_image, "" .$dst_filename_full. "$thumb1"); } //-------------------- create thumbnail -------------------------------------------- //$src_filename = source of image //$dst_filename_thumb = location to store final image function createthumb($src_filename, $dst_filename_thumb) { $size = getimagesize($src_filename); // get image size $stype = $size['mime']; //get image type : gif,png,jpg $w = $size[0]; // width of image $h = $size[1]; // height of image //do a switch statment to create image from right image type switch($stype) { //if image is gif create from gif case 'image/gif': $simg = imagecreatefromgif($src_filename); break; //if image is jpeg create from jpeg case 'image/jpeg': $simg = imagecreatefromjpeg($src_filename); break; //if image is png create from png case 'image/png': $simg = imagecreatefrompng($src_filename); break; } $width = $w; // get image width $height = $h; // get image height // size to create thumnail width $thumb_width = 150; $thumb_height = 150; //use true colour for image $dimg = imagecreatetruecolor($thumb_width, $thumb_height); $wm = $width/$thumb_width; //width divided by new width $hm = $height/$thumb_height; //height divided by new height $h_height = $thumb_height/2; //ass new height and chop in half $w_height = $thumb_width/2; //ass new height and chop in half //if original width is more then original height then modify by width if($w> $h) { $adjusted_width = $w / $hm; // add original width and divide it by modified height and add to var $half_width = $adjusted_width / 2; // chop width in half $int_width = $half_width - $w_height; // take away modified height from new width //make a copy of the image imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$thumb_height,$w,$h); //else if original width is less or equal to original height then modify by height } elseif(($w <$h) || ($w == $h)) { $adjusted_height = $h / $wm; // diving original height by modified width $half_height = $adjusted_height / 2; // chop height in half $int_height = $half_height - $h_height; // take away modified height from new width //make a copy of the image imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$thumb_width,$adjusted_height,$w,$h); } else { // don't modify image and make a copy imagecopyresampled($dimg,$simg,0,0,0,0,$thumb_width,$thumb_height,$w,$h); } $ran = "thumb_".rand (); // generate random number and add to a string $thumb2 = $ran.".jpg"; //add random string to a var and append .jpg on the end global $thumb_Add_thumb; //make this var available outside the function as it will be needed later. $thumb_Add_thumb = $dst_filename_thumb; // add destination $thumb_Add_thumb .= $thumb2; // append file name on the end //actually create the final image imagejpeg($dimg, "" .$dst_filename_thumb. "$thumb2"); } /********end functions ***********/ // if form submitted then process form if (isset($_POST['submit'])){ // check feilds are not empty $imageTitle = trim($_POST['imageTitle']); if (strlen($imageTitle) < 3 || strlen($imageTitle) > 255) { $error[] = 'Title must be at between 3 and 255 charactors.'; } // check feilds are not empty or check image file size if (!isset($_FILES["uploaded"])) { $error[] = 'You forgot to select an image.'; } // check feilds are not empty $imageDesc = trim($_POST['imageDesc']); if (strlen($imageDesc) < 3) { $error[] = 'Please enter a description for your image.'; } // location where inital upload will be moved to $target = "productimages/" . $_FILES['uploaded']['name'] ; // find the type of image switch ($_FILES["uploaded"]["type"]) { case $_FILES["uploaded"]["type"] == "image/gif": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; case $_FILES["uploaded"]["type"] == "image/jpeg": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; case $_FILES["uploaded"]["type"] == "image/pjpeg": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; case $_FILES["uploaded"]["type"] == "image/png": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; case $_FILES["uploaded"]["type"] == "image/x-png": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; default: $error[] = 'Wrong image type selected. Only JPG, PNG or GIF accepted!.'; } // if valadation is okay then carry on if (!$error) { // post form data $imageTitle = $_POST['imageTitle']; $imageDesc = $_POST['imageDesc']; //strip any tags from input $imageTitle = strip_tags($imageTitle); $imageDesc = strip_tags($imageDesc); // add slashes if needed if(!get_magic_quotes_gpc()) { $imageTitle = addslashes($imageTitle); $imageDesc = addslashes($imageDesc); } // remove any harhful code and stop sql injection $imageTitle = mysql_real_escape_string($imageTitle); $imageDesc = mysql_real_escape_string($imageDesc); //add target location to varible $src_filename $src_filename = $target; // define file locations for full sized and thumbnail images $dst_filename_full = 'productimages/'; $dst_filename_thumb = 'productthumb/'; // create the images createthumbfull($src_filename, $dst_filename_full); //call function to create full sized image createthumb($src_filename, $dst_filename_thumb); //call function to create thumbnail image // delete original image as its not needed any more. unlink ($src_filename); // insert data into images table $query = "INSERT INTO table (imageTitle, imageThumb, imageFull, imageDesc) VALUES ('$imageTitle', '$thumb_Add_thumb', '$thumb_Add_full', '$imageDesc')"; $result = mysql_query($query) or die ('Cannot add image because: '. mysql_error()); // show a message to confirm results echo "<h3 align='center'> $imageTitle uploaded</h3>"; } } //dispaly any errors errors($error); ?> <form enctype="multipart/form-data" action="" method="post"> <fieldset> <legend>Upload Picture</legend> <p>Only JPEG, GIF, or PNG images accepted</p> <p><label>Title<br /></label><input type="text" name="imageTitle" <?php if (isset($error)){ echo "value=\"$imageTitle\""; }?> /></p> <p><label>Image<br /></label><input type="file" name="uploaded" /></p> <p><label>Description<br /></label><textarea name="imageDesc" cols="50" rows="10"><?php if (isset($error)){ echo "$imageDesc"; }?></textarea></p> <p><label> </label><input type="submit" name="submit" value="Add Image" /></p> </fieldset> </form> view data Code: [Select] <?php // Connects to your Database mysql_connect("localhost", "user", "pass") or die(mysql_error()) ; mysql_select_db("DB") or die(mysql_error()) ; //Retrieves data from MySQL $data = mysql_query("SELECT * FROM table") or die(mysql_error()); //Puts it into an array while($info = mysql_fetch_array( $data )) { ?> <?php echo "<img src=http://www.web.com/productimages/" .$info['imagefull'] ." > <br>"; ?> <?php echo "<img src=http://www.web.com/productthumb/" .$info['imageThumb'] ." > <br>"; ?> <?php echo "<b>imageTitle:</b> ".$info['imageTitle'] . "<br> "; ?> <?php echo "<b>imageDesc:</b> ".$info['imageDesc'] . " <hr>"; ?> <?php }?> Hi everyone,
I've been running a self-written php shopping cart for the last 8 years, with lots of success. Recently however, the credit card processor (Linkpoint) I use upgraded their gateway, and now I have a problem.
Basically, the last page of my checkout does a _POST to a specific url for their gateway. I send through a bunch of <input> variables, some of them hidden, but all of them check out okay. I have combed over their specs, made sure I'm not sending any bad characters, made sure I've got the right format for the fields they want, etc...
Right now the transaction is successful, the customer's card is charged, but Linkpoint's system is returning an error message: We are unable to process your request due to invalid data.
Long story short, their support staff has asked me to "send them the xml string" via email. I have no idea how to do this (even after spending a few hours online trying to figure it out).
Is there a simple way to generate the xml string that's being passed during the _POST? Some kind of php code I can incorporate into my final checkout page, run a test transaction, and maybe write the string out somewhere so I can get it to them?
Any help you guys could give me would be greatly appreciated. Thanks in advance! Danny Submit2.php Code: [Select] <?php $db = mysql_connect("localhost", "root") or die("Could not connect."); //username and password if(!$db) die("no db"); if(!mysql_select_db("simple",$db)) if(!mysql_select_db("regis",$db))//database name die("No database selected."); $message=$_POST['message']; if(isset($_POST['submit'])) //if submit button push has been detected { $message=$_POST['message']; if(strlen($message)<1) { print "You did not input a message"; } else { $message=strip_tags($message); $IP=$_SERVER["REMOTE_ADDR"]; //grabs poster's IP $checkforbanned="SELECT IP from admin where IP='$IP'"; $checkforbanned2=mysql_query($checkforbanned) or die("Could not check for banned IPS"); if(mysql_num_rows($checkforbanned2)>0) //IP is in the banned list { print "You IP is banned from posting."; } else if(strlen($message)>=1) { $message=strip_tags($message); echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('$message')</SCRIPT>"); die("<meta http-equiv=\"refresh\" content=\"0; url=registration.php\">"); } $message=$_POST['message']; $message=strip_tags($message); /* if($_POST['username'] && $_POST['pass']) { $name = mysql_query("SELECT * FROM Persons"); $thedate = date("U"); //grab date and time of the post $insertmessage="INSERT into mesej (name,IP,postime,message) values('$name','$IP','$thedate','$message')"; mysql_query($insertmessage) or die("Could not insert message"); } */ } } if(!isset($message)) { print "<form action='' method='post' name='form'>"; print "Your message:<br>"; print "<textarea name='message' cols='40' rows='2'></textarea><br>"; print "<a onClick=\"addSmiley(':)')\"><img src='smile.gif'></a> "; print "<a onClick=\"addSmiley(':(')\"><img src='blush.gif'></a> "; print "<a onClick=\"addSmiley(';)')\"><img src='images/wink.gif'></a> "; print "<input type='submit' name='submit' value='Set Name'></form>"; print "<script language=\"Java Script\" type=\"text/javascript\">\n"; print "function addSmiley(a)\n"; print "{\n"; print "document.form.message.value += a;"; print "document.form.message.focus();\n"; print "}\n"; print "</script>\n"; print "<br><br>"; } ?> Registration.php Code: [Select] <?php $db = mysql_connect("localhost", "root") or die("Could not connect."); //username and password if(!$db){die("no db");} if(!mysql_select_db("regis",$db)){die("No database selected.");} $message=$_POST['message']; echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('$message')</SCRIPT>"); if (isset($_POST['sub'])) { $message=strip_tags($message); if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) { print "You did not complete all of the required fields"; } // checks if the username is in use if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM registration WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { print ('Sorry, the username '.$_POST['username'].' is already in use.'); } //this makes sure both passwords entered match if ($_POST['pass'] != $_POST['pass2']) { print ('Your passwords did not match. '); } // here we encrypt the password and add slashes if needed $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); } // now we insert it into the database if($_POST['username'] && $_POST['pass'] && $_POST['pass2'] ) { $insert = "INSERT INTO registration (username, password) VALUES ('".$_POST['username']."', '".$_POST['pass']."')"; $add_member = mysql_query($insert); echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('Registration had been succesfully added :)')</SCRIPT>"); print("<meta http-equiv=\"refresh\" content=\"0; url=login.php\">"); } } else { echo "<form action='registration.php' method='post'> <table border='0'> <tr><td>Username:</td><td> <input type='text'name='username' maxlength='60'> </td></tr> <tr><td>Password:</td><td> <input type='password' name='pass' maxlength='10'> </td></tr> <tr><td>Confirm Password:</td><td> <input type='password' name='pass2' maxlength='10'> </td></tr> <tr><th colspan=2><input type='submit' name='sub' value='Register'></th></tr> </table> </form> "; } im just want the message text area to be appear in registhration php in text box but its doest not appear instead the output is empty when im testing the first one that is : if(strlen($message)>=1) { $message=strip_tags($message); echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('$message')</SCRIPT>"); die("<meta http-equiv=\"refresh\" content=\"0; url=registration.php\">"); that javascript box can run and read the same message that was input but when come to registrtaion php its only empty which way im wrong ? ?> I have 3 dropdown menus which have the same name <select name="dropdown">, how to get the value from 3 of them by using php for loop and array? I did try to put array on them before, but seem it can't work. My codes : <?php for ( $counter = 1; $counter <= 3; $counter ++) { if (isset($_POST['submit'])) { //Form has been submitted. $dropvalue = $_POST['dropdown[$counter]']; echo $dropvalue; } } ?> <form action="test8.php" name="frmtest8" method='post'> <select name="dropdown[1]"> <option value="1st">first</option> <option value="2nd">second</option> <option value="3rd">third</option> </select> <select name="dropdown[2]"> <option value="1st">first</option> <option value="2nd">second</option> <option value="3rd">third</option> </select> <select name="dropdown[3]"> <option value="1st">first</option> <option value="2nd">second</option> <option value="3rd">third</option> </select> <input type="submit" name="submit" value="Send" /> </form> It gives error message Parse error: parse error in C:\wamp\www\plekz\test8.php on line 23 I guess the error is because of $_POST['dropdown[$counter]']; I cannot put the two symbols [] inside $_POST[' '] right? How to call the array if cannot put the two symbols? Hi, I want to be able to retrieve records from db tables to build an xml file. The problem I am having is that I don't know how to retrieve a value after using foreign key to get appropriate value. You see below I want to make a new attribute to store to var $newAttr. Code: [Select] <?php $doc=new DOMDocument(); mysql_connect("localhost","root"); mysql_select_db("xmlDB"); $edges=mysql_query("SELECT * FROM edge"); while($row=mysql_fetch_assoc($edges)) { if($row['flag']=='val') { $curValue=mysql_query("SELECT val FROM value,edge WHERE val.edge_id=edge.edge_id"); if($curRowIsAttribute=mysql_query("SELECT is_Attribute FROM value,edge WHERE value.is_Attribute='Y' AND value.edge_id=edge.edge_id")) { //create attribute node $newAttr=$dom->createAttribute();//HELP HERE PLEASE THEN I SHOULD BE ABLE TO COMPLETE NEXT TWO LINES BELOW! //set attribute value ... //append attribute to current element ... }//END IF }//END IF }//END BIG WHILE ?> Any help much appreciated! I have a form where you can pick all the days in the week. When the form is posted my code finds the date of the day you picked that most recently went by. Then the code takes that date, and echos the date of every day of the week that you picked that comes after that date for a year. But for some reason he thinks we're in 2009, even though i know the date puts out that we're in 2010. Here's the code: <?php //function if(isset($_POST['submit'])) { function nextWeeksDay($date_begin,$nbrweek) { $nextweek=array(); for($i = 1; $i <= $nbrweek; $i++) { // 52 week in one year of course $nextweek[$i]=date('d-m-y', strtotime('+'.$i.' week',$date_begin)); } return $nextweek; } //Get what user posted as day, and find the date of the past day gone. $roday = $_POST['day']; echo $roday; echo date('d-m-y',strtotime('last ' . $roday)); $sistdag = date('d-m-y',strtotime('last ' . $roday)); /// end function /// example of a select date // var $date_begin = strtotime($sistdag); //D Day Month Year - like function format. $nbrweek=52; // call function $result=nextWeeksDay($date_begin,$nbrweek); // Preview for($i = 1; $i <= $nbrweek; $i++) { echo '<br> - '.$result[$i]; } } ?> All help appreciated! Hi! I am trying to implement the comment feature. After a user selects a recipe from the search results (http://razor.ischool.utexas.edu/~nem/project/index.php scroll down to choose a recipe from the search results), the recipe page is displayed. The user may leave a comment at the bottom of the recipe page if she wishes to. The comment would be recorded in a mysql table and be displayed along with other comments for this particular recipe. The problem is that when the user has entered the comment and name and hits "Add my comment", this error appears: Notice: Undefined index: id in /.../recipeText_w.php on line 57 error retrieving proteins data While I understand it happens because the recipe Id ($_GET['id']) becomes unavailable after the comment and name are submitted, I am not sure how to make the recipe ID available again so that the same recipe page is displayed. The script is attached. I will appreciate your advice. I have two pages - add_product.php and show.php here is the code for add_product.php Code: [Select] <?php ini_set('display_errors',1); error_reporting(-1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Check for a name: if (empty($_POST['product'])) { $add_cat_errors['product'] = 'Please enter the name!'; } // Check for a description: if (empty($_POST['prod_descr'])) { $add_cat_errors['prod_descr'] = 'Please enter the description!'; } // Check for a category: if (!isset($_POST['cat']) || !filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['cat'] = 'Please select a category!'; } // Check for a price: if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) { $add_cat_errors['price'] = 'Please enter a valid price!'; } // Check for a category: if (!isset($_POST['directory']) || !filter_var($_POST['directory'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['directory'] = 'Please select a directory!'; } // Check for a stock: if (empty($_POST['stock']) || !filter_var($_POST['stock'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['stock'] = 'Please enter the quantity in stock!'; } if (empty($add_cat_errors)) { $query = "INSERT INTO product (product, prod_descr, catID, price, dirID, stock) VALUES (?, ?, ?, ?, ?, ?)"; // Prepare the statement: $stmt = mysqli_prepare($dbc, $query); // For debugging purposes: // if (!$stmt) echo mysqli_stmt_error($stmt); // Bind the variables: mysqli_stmt_bind_param($stmt, 'sssssi', $name, $desc, $_POST['cat'], $_POST['price'], $_POST['directory'], $_POST['stock']); // Make the extra variable associations: $name = strip_tags($_POST['product']); $desc = strip_tags($_POST['prod_descr']); // Execute the query: mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) == 1) { // If it ran OK. // Print a message: echo '<h4>The product has been added!</h4>'; // Clear $_POST: $_POST = array(); // Clear $_FILES: $_FILES = array(); } else { // If it did not run OK. trigger_error('The product could not be added due to a system error. We apologize for any inconvenience.'); } } // End of $errors IF. } else { // Clear out the session on a GET request: } // End of the submission IF. require_once ('./includes/form_functions.inc.php'); ?> <form enctype="multipart/form-data" action="add_image.php?prodID={$row['prodID']}" method="post" accept-charset="utf-8"> <input type="hidden" name="MAX_FILE_SIZE" value="524288" /> Product<br /><?php create_form_input('product', 'text', $add_cat_errors); ?> Description<br /><?php create_form_input('prod_descr', 'textarea', $add_cat_errors); ?> Category<br /><select name="cat"<?php if (array_key_exists('cat', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT catID, cat FROM category ORDER BY cat ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['cat']) && ($_POST['cat'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('cat', $add_cat_errors)) echo $add_cat_errors['cat']; ?> Price<br /><?php create_form_input('price', 'text', $add_cat_errors); ?> Directory<br /><select name="directory"<?php if (array_key_exists('directory', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT dirID, directory FROM directory ORDER BY directory ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['directory']) && ($_POST['directory'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('directory', $add_cat_errors)) echo $add_cat_errors['directory']; ?> </select> <br /> Stock<br /><?php create_form_input('stock', 'text', $add_cat_errors); ?> <input type="submit" value="Add This Product" class="button" /> </fieldset> </form> and here is the code for show.php Code: [Select] <?php ini_set('display_errors',1); error_reporting(-1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if($id = isset($_GET['prodID'])) { $q = "SELECT `prodID`, `product`, `prod_descr`, `catID`, `dirID`, `price`, `stock` FROM product WHERE `prodID`='{$_GET['prodID']}'"; $r = mysqli_query($dbc, $q); while($row = mysqli_fetch_array($r)) { echo $row['product']; echo "<br />"; echo $row['prod_descr']; echo "<br />"; echo $row['catID']; echo "<br />"; echo $row ['dirID']; echo "<br />"; echo $row['price']; echo "<br />"; echo $row['stock']; } } What I want is to try and retrieve the id of the last record inserted in add_product and pass it into show.php, but I get this error message. Quote An error occurred in script 'C:\Users\David Morgan\Desktop\WEBSITES\hairz_&_graces\site\admin\add_image.php' on line 16: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given I am struggling to find out where I am going wrong at the moment, if anyone could please help me that would be really appreciated. Hi, Is it possible to retrieve all the information from a posted value without knowing the input field? My page is taking information from a database and then creates a page with checkboxs so that people can select certain fields. There are 1300 fields in the database so I don't know what fields will be submitted when a person saves the page, is there a simple way to check what fields have been submitted without writing a check for each checkbox? I hope this makes sense, thanks in advance for any help. on page load pop up comes for selecting tv or movies (session is started in conn.php) if tv is selected session['select'] = 'tv_sotime' same for movies Now i want to change the selection I kept a link 'CHANGE' for selection i will unset session['select'] by passing variable on session.php but when i load /entertainment.php the pop up should not come Thank U... index.php Code: [Select] <? include("conn.php"); //require('_drawrating.php'); $pagename="Entertainment"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?=$settings->ScriptName?> | <?=$pagename?></title> <link rel="shortcut icon" href="images/favicon.ico" /> <link rel="shortcut icon" type="images/png" href="images/favicon.png" /> <link rel="shortcut icon" type="images/png" href="images/favicon.gif" /> <link rel="stylesheet" href="style.css" type="text/css" media="all" /> <link rel="stylesheet" href="css/cnelstyle.css" type="text/css" media="all" /> <link media="screen" rel="stylesheet" href="css/colorbox.css" /> <script src="js/jquerylatestmin.js" type="text/javascript"></script> <script src="js/jquery.colorbox-min.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $(window).bind('load', function(e) { $.colorbox({ 'width' : 300, 'height' : 130, 'transitionIn' : 'none', 'transitionOut' : 'elastic', 'centerOnScroll' : 'true', 'overlayOpacity' : 0.2, 'overlayColor' : '#000', 'modal' : 'true', href:"select.php"}); }); }); </script> </head> <body> <? //require_once("fb.php")?> <div id="wrap"> <? include('header.php'); include("session.php"); ?> <div class="wraper"> <div class="middle"> <div class="ad"><?=stripslashes($adsense->Ads7)?></div> </div> <div class="clr"></div> </div> </div> <div class="footer"> <div class="wraper"> <?php include("footer.php"); ?> </div> </div> </body> </html> tv_sotime.php Code: [Select] <?php include("conn.php"); $pagename="TV SHOWTIME"; $_SESSION['select'] = 'tv_sotime'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> <?=$settings->ScriptName?> | <?=$pagename?> </title> <link rel="shortcut icon" href="images/favicon.ico" /> <link rel="shortcut icon" type="images/png" href="images/favicon.png" /> <link rel="shortcut icon" type="images/png" href="images/favicon.gif" /> <link rel="stylesheet" href="css/cnelstyle.css" type="text/css" media="all" /> <link rel="stylesheet" href="style.css" type="text/css" media="all" /> <link rel="stylesheet" href="jscss/main.css" /> <script type="text/javascript" src="jscss/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="jscss/main.js"></script> </head> <body> <? //include("customjqmodalbox.php"); require_once("fb.php"); ?> <div id="wrap"> <? include('header.php')?> <div class="wraper"> <div class="middle"> <div class="middle_content"><a href="session.php?curr=c">Change</a></div> <div id="page"> <ul class="mytabs" id="tabs"> <li class="title"> <h2><strong>What's on Today?</strong></h2> <? //date('l M d Y')?> </li> <!-- <li class="todaydate"> <h2></h2> </li>--> <li class="current"><a href="tab-1.html">Movies</a></li> <li><a href="tab-2.html">Reality</a></li> <li><a href="tab-3.html">Sports</a></li> </ul> <div class="mytabs-container" id="tabs-container"> Loading... </div> </div> <!-- page --> <div class="ad"> <?=stripslashes($adsense->Ads7)?> </div> <div class="ss"> <h3 id="cat_head">Categories</h3> <ul> <li><a href="#">Drama</a></li> <li><a href="#">TV Programs</a></li> <li><a href="#">Special Programs for special Day</a></li> </ul> <img src="images/cineaxis.png" alt="" /> </div> </div> </div> <div class="clr"></div> </div> </div> <!-- warp --> <!--<div class="fb-like-box" data-href="http://www.facebook.com/CineAxis" data-width="198" data-height="274" data-show-faces="true" data-border-color="#E8E8E8" data-stream="false" data-header="false"> </div>--> <div class="footer"> <div class="wraper"> <?php include("footer.php"); ?> </div> </div> </body> </html> Code: [Select] <? include("conn.php"); //session_start(); if(isset($_GET['curr']) == 'c') { unset($_SESSION['select']); //session_destroy(); header("Location:index.php"); } if(isset($_SESSION['select'])) { if($_SESSION['select'] == 'tv_sotime') { $page = 'tv_sotime.php'; header("Location:$page"); } if($_SESSION['select'] == 'movie_sotime') { $page2 = 'movie_sotime.php'; header("Location:$page2"); } } ?> Dear All, I have login script already. i have two database one is users and another one is reference in both user_name is common. In this if a user login and search the refid means that user datas onle possible to retrieve. for others datas they cant access. i wrote the below code but it display all user datas. kindly help me <?php session_start(); if (!$_SESSION["user_name"]) { // User not logged in, redirect to login page Header("Location: login.php"); / } // Member only content // ... $con = mysql_connect('localhost','root',''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("login", $con); $user_name = $_POST['user_name']; $query = "select * from reference,users where reference.user_name=users.user_name and reference.refid='$refid'"; $result = mysql_query($query) or trigger_error('MySQL encountered a problem<br />Error: ' . mysql_error() . '<br />Query: ' . $query); while($row = mysql_fetch_array($result)) { echo $row['refid']; echo $row['origin']; echo $row['dest']; echo $row['date']; echo $row['exdate']; echo $row['user_name']; } echo "<p><a href=\"logout.php\">Click here to logout!</a></p>"; ?> <html> <form method="post" action="final.php"> Ref Id:<input type="text" name="refid"> <input type="submit" value="submit" name="submit"> </html> |