PHP - Issue In Simplexmlelement
Hello!
I am using CURL to access HTML and extract all the elements from it as below Code: [Select] ** * Initialize the cURL session */ $ch = curl_init(); /** * Set the URL of the page or file to download. */ curl_setopt($ch, CURLOPT_URL,'http://www.w3schools.com/PHP/php_xml_simplexml.asp'); /** * Ask cURL to return the contents in a variable * instead of simply echoing them to the browser. */ curl_setopt($ch, CURLOPT_FAILONERROR,1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT, 15); /** * Execute the cURL session */ $contents = curl_exec ($ch); /** * Close cURL session */ curl_close ($ch); This works perfectly , but my next step is to use SimpleXMLElement() and grab a particular element from it which is. Code: [Select] $xml_data = new SimpleXMLElement($contents); but I came across an article saying that there is no pint using SimpleXMLElement() to grab HTML Elements, Is that true? and BTW if I need to grab a particular element (in the already extracted HTML using CURL) what is the function I am supposed to use ? Thank you Similar TutorialsHey Guys, I have a snippet of XML here.. Code: [Select] <courses> <course> <id>70</id> <name>Marketing and Social Media</name> <dates> <date> <instance_id>6747</instance_id> <location /> <course_type>Day</course_type> <date_available>2011/07/13</date_available> <time_start>9:30</time_start> <time_end>17:00</time_end> <availibility>7</availibility> <running_dates> <running_date>2011/07/13</running_date> <running_date>2011/07/14</running_date> </running_dates> </date> </dates> </course> I'm trying to run xpath query to return all the courses and running dates associated with it but I dont understand how I get the running_dates? This is what I have.. Code: [Select] <?php $xmlstr = "../wp-content/themes/iact/courses.xml"; $xml = new SimpleXMLElement($xmlstr, NULL, TRUE); foreach ($xml->xpath('//date/running_dates') as $date) { $t = "<p class='heading'>". $date->course_type."</p> <div class='content'>".$date->running_date."</div>"; // do I need to go into another foreach here to loop all of the running dates? hardly? echo $t; } ?> Hi Guys, I'm trying to run the following code but the page breaks with no errors. I'm using PHP 5 which should run Simple XML. Code seems fine to me... Code: [Select] <?php $xmlstr = "courses.xml"; $xml = new SimpleXMLElement($xmlstr); // I Know it's breaking at this line echo $xml->course[0]->name; ?> Hi guys, I'm constructing a PHP document, using SimpleXML- I want to set the encolding of the document to "ISO-8859-1" - how do I do this.. This prob is driving me nuts... Can someone please help? Thanks in advance. Will I have this SimpleXMLElement Object and I can't echo out any attribute. In this example I am only showing you one SimpleXMLElement Object of the entire result set just for brevity. Here is the code that loops through the results: foreach($oXML->links->link as $o){ echo "<pre>";print_r($o);echo "</pre>"; } SimpleXMLElement Object ( [advertiser-id] => 2860239 [advertiser-name] => Amber Alert GPS [category] => Array ( [0] => children [1] => children ) [click-commission] => Array ( [0] => 0.0 [1] => 0.0 ) [creative-height] => Array ( [0] => 0 [1] => 0 ) [creative-width] => Array ( [0] => 0 [1] => 0 ) [language] => en [lead-commission] => SimpleXMLElement Object ( ) [link-code-html] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [link-code-javascript] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [description] => 20% discount of Amber Alert GPS Child Locator Device when using "Amber2" Promo Code. [destination] => http://www.amberalertgps.com [link-id] => 10745524 [link-name] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [link-type] => Text Link [performance-incentive] => false [promotion-end-date] => SimpleXMLElement Object ( ) [promotion-start-date] => SimpleXMLElement Object ( ) [promotion-type] => coupon [relationship-status] => joined [sale-commission] => 30.00% [seven-day-epc] => N/A [three-month-epc] => 2.66 ) I try to do this but it doesn't work: foreach($oXML->links->link as $o){ echo $o['advertiser-id']; } # I also tried this: foreach($oXML->links->link as $o){ echo $o->advertiser-id; } How do you echo the values? Hello, I have been working with PHP for many years, but have avoided XML parsing - now I know why. I am having some difficultly. In the following XML example, I am trying to read domain:name and domain:reason. I have struggled for the past 3 nights. Code: [Select] <?xml version="1.0" encoding="utf-8"?> <epp xmlns="urn:ietf:params:xml:ns:epp-1.0"> <response> <result code="1000"> <msg>Command completed successfully</msg> </result> <resData> <domain:chkData xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"> <domain:cd> <domain:name avail="0">foo.com</domain:name> <domain:reason>registered</domain:reason> </domain:cd> <domain:cd> <domain:name avail="0">foo.net</domain:name> <domain:reason>registered</domain:reason> </domain:cd> <domain:cd> <domain:name avail="0">foo.org</domain:name> <domain:reason>registered</domain:reason> </domain:cd> </domain:chkData> </resData> <trID> <svTRID>test-0000-0000</svTRID> </trID> </response> </epp> The code I am using is below. This assumes the above XML data is in a variable called $xmldata Code: [Select] $xml = new SimpleXMLElement($xmldata); foreach ($xml->response->resData as $entry){ $namespaces = $entry->getNameSpaces(true); $domain = $entry->children($namespaces['domain']); echo "Domain : " . $domain->name. "<br />"; echo "Domain : " . $domain->reason . "<br />"; } Can anyone advise where I am going wrong? Thanks in advance. Hello, I'm in need of help. Sometimes my PHP reads XML from a ssh and it tends to fail at times. Heres my complete error: Code: [Select] [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: Entity: line 3: parser error : Premature end of data in tag info line 2 in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: ^ in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/nmdgamin/public_html/private/includes/functions/revision.php:69 Stack trace: #0 /home/nmdgamin/public_html/private/includes/functions/revision.php(69): SimpleXMLElement->__construct('<?xml version="...') #1 /home/nmdgamin/public_html/private/includes/functions/update.php(16): CheckRemoteRevision('SpaceBuild') #2 /home/nmdgamin/public_html/prv_updater.php(13): Update() #3 {main} thrown in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 Remote function: function CheckRemoteRevision($Name){ if($Name){ if($Query = MySQLQuery('SELECT name, url, sv_revision FROM data WHERE name=\''. $Name .'\';')){ if($XMLFile = shell_exec('svn info \''. $Query['url'] .'\' --username anonsvn --password anonsvn --xml')){ if($DCheck = explode(' ', $XMLFile)){ if($DCheck[0] == 'svn:'){ $Revision = '0'; $Result = MySQLQuery('UPDATE data SET sv_revision=\''. $Revision .'\' WHERE name=\''. $Query['name'] .'\';'); return False; } } $XML = new SimpleXMLElement($XMLFile); foreach($XML->entry as $Attribute){ $Revision = $Attribute['revision']; } if($Query['sv_revision'] < $Revision || $Query["sv_revision"] != $Revision){ $Result = MySQLQuery('UPDATE data SET sv_revision=\''. $Revision .'\' WHERE name=\''. $Query['name'] .'\';'); } return $Revision; }else{ return False; } }else{ return False; } }else{ return False; } } How would I full proof this from getting this error again, It seems to happen at completely random times. I'm not very good with XML in PHP Thanks! Folks, I remember once having a php or html5 issue where the first option had to be blank in the drop down. Otherwise, it wasn't working. What wasn't working ? How wasn't working ? I can't remember. either php had difficulty reading user input or the drop down was not showing any options. And so, I had to add a blank value. So, something like this wasn't working ...
<label for="tos_agreement">Agree to TOS or not ?</label> <select name="tos_agreement" id="tos_agreement"> <option value="yes">Yes</option> <option value="no">No</option> </select>
And, I think I added a blank value, at somebody's advice, to get it to work. I think it was something like this, if I remember correctly:
<label for="tos_agreement">Agree to TOS or not ?</label> <select name="tos_agreement" id="tos_agreement"> <option value=" ">Select here</option> <option value="yes">Yes</option> <option value="no">No</option> </select>
Or, maybe it was something like this:
<label for="tos_agreement">Agree to TOS or not ?</label> <select name="tos_agreement" id="tos_agreement"> <option value=" "></option> <option value="yes">Yes</option> <option value="no">No</option> </select>
I can't remember. All I remember slightly that there was a blank value. I been going through my php files to find that particular file to jog my memory but I failed to find it. Can you folks explain to me if a blank value is required or not ? What is the benefit/disaster of adding it and how should the blank value be added ? Show me an example.
Was this a php or html 5 issue ? Can anybody fugure ?
Thank You Hi, I have this code below which groups all the SubHeading together and then queries the same table to find RiskConsequence which are grouped that match SubHeading then to query this table one more last time with all the Risk Mitigation that matches the grouped RiskConsequence. Problem I get is it does the SubHeading, the RiskConsequences it only does one of them not all of them before it moves onto the RiskMitigation. I know I have a php coding issue just cant see the wood from the tree's as the queries work. Code: [Select] <?php include ("include.php"); $query = "SELECT * FROM tblriskassessmentdatabank GROUP BY SubHeading"; $results = mysql_query($query) or die("Error: " . mysql_error()); while($row1 = mysql_fetch_array($results)){ echo'<a href="#" onClick="return(changeDisplay(';echo"'";echo($row1[SubHeading]);echo"'))";echo'">';echo($row1[SubHeading]);echo'</a><br /><br />'; echo'<div id="';echo($row1[SubHeading]); echo'" class="HideText">'; $risksub = $row1[SubHeading]; $query1 = "SELECT * FROM tblriskassessmentdatabank GROUP By RiskConsequence"; $results1 = mysql_query($query1) or die("Error: " . mysql_error()); while($row2 = mysql_fetch_array($results1)){ echo'<a href="#" onClick="return(changeDisplay(';echo"'";echo($row2[RiskConsequence]);echo"'))";echo'">';echo($row2[RiskConsequence]);echo'</a><br />'; echo'<div id="';echo($row2[RiskConsequence]); echo'" class="HideText">'; $risksub1 = $row2[RiskConsequence]; $query1 = "SELECT * FROM tblriskassessmentdatabank WHERE RiskConsequence = '$risksub1'"; $results1 = mysql_query($query1) or die("Error: " . mysql_error()); while($row3 = mysql_fetch_array($results1)){ echo'<input name="checkbox[]" type="checkbox" id="checkbox[]" value="';echo($row3[IssueNumber]);echo'" /> <label for="checkbox[]"></label>';echo($row3[RiskMitigation]);echo'<br /><br />'; } echo'</div>'; } echo'</div>'; } ?> I have a script that saves a full size and a cropped version that is re-sized to 200x200. The full size saves just fine the cropped and re-sized version is all messed up. Example: Here is the cropped and re-size code: Code: [Select] $new_cropped_image_resource = imagecreatetruecolor(200, 200); switch($photo["ext"]){ case "gif": $cropped_image = imagecreatefromgif($processing_image_temp_name_cropped); break; case "jpg": $cropped_image = imagecreatefromjpeg($processing_image_temp_name_cropped); break; case "png": $cropped_image = imagecreatefrompng($processing_image_temp_name_cropped); break; } list($cropped_width, $cropped_height) = getimagesize($processing_image_temp_name_cropped); imagecopyresampled($new_cropped_image_resource,$cropped_image,0,0,0,0,200,200,$cropped_width,$cropped_height); switch($photo["ext"]){ case "gif": imagegif($new_cropped_image_resource, $processing_image_temp_name_cropped); break; case "jpg": imagejpeg($new_cropped_image_resource, $processing_image_temp_name_cropped, 100); break; case "png": imagepng($new_cropped_image_resource, $processing_image_temp_name_cropped); break; } Any ideas? I'm stuck :/ Thanks for any help -Shane Greetings =), seems i'm stumped again. lol What I want to do is check to see if a row exists if it does assign the variable to the $deposit variable to $row['price_each'] If it does not exist, i want it to assign the variable $deposit = 0 Here is my code, I think I am doing something wrong, becuase it keeps giving me the undefined variable for $deposit, when the statment i wrote should make it work. I think my syntax is off, or my ==0 is in the wrong place. I'm not too expierenced with php and i'm still learning. Any help would be greatly appreciated! Code: [Select] $deposit_query2 = mysql_query("SELECT * FROM invoice_entries, sku_codes WHERE invoice_entries.invoice_number = $invoice_number AND invoice_entries.sku_number = sku_codes.sku AND sku_codes.sku = 01-00") or die(mysql_error()); if ($row = mysql_fetch_array($deposit_query2)==0 ) { $deposit = $row['price_each']; } else { $deposit = 0; } I run this query in TOAD ( database management application ) and it returns to me the date that a specified table was last updated. Code: [Select] $qry = "SELECT to_char(LAST_DDL_TIME, 'MM/DD/YYYY') AS LASTUPDATED FROM all_objects WHERE owner = 'USER' AND object_name = 'TABLENAME'"; $go = oci_parse($conn, $qry); oci_execute($go); $result = oci_fetch_assoc($go) echo = $result['LASTUPDATED']; However when i run that identical query through PHP i get absolutely NOTHING. Any idea if perhaps PHP isnt capable of retreiving such data or if maybe i'm doing something wrong. Thanks! Hi guys I have IPN setup for my online shop which is working fine but when payment is confirmed, my shop should send a link confirming purchase along with list of items, so I have added that to my IPN, there is an issue, it owuldnt send the email, I have checked every table/column name and they are correct, IPN works because I receive paypal confirmation email and updates database, so something should be wrong with they way I have written the code to send this email. Please find the code below, I have deleted some un-necessary info: Code: [Select] <? include ('includes/db.php'); // PHP 4.1 // read the post from PayPal system and add 'cmd' $req = 'cmd=_notify-validate'; foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } // post back to PayPal system to validate $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($req) . "\r\n\r\n"; $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); // assign posted variables to local variables $item_name = $_POST['item_name']; $item_number = $_POST['item_number']; $payment_status = $_POST['payment_status']; $payment_amount = $_POST['mc_gross']; $payment_currency = $_POST['mc_currency']; $txn_id = $_POST['txn_id']; $receiver_email = $_POST['receiver_email']; $payer_email = $_POST['payer_email']; $order_id = mysql_real_escape_string((int)$_POST['custom']); if (!$fp) { // HTTP ERROR } else { fputs ($fp, $header . $req); while (!feof($fp)) { $res = fgets ($fp, 1024); if (strcmp ($res, "VERIFIED") == 0) { if ($payment_status=='Completed') { $txn_check=mysql_query("SELECT txn_id FROM orders WHERE txn_id='$txn_id'"); if (mysql_num_rows($txn_check)!=1) { if($receiver_email=='me@mydomain.com'){ ////////// $get=mysql_query("SELECT amount FROM orders WHERE amount='$payment_amount'"); while ($get_row=mysql_fetch_array($get)) { $amount=$get_row['amount']; } if($amount==$payment_amount && $payment_currency=='GBP') { $update=mysql_query("UPDATE orders SET confirmed='1', txn_id='$txn_id' WHERE order_ref='$order_id'"); $select=mysql_query("SELECT * FROM ordered_product WHERE order_ref='$order_id'"); while($row=mysql_fetch_array($select)) { $product_number=$row['product_ref']; $quantity_ordered=$row['quantity_ordered']; $update=mysql_query("UPDATE products SET instock=instock-1 WHERE product_ref='$product_number'"); } $select=mysql_query("SELECT * FROM orders WHERE order_ref='order_id' AND confirmed='1'"); while ($row=mysql_fetch_array($select)) { $order_number=$row['order_ref']; $name=$row['user_name']; $email=$row['user_email']; $address1=$row['address_1']; $address2=$row['address_2']; $address3=$row['address_3']; $city=$row['city']; $postcode=$row['postcode']; $country=$row['country']; $amount=$row['txn_id']; $date=$row['order_date']; } $select=mysql_query("SELECT * FROM ordered_product WHERE order_ref='$order_id'"); while($get_row=mysql_fetch_array($select)) { $product_ref=$get_row['product_ref']; $quantity=$get_row['quantity_ordered']; } $select=mysql_query("SELECT * FROM products WHERE product_ref='$product_ref'"); while($get_row=mysql_fetch_array($select)) { $product_name=$get_row['product_name']; $product_price=$get_row['price']; echo "<table width='439' border='0' cellspacing='0' cellpadding='0'> <tr> <td width='219'>$product_name</td> <td width='120'>$quantity</td> <td width='98'>£$product_price</td> </tr> </table>"; } ///////// $headers=array( 'From:me@mydomain.com', 'Content-Type:text/html' ); $body="<table width='492' border='0' cellspacing='0' cellpadding='0' style='font-family:Verdana, Geneva, sans-serif; font-size:12px; color:#333;'> <tr> <td width='492' height='374' valign='top'><table width='497' border='0' cellspacing='0' cellpadding='0'> <tr> <td width='497' height='97'><img src='../images/logo.png'/></td> </tr> <tr> <td>Thank you for ordering. Your order should arrive in the next 2-3 days.</td> </tr> <tr> <td height='48'><strong>ORDER NUMBER:</strong> $order_number</td> </tr> <tr> <td height='48'><p><strong>DELIVERY ADDRESS: </strong></p> <p>$address1 <br/> $address2 <br/> $address3 <br/> $city <br/> $postcode <br/> $country</p> <p> </p></td> </tr> <tr> <td height='48'><p><strong>YOUR ORDER:</strong></p> <table width='439' border='0' cellspacing='0' cellpadding='0'> <tr> <td width='219'><strong>Item</strong></td> <td width='120'><strong>Quantity</strong></td> <td width='98'><strong>Price</strong></td> </tr> </table><br/> <table width='439' border='0' cellspacing='0' cellpadding='0'> <tr> <td width='219'>$product_name</td> <td width='120'>$quantity</td> <td width='98'>£$product_price</td> </tr> </table> <p> </p></td> </tr> <tr> <td height='48'><p><strong>Sub Total:</strong> £amount<br/> </p></td> </tr> </table></td> </tr> <tr> <td height='374' valign='top'><strong>N.B Any sales items are non-returnable</strong></td> </tr> </table> "; $subject = "ORDER CONFIRMATION - "; mail($to, $subject, $body, implode("\r\n",$headers)); } //////// } } } } else if (strcmp ($res, "INVALID") == 0) { header('Location: payment-error.php'); } } fclose ($fp); } ?> Thank you all in advance A friend told me vaguely that there is a possible insecurity with a RFI, in my dynamic image, that reads a players stats off of a seprate web page, parses it, and prints it on the image: <?php Header ('Content-type: image/jpeg'); Header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); Header('Expires: Thu, 19 Nov 1981 08:52:00 GMT'); Header('Pragma: no-cache'); // get CMID variable from the url $cmid = htmlentities($_GET['cmid']); if ($cmid < 100000 or $cmid > 999999); $cmid = 563853; elseif ($cmid > 100000 and $cmid < 999999); $cmid = $cmid; else $cmid = 563853; // create the image using your own background $image = imagecreatefromjpeg("background.jpg"); // dimensions of the image used $img_width = 600; $img_height = 9; // set the colours $cool = imagecolorallocate($image, 81, 86, 96); $black = imagecolorallocate($image, 0, 0, 0); $white = imagecolorallocate($image, 255, 255, 255); $red = imagecolorallocate($image, 255, 0, 0); $grey = imagecolorallocate($image, 204, 204, 204); $green = imagecolorallocate($image, 206, 129, 18); $blue = imagecolorallocate($image, 0, 0, 255); $yellow = imagecolorallocate($image, 225, 225, 0); $statcolor = $yellow; // set the font and print text $font = 'Verdana.ttf'; /* // counter - CHMOD your counter file to 777 $viewss = file("views.txt"); $views = $viewss[0]; $views++; $fp = fopen("views.txt", "w"); fwrite($fp, $views); fclose($fp); $counter = "$views"; // View Output imagettftext($image, 7, 0, 16, 117, $yellow, $font, "Views:$counter"); */ // Attempt to make web content grabber. function get_url_contents($url){ $crl = curl_init(); $timeout = 5; curl_setopt ($crl, CURLOPT_URL,$url); curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout); $ret = curl_exec($crl); curl_close($crl); return $ret; } // Web content grabber execution. $returned_content = get_url_contents("http://uberstrike.cmune.com/Profile?cmid=$cmid"); // Parsing the returned content for Global Rank. $clanstart = strpos($returned_content, 'Clan:'); $clanend = strpos($returned_content, '</h2>', $clanstart); $clanunref = substr($returned_content, $clanstart, $clanend); $clanrefstart = strpos($clanunref, '['); $clanrefend = strpos($clanunref, ']', $clanrefstart); $clan = substr($clanunref, $clanrefstart, $clanrefend); $clan = html_entity_decode(strip_tags($clan)); // Stripping the parsed Global Rank of HTML. $clan = html_entity_decode(strip_tags($clan)); // Filtering Clan to only show the value number, not text or formatting in between. $clan = str_replace ("C", "", $clan); $clan = str_replace ("l", "", $clan); $clan = str_replace ("a", "", $clan); $clan = str_replace ("n", "", $clan); $clan = str_replace (":", "", $clan); $clan = str_replace (" ", "", $clan); // Parsing the returned content for Name. $namestart = strpos($returned_content, '<span style="color: #FEC42C; font-size: 20px; font-weight: bold;">'); $nameend = strpos($returned_content, '</span>', $namestart); $name = substr($returned_content, $namestart, $nameend-$namestart); // Stripping the parsed Name of HTML elements. $name = html_entity_decode(strip_tags($name)); // Clan and name output. imagettftext($image, 7, 0, 50, 7, $yellow, $font, "$clan" . "$name"); // Parsing the returned content for Global Rank. $rankstart = strpos($returned_content, '<h2 style="font-size:14px; font-weight:bold; text-indent:0px; margin-left:25px;">'); $rankend = strpos($returned_content, '<br />', $rankstart); $rank = substr($returned_content, $rankstart, $rankend-$rankstart); // Stripping the parsed Global Rank of HTML. $rank = html_entity_decode(strip_tags($rank)); // Filtering Rank to only show the value number, not text or formatting in between. $rank = str_replace ("G", "", $rank); $rank = str_replace ("l", "", $rank); $rank = str_replace ("o", "", $rank); $rank = str_replace ("b", "", $rank); $rank = str_replace ("a", "", $rank); $rank = str_replace ("R", "", $rank); $rank = str_replace ("n", "", $rank); $rank = str_replace ("k", "", $rank); $rank = str_replace (":", "", $rank); $rank = str_replace (" ", "", $rank); // Rank Output. imagettftext($image, 7, 0, 230, 7, $yellow, $font, "$rank"); $killstart = strpos($returned_content, '<h3 style="color: #FEC42C;">All time record</h3>'); $killend = strpos($returned_content, '</tr>', $killstart); $kill = substr($returned_content, $killstart, $killend-$killstart); // Stripping the parsed kill of HTML. $kill = html_entity_decode(strip_tags($kill)); // Filtering kill to only show the value number, not text or formatting in between. $kill = str_replace ("K", "", $kill); $kill = str_replace ("i", "", $kill); $kill = str_replace ("l", "", $kill); $kill = str_replace ("A", "", $kill); $kill = str_replace ("t", "", $kill); $kill = str_replace ("m", "", $kill); $kill = str_replace ("e", "", $kill); $kill = str_replace ("r", "", $kill); $kill = str_replace ("o", "", $kill); $kill = str_replace ("d", "", $kill); $kill = str_replace ("c", "", $kill); $kill = str_replace ("s", "", $kill); $kill = str_replace (" ", "", $kill); $kill = trim($kill); // Cannon Stats output. imagettftext($image, 7, 0, 410, 7, $yellow, $font, $kill); // Parsing the returned content for KDR. $KDRstart = strpos($returned_content, '<span title="Kill Death Ratio">KDR</span>'); $KDRend = strpos($returned_content, '</tr>', $KDRstart); $KDR = substr($returned_content, $KDRstart, $KDRend-$KDRstart); // Stripping the parsed KDR of HTML. $KDR = html_entity_decode(strip_tags($KDR)); // Filtering KDR to only show the value number, not text or formatting in between. $KDR = str_replace ("K", "", $KDR); $KDR = str_replace ("D", "", $KDR); $KDR = str_replace ("R", "", $KDR); $KDR = str_replace (" ", "", $KDR); $KDR = trim($KDR); // KDR Output. imagettftext($image, 7, 0, 323, 7, $yellow, $font, "$KDR"); // IP Logger $logfile= 'iplog.html'; $IPlog = $_SERVER['REMOTE_ADDR']; $logdetails= date("F j, Y, g:i a") . ': ' . '<a href=http://www.ip2location.com/demo.aspx?ip='.$_SERVER['REMOTE_ADDR'].'>'.$_SERVER['REMOTE_ADDR'].'</a>'; $fplog = fopen($logfile, "a"); fwrite($fplog, $logdetails); fwrite($fplog, "<br>"); fclose($fplog); // output and destroy imagepng($image); imagedestroy($image); ?> I have a page showing a list of events from tournaments/leagues (http://www.americandartsdatabase.com/player-rankings/included-leagues-tournaments/) If you click on the CLICK HERE link, it should come up with a page that shows the stats for that particular event. Some events it works and some it does not. 11th Annual ABDA Nationals works fine North Side Dart League does not work Code: [Select] Below is the list of tournaments and leagues that are included in the rankings. If you wish to have your tournaments and/or leagues included in the rankings, please register and send me the stats. <?php $mynewdate = strftime("%Y-%m-%d", strtotime("-730 days")); echo "<font color=red><b>Included are leagues and tournaments from " . $mynewdate . " to today.</b></font>"; $dbh=mysql_connect ("localhost", "database", "password") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("database"); $query = "SELECT `event`, `date` FROM `stats` WHERE `date` >= '$mynewdate' GROUP BY `event` ,`date` ORDER BY `date`"; $rank = 0; $rankh = 0; $result = mysql_query($query,$dbh) or die(mysql_error()); ?> <table align=center width=90%> <tr> <th align="left">League/Tournament</th> <th align="left">Date</th> <th align="left">View Stats</th> </tr> <?php while($row = mysql_fetch_array($result)) { $event = $row['event']; $year = $row['date']; $url = "<a href=\"http://www.americandartsdatabase.com/player-rankings/included-leagues-tournaments/stats/?event=" . $event . "&year=" . $year . "\">Click Here</a>"; echo "<tr>"; echo "<td>" . $event . "</td>"; echo "<td>" . $year . "</td>"; echo "<td>" . $url . "</td>"; echo "</tr>"; } ?> </table> Here is the STATS code Code: [Select] <?php $event = $_GET['event']; $date= $_GET['year']; $rank = 0; echo "<h1>Event: " . $event . "</h1><br>"; echo "<h1>Date: " . $date . "</h1><br>"; $dbh=mysql_connect ("localhost", "database", "password") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("database"); $query = "SELECT `firstname`, `lastname`, `games`, `points`, `event`, `date`, (`points`/`games`) FROM `stats` WHERE `event` = '$event' and `date` = '$date' ORDER BY (`points`/`games`) DESC"; $result = mysql_query($query,$dbh) or die(mysql_error()); ?> <table align=center width=100%> <tr> <th align="left">Rank</th> <th align="left">Player</th> <th align="left">Games</th> <th align="left">Points</th> <th align="left">Average</th> </tr> <?php while($row = mysql_fetch_array($result)) { $rank = $rank + 1; echo "<tr>"; echo "<td>" . $rank . "</td>"; echo "<td>" . $row['firstname'] . " " . $row['lastname'] . "</td>"; echo "<td>" . $row['games'] . "</td>"; echo "<td>" . $row['points'] . "</td>"; echo "<td>" . number_format(($row['points']/$row['games']),4) . "</td>"; echo "</tr>"; } ?> </table> How can I make it say... if none of the values in the array = $is_assoicate then do stuff... Right now it adds an li every time a value is not in the array. I only want it to add in 1 LI Code: [Select] <?php foreach($users_associates as $is_associate) { if ($is_associate['user_id'] != $user_info['uid']) { ?> <li class="bass"> <a href="" title="Become Associates" id="becomeassoc" class="mll"> <span class="f_right">Become Associates</span><img src="../assets/img/becomeassoc.jpg" class="mrs vmiddle" alt="Become Associates" /> </a> </li> <?php } } ?> hi phpfreaks, I have been using learning the pdo library. But I am really stuck on this one query. The above sql statement works if in phpadmin I get three results but for the life of me I can't get them with the code below. I have tried I am trying to return all columns in an array some thing like array (0=>array(0=>business blah, etc ) I have been playing with the fetch mode to try and achieve this but I can't get any results not even an obj but I am not getting any errors. Is the code below wrong? Code: [Select] $query = "SELECT Business_Name,First_Name,Last_Name,Username,Email,Phone,Mobile,Social_Media,Web_Site,User_Language,Admin_Level FROM customer WHERE Admin_Level ='Admi'"; try { //$this->dataObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->dataObj->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); $sth = $this->dataObj->prepare($query); $stmt = $this->dataObj->query($query); $stmt->setFetchMode(); $result = $stmt->fetchAll(); } catch (PDOException $e) { $e->getMessage(); } return $result; } I have written the following PHP script. It is working ok but I having problem with the AM and PM issue here. My script cannot differentiate AM and PM. Please help me.. Thanks in Advance <?php $d=("1:01 AM"); if ($d < "2:00 PM") echo "Present"; elseif ($d > "2:00") echo "Late"; elseif ($d == "2:00") echo "Equal"; else echo "Have a nice day!"; ?> HI there im having a problem with updating one table with anopther tables contents atm i have this code: Code: [Select] if($sql) { $msg = "Taxi Accepted sucessfully."; mysql_query("INSERT INTO user_location ( User_ID,User_Longitude,User_Latitude) SELECT User_ID,User_Longitude,User_Latitude FROM quotes") or die (mysql_error()); } else { $msg = "Taxi not Accepted sucssfully try again."; echo "$msg"; } The error message im getting is :Duplicate entry '1' for key 1 :S any help at all Thank You Hi everyone... My script register01.php isnt working as expected, it should take variables from register00.php and insert them into the db. It is currently re-loading itself and not inserting, could you take a look at this for me: register00.php Code: [Select] <form enctype="multipart/form-data" method="post" action="register01.php"> <table width="316" height="120" border="0"> <tr><td colspan=2><h1>Register/Sign Up</h1></td></tr> <tr><td>Company Name:</td><td> <input name="company_name" type="text" id="company_name"> </td></tr> <tr><td>Contact Name:</td><td> <input name="contact_name" type="text" id="contact_name"> </td></tr> <tr><td>Contact Number:</td><td> <input name="phone" type="number" id="phone" value="incl. area code"> </td></tr> <tr><td>Address line 1:</td><td> <input name="street1" type="text" id="street1"> </td></tr> <tr><td>Address line 2:</td><td> <input name="street2" type="text" id="street1"> </td></tr> <tr><td>Area:</td><td> <input name="location" type="text" id="location"> </td></tr> <tr><td>City:</td><td> <input name="city" type="text" id="city"> </td></tr> <tr><td>Postcode:</td><td> <input name="postcode" type="text" id="postcode"> </td></tr> <tr><td>Username:</td><td> <input name="username" type="text" id="username"> </td></tr> <tr><td>Password:</td><td> <input name="password" type="password" class="style7" id="password"> </td></tr> <tr><td>Email:</td><td> <input name="email" type="text" class="style7" id="email"> </td></tr> <tr><td>Company Logo:</td><td> <input name="upload" type="file" class="style7" id="upload"> </td></tr> <tr><td>Company Description:</td><td> <textarea rows="20" cols="50" name="premiumuser_description" id="premiumuser_description"></textarea> </td></tr> <tr><td> <input name="Submit" type="submit" value="Register" /> </td></tr> </table> register01.php Code: [Select] <?PHP session_start(); include('db.php'); /* set some validation variables */ $error_message = ""; /* DEFINE THE FUNCTION */ /* ============================================== */ /* ============================================== */ /* DO NOT MODIFY THIS FUNCTION */ function Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path) { $s_path = trim($s_path); $o_path = trim($o_path); $save = $s_path . $save; $file = $o_path . $file; $ext = strtolower(end(explode('.',$save))); list($width, $height) = getimagesize($file) ; if(($width>$t_w) OR ($height>$t_h)) { $r1 = $t_w/$width; $r2 = $t_h/$height; if($r1<$r2) { $size = $t_w/$width; }else{ $size = $t_h/$height; } }else{ $size=1; } $modwidth = $width * $size; $modheight = $height * $size; $tn = imagecreatetruecolor($modwidth, $modheight) ; switch ($ext) { case 'jpg': case 'jpeg': $image = imagecreatefromjpeg($file) ; break; case 'gif': $image = imagecreatefromgif($file) ; break; case 'png': $image = imagecreatefrompng($file) ; break; } imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; imagejpeg($tn, $save, 100) ; return; } /* END OF RESIZE FUNCTION */ //This is the directory where images will be saved $target = "/home/users/web/b109/ipg.removalspacecom/images/COMPANIES/"; $target = $target . basename( $_FILES['upload']['name']); // Connects to your Database session_start(); include ('db.php'); //This gets all the other information from the form /* ============================================== */ /* ============================================== */ /* YOU NEED TO DO SOME VALIDATION AND SANITIZING OF YOUR FORM DATA */ if((!isset($_POST['company_name'])) || (strlen(trim($_POST['company_name'])) <5) || (trim($_POST['company_name']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['company_name'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid company name<br>"; $error_message = $error_message . "Valid names are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['company_name'] . "</font><hr>"; } /* END validating company_name */ /* =============================================== */ if((!isset($_POST['contact_name'])) || (strlen(trim($_POST['contact_name'])) <5) || (trim($_POST['contact_name']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['contact_name'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid contact name<br>"; $error_message = $error_message . "Valid names are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['contact_name'] . "</font><hr>"; } /* END validating contact_name */ /* =============================================== */ if((!isset($_POST['phone'])) || (strlen(trim($_POST['phone'])) <5) || (trim($_POST['phone']) != preg_replace("/[^0-9\s\-\_]/", "", trim($_POST['phone'])))) { /* if it is NOT set, then set the error variable and start building the error message */ $error_message = $error_message . "You must enter a valid phone<br>"; $error_message = $error_message . "Valid phones are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid phone was: <font color="red">' . $_POST['phone'] . "</font><hr>"; }else{ $phone = trim($_POST['phone']); } /* END validating phone */ /* =============================================== */ /* =============================================== */ /* validating the email */ /* create a function */ function validateEmailAddress($email) { return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email); } if(!isset($_POST['email']) || validateEmailAddress($_POST['email']) !=1) { $error_message = $error_message . "You must enter a valid email address<br>"; $error_message = $error_message . 'The invalid email was: <font color="red">' . $_POST['email'] . "</font><hr>"; } /* END validating email */ /* =============================================== */ if((!isset($_POST['street1'])) || (strlen(trim($_POST['street1'])) <5) || (trim($_POST['street1']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['street1'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid address<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['street1'] . "</font><hr>"; } /* END validating street1 */ /* =============================================== */ if((!isset($_POST['street2'])) || (strlen(trim($_POST['street2'])) <5) || (trim($_POST['street2']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['street2'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid address<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['street2'] . "</font><hr>"; } /* END validating street2 */ /* =============================================== */ if((!isset($_POST['premiumuser_description'])) || (strlen(trim($_POST['premiumuser_description'])) <5) || (trim($_POST['premiumuser_description']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['premiumuser_description'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid address<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['premiumuser_description'] . "</font><hr>"; } /* END validating premiumuser_description */ /* =============================================== * /* =============================================== */ /* this section of code will set up an error message for the username if ANY of the conditions occur 1) checks to see if $_POST['username'] is NOT set 2) if length of username is less than 5 3) if username has anything other than letter, numbers or underscores */ if((!isset($_POST['username'])) || (strlen(trim($_POST['username'])) <5) || (trim($_POST['username']) != preg_replace("/[^a-zA-Z0-9\_]/", "", trim($_POST['username'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid username<br>"; $error_message = $error_message . "Valid names are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['username'] . "</font><hr>"; } /* END validating username */ /* =============================================== */ /* =============================================== */ /* this section of code will set up an error message for the password if ANY of the conditions occur 1) checks to see if $_POST['upassword'] is NOT set 2) if length of upassword is less than 5 3) if upassword has anything other than letter, numbers or underscores */ if((!isset($_POST['password'])) || (strlen(trim($_POST['password'])) <5) || (trim($_POST['password']) != preg_replace("/[^a-zA-Z0-9\_]/", "", trim($_POST['password'])))) { /* if it is NOT set, then set the error variable and start building the error message */ $error_message = $error_message . "You must enter a valid password<br>"; $error_message = $error_message . "Valid passwords are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid password was: <font color="red">' . $_POST['password'] . "</font><hr>"; }else{ $password = trim($_POST['password']); } /* END validating password */ /* =============================================== */ /* =============================================== */ /* check to see if username is already taken */ $username = mysql_real_escape_string(trim($_POST['username'])); $query1 = "SELECT username from companies WHERE username = '$username'"; $result1 = mysql_query($query1) or die(mysql_error()); $count = mysql_num_rows($result1); if($count>0) { $error_message = $error_message . 'The username: <font color="red">' . $_POST['username'] . "</font> is taken.<hr>"; } /* =============================================== */ /* if any of the post variables are invalid */ /* set the session variable and send back to the form page */ if(strlen(trim($error_message))>0) { $_SESSION['error_message'] =$error_message; header("Location: register00.php"); exit(); } /* =============================================== */ $uploadDir = 'images/COMPANIES'; /* main picture folder */ $max_height = 450; /* largest height you allowed; 0 means any */ $max_width = 450; /* largest width you allowed; 0 means any */ $max_file = 2000000; /* set the max file size in bytes */ $image_overwrite = 1; /* 0 means overwite; 1 means new name */ /* add or delete allowed image types */ $allowed_type01 = array( "image/gif", "image/pjpeg", "image/jpeg", "image/png", "image/x-png", "image/jpg"); $do_thumb = 1; /* 1 make thumbnails; 0 means do NOT make */ $thumbDir = "/images/thumbs"; /* thumbnail folder */ $thumb_prefix = ""; /* prefix for thumbnails */ $thumb_width = 90; /* max thumb width */ $thumb_height = 70; // max thumb height //Writes the photo to the server if(move_uploaded_file($_FILES['upload']['tmp_name'], $target)) { /* HERE IS WHERE WE WILL DO THE ACTUAL RESIZING */ /* ============================================== */ /* ============================================== */ /* THESE SIX PARAMETERS MAY BE CHANGED TO SUIT YOUR NEEDS */ $o_path ="images/COMPANIES/"; $s_path = "images/thumbs/"; $file = $upload; $save = $file; $t_w = 200; $t_h = 150; /* ============================================== */ /* ============================================== */ /* DO NOT CHANGE THIS NEXT LINE */ Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path); //Tells you if its all ok /* ============================================== */ /* ============================================== */ /* PROVIDE A WAY FOR THEM TO GO SOMWHERE */ echo "The file ". $file . " has been uploaded, and your information has been added to the directory"; }else { //Gives and error if its not /* ============================================== */ /* ============================================== */ /* PROVIDE A WAY FOR THEM TO GO SOMWHERE */ echo "Sorry, there was a problem uploading your file."; } /* =============================================== */ /* PREPARE DATA FOR INSERTION INTO TABLE */ /* FUNCTION TO CREATE SALT */ function createSalt() { $string = md5(uniqid(rand(), true)); return substr($string, 0, 3); } //Writes the information to the database /* ============================================== */ /* ============================================== */ /* ALWAYS WRITE YOUR QUERIES AS STRINGS THAT WAY WHEN TESTING, YOU CAN MAKE SURE THAT THE VALUES CONTAIN WHAT YOU EXPECT */ $salt = createsalt(); $passwod = trim($_POST['password']); $hash = hash('sha256', $salt, $password); $approved = 0; $username = mysql_real_escape_string(trim($_POST['username'])); $email = mysql_real_escape_string(trim($_POST['email'])); $query ="INSERT INTO `companies` (company_name, contact_name, location, postcode, street1, street2, city, phone, email, basicpackage_description, premiumuser_description, password, salt, approved, upload) VALUES ('$company_name', '$contact_name', '$location', '$postcode', '$street1', '$street2', '$city', '$phone', '$email', '$basicpackage_description', '$premiumuser_description', '$password', '$salt', '$approved', '$upload')"; $result = mysql_query($query) or die(mysql_error()); /* =============================================== */ /* at this point we can send an email to the admin as well as the user. DO NOT send the user's password to ANYONE!!!! */ ?> Thank you for registering.<br>; Your account will be approved and activated within 24 hours.<br><br> Click here to return to the <a href="index.php">main page</a>. |