PHP - Urgent: Using Curl To Get Rss Feed Fails - Think I Am Really Close... Help!
I am creating this feature for a client of mine that needs it working by tomorrow!
I am trying to use cURL to grab the RSS feed he http://blogs.menshealth.com/fitness-pros/feed But all I get back is an empty string... Please help - I've been searching Google & this forum but haven't found anything that I can use that fixes this issue. $feed = getRssData(); echo "<pre>\n"; print_r( $feed ); echo "\n</pre>\n"; function getRssData() { // returns the feed array $requested_feed = "http://blogs.menshealth.com/fitness-pros/feed"; $ch = curl_init($requested_feed); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $rss_data = curl_exec($ch); curl_close($ch); echo "RSS DATA: <br />\n" . $rss_data; $doc = new DOMDocument(); $doc->load($rss_data); $arrFeeds = array(); foreach ($doc->getElementsByTagName('item') as $node) { $itemRSS = array ( 'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue ); array_push($arrFeeds, $itemRSS); } return $arrFeeds; } You can see a live test he http://pro-formpt.com/get_rss.php?feed=workout It only has a few parameters in it so I can use the same file to grab other RSS Feeds as well - but they all fail the same way. Like this one: http://pro-formpt.com/get_rss.php?feed=living Which should grab the feed from he http://blogs.menshealth.com/mh-life/feed I truly appreciate any suggestions! Thanks! Similar TutorialsHello PHP Freaks! I have the following PHP Curl code which is supposed to fetch the twitter timeline feed for a specific username and parse and display it on a page, but for some reason Curl is unable to fetch data from twitter: Code: [Select] <?php function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } $json = get_data("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=digioz&count=2"); if ($json != false) { $obj = json_decode($json); foreach($obj as $var => $value) { echo "Message number: $var <br/>"; echo "Name: " . $obj[$var]->user->name; echo "Handle: " . $obj[$var]->user->screen_name . "<br/>"; echo "Message: " . $obj[$var]->text; echo "Created" . $obj[$var]->created_at . "<br/>"; echo "URL" . $obj[$var]->user->url . "<br/>"; echo "Location" . $obj[$var]->user->location . "<br/>"; echo "<br/>"; } } else { echo "Could not fetch Twitter Data"; } ?> Anyone have any idea why the data is not being fetched? If I copy and paste the URL into my browser window it returns results just fine, so I know the problem is not with the URL. Thanks, Pete Hi All, My goal is to process all redirects serverside and simply return the user to the 'final' URL. Here's my function to get the final URL: PHP Code: function get_final_url($url){ global $final_host; $redirects = get_all_redirects($url); if (count($redirects)>0){ $final_url = array_pop($redirects); if(substr($final_url,0,7) != 'http://' && !empty($final_host)) { $final_url = 'http://'.$final_host.$final_url; } return $final_url; } else { return $url; } Here's the cURL execution: $ch2 = curl_init(); curl_setopt($ch2,CURLOPT_URL,$url); curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch2,CURLOPT_POST,''); curl_setopt($ch2,CURLOPT_POSTFIELDS,''); curl_exec($ch2); curl_close($ch2); For some reason, this works no problem, posts any data over to the URLs serverside, redirects serverside, and passes the client to the final URL, with none of the redirection displayed via HTTPWatch or any similar debug utility. Sometimes, however, it does show phases of redirection. Any insight into what I might be doing incorrectly? Thanks SO much in advance. E good day dear community, i am workin on a Curl loop to fetch multiple pages: i have some examples - and a question: Example: If we want to get information from 3 sites with CURL we can do it like so: $list[1] = "http://www.example1.com"; $list[2] = "ftp://example.com"; $list[3] = "http://www.example2.com"; After creating the list of links we should initialize the cURL multi handle and adding the cURL handles. $curlHandle = curl_multi_init(); for ($i = 1;$i <= 3; $i++) $curl[$i] = addHandle($curlHandle,$list[$i]); Now we should execute the cURL multi handle retrive the content from the sub handles that we added to the cURL multi handle. ExecHandle($curlHandle); for ($i = 1;$i <= 3; $i++) { $text[$i] = curl_multi_getcontent ($curl[$i]); echo $text[$i]; } In the end we should release the handles from the cURL multi handle by calling curl_multi_remove_handle and close the cURL multi handle! If we want to another Fetch of sites with cURL-Multi - since this is the most pretty way to do it! Well I am not sure bout the string concatenation. How to do it - Note I want to fetch several hundred pages: see the some details for this target-server sites - /(I have to create a loop over several hundred sites). * siteone.example/?show_subsite=9009 * siteone.example/?show_subsite=9742 * siteone.example/?show_subsite=9871 .... and so on and so forth Question: How to appy this loop into the array of the curl-multi? <?php /************************************\ * Multi interface in PHP with curl * * Requires PHP 5.0, Apache 2.0 and * * Curl * ************************************* * Writen By Cyborg 19671897 * * Bugfixed by Jeremy Ellman * \***********************************/ $urls = array( "siteone", "sitetwo", "sitethree" ); $mh = curl_multi_init(); foreach ($urls as $i => $url) { $conn[$i]=curl_init($url); curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1);//return data as string curl_setopt($conn[$i],CURLOPT_FOLLOWLOCATION,1);//follow redirects curl_setopt($conn[$i],CURLOPT_MAXREDIRS,2);//maximum redirects curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,10);//timeout curl_multi_add_handle ($mh,$conn[$i]); } do { $n=curl_multi_exec($mh,$active); } while ($active); foreach ($urls as $i => $url) { $res[$i]=curl_multi_getcontent($conn[$i]); curl_multi_remove_handle($mh,$conn[$i]); curl_close($conn[$i]); } curl_multi_close($mh); print_r($res); ?> I look forward to your ideas. i use file_get_contents() to grab entire web pages to send as html emails. How can i error check that the url i use in file_get_contents() actually exists. I thought i could put it in an if statement like cURL but that doesn't work. Code: [Select] <?php if($email_body = file_get_contents($url)) { $config['mailtype'] = 'html'; $this->email->initialize($config); $this->email->from('support@test.com', 'Testing'); $this->email->to($email); $this->email->subject("Confirm Reply-To Email"); $this->email->message($email_body); $this->email->send(); } I've hit a bit of a roadblock with one of my projects and I cant seem to get past it. I am trying to add a new row to one of my tables, but the foreign key seems to be causing me problems. As you will see from my code below, I am trying to insert a row into my 'job' table. Error: Query failed: Cannot add or update a child row: a foreign key constraint fails (`kanix_support_desk`.`job`, CONSTRAINT `job_ibfk_1` FOREIGN KEY (`agentId`) REFERENCES `agents` (`agentId`)) Tables: Code: [Select] CREATE TABLE IF NOT EXISTS `agents` ( `agentId` int(11) NOT NULL AUTO_INCREMENT, `AgentFirstname` varchar(50) DEFAULT NULL, `AgentSurname` varchar(50) DEFAULT NULL, `username` varchar(25) DEFAULT NULL, `password` varchar(25) DEFAULT NULL, `rank` varchar(12) NOT NULL, PRIMARY KEY (`agentId`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; CREATE TABLE IF NOT EXISTS `job` ( `jobId` int(11) NOT NULL AUTO_INCREMENT, `agentId` int(11) NOT NULL, `date` date NOT NULL, `time` time DEFAULT NULL, `jobName` varchar(100) NOT NULL, `jobDescription` varchar(9999) NOT NULL, `jobstatus` varchar(50) NOT NULL, `customerFirstname` varchar(50) DEFAULT NULL, `customerSurname` varchar(50) DEFAULT NULL, `CustomerTelephoneNo` varchar(50) DEFAULT NULL, PRIMARY KEY (`jobId`), KEY `agentId` (`agentId`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; Php: Code: [Select] session_start(); include("dbConnect.php"); $agent = $_SESSION['agent']; //Set agent name and ID variables $agentid = $_SESSION['identity']; //Check that no section of the form was left blank if($_POST['fname'] != null && $_POST['sname'] != null && $_POST['phone'] != null && $_POST['jtitle'] != null && $_POST['jdesc'] != null){ mysql_query("INSERT INTO job (jobId, agentId, date, time, jobName, jobDescription, jobstatus, customerFirstname, customerSurname, customerTelephoneNo) VALUES (null, '".$agentid."', CURDATE(), NOW(), '".$_POST['jtitle']."', '".$_POST['jdesc']."', 'Live', '".$_POST['fname']."', '".$_POST['sname']."', '".$_POST['phone']."')") or die ("Query failed: " . mysql_error()); header("location:reception.php?content=3"); } else{ //Error message header("location:reception.php?content=4"); } I have installed a new extension on my server. After installation, i see the .so file in the extension directory. I also added the extension to the php.ini file. However, php still fails to load the extension. Any suggestions on how i can fix this?
I am running PHP 5.* with Apache/2.* (CentOS)
Restarted apache server after adding the extension in the php.ini file.
I followed the installation instructions as listed on this website: http://www.mickgenie...-centos-server/ I have release notes on my server, at example.com/release.txt. My software points to this file so people can see the notes: Code: [Select] file_get_contents( http://example.com/release.txt ); Why -- since all sites are on the internet -- can most of my customers see the file but some cannot? Just seems odd to me. Could some servers be turning that off or something? Doesn't seem like a problem on my server. I'm trying to pull the stock quotes Beta from yahoo finance since the yahoo query language doesn't support it. My code returns an empty array. Any ideas why? Code: [Select] <?php $content = file_get_contents('http://finance.yahoo.com/q?s=NFLX'); preg_match('#<tr><th width="48%" scope="row">Beta:</th><td class="yfnc_tabledata1">(.*)</td></tr>#', $content, $match); print_array($match); ?> I am having an issue in which fopen randomly generates either timeout or "failed to open stream" errors when trying to get stock quotes from yahoo finance. Here's an example. <b>Warning</b>: fopen(http://finance.yahoo.com/d/quotes.csv?s=NFLX&f=sl1d1t1c1ohgv&e=.csv) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: HTTP request failed! This issue occurs sporadically; sometimes it's fine, other times it errors out causing the quote to fail. Any ideas on how I can resolve this? Thanks very much. Hey Guys,
I'm doing some coding and I've managed to snip something off....
This is the original code
<form method="post" action="{$systemsslurl}cart.php?a=add&domain=register"> <table class="table table-striped table-framed"> <thead> <tr> <th></th> <th>{$LANG.domainname}</th> <th class="textcenter">{$LANG.domainstatus}</th> <th class="textcenter">{$LANG.domainmoreinfo}</th> </tr> </thead> <tbody> {foreach from=$availabilityresults key=num item=result} <tr> <td class="textcenter">{if $result.status eq "available"}<input type="checkbox" name="domains[]" value="{$result.domain}" {if $num eq "0" && $available}checked {/if}/><input type="hidden" name="domainsregperiod[{$result.domain}]" value="{$result.period}" />{else}X{/if}</td> <td>{$result.domain}</td> <td class="textcenter {if $result.status eq "available"}domcheckersuccess{else}domcheckererror{/if}">{if $result.status eq "available"}{$LANG.domainavailable}{else}{$LANG.domainunavailable}{/if}</td> <td class="textcenter">{if $result.status eq "unavailable"}<a href="http://{$result.domain}" target="_blank">WWW</a> <a href="#" onclick="popupWindow('whois.php?domain={$result.domain}','whois',650,420);return false">WHOIS</a>{else}<select name="domainsregperiod[{$result.domain}]">{foreach key=period item=regoption from=$result.regoptions}<option value="{$period}">{$period} {$LANG.orderyears} @ {$regoption.register}</option>{/foreach}</select>{/if}</td> </tr> {/foreach} </table> <p align="center"><input type="submit" value="{$LANG.ordernowbutton} »" class="btn btn-danger" /></p> </form>and I've changed it to: <form method="post" action="{$systemsslurl}cart.php?a=add&domain=register"> {foreach from=$availabilityresults key=num item=result} {if $result.status eq "available"} <div style="width: 400px; color: #339933; font-size:14px;"><img src="/templates/dj/yes.jpg" style="float:left" />{$tld}<br />Available</div> <div style="width: 100px;" >{$name}<p style="color: #339933;">{$tld}</p></div> <div style="width: 200px;" ><select name="domainsregperiod[{$result.domain}]">{foreach key=period item=regoption from=$result.regoptions}<option value="{$period}">{$period} {$LANG.orderyears} @ {$regoption.register}</option>{/foreach}</select> <input type="submit" value="{$LANG.ordernowbutton} »" class="btn btn-danger" /></div> {/if} {if $result.status eq "unavailable"} <div style="width: 400px; color: #cc0000; font-size:14px;"><img src="/templates/dj/no.jpg" style="float:left" />{$tld}<br />Taken</div> <div style="width: 100px;" >{$domain}<p style="color: #cc0000;">{$tld}</p></div> <div style="width: 200px;" ><a href="http://{$result.domain}" target="_blank">WWW</a> <a href="#" onclick="popupWindow('whois.php?domain={$result.domain}','whois',650,420);return false">WHOIS</a></div> {/if} {/foreach}</form>The original code works fine and add to my cart, the new "updated" version fails... What have I done wrong? Code: [Select] $newid = 9; ?> <html> <head> <title>Used Cars : Add Stock</title> <?php if ($_SERVER['REQUEST_METHOD'] == "POST") { $uploaddir = "../usedcars/images"; $imgfile = ($_FILES['imgfile']['tmp_name']); $imgfile_name = ($_FILES['imgfile']['name']); $imgfile1 = ($_FILES['imgfile1']['tmp_name']); $imgfile_name1 = ($_FILES['imgfile1']['name']); $imgfile2 = ($_FILES['imgfile2']['tmp_name']); $imgfile_name2 = ($_FILES['imgfile2']['name']); $imgfile3 = ($_FILES['imgfile3']['tmp_name']); $imgfile_name3 = ($_FILES['imgfile3']['name']); $imgfile4 = ($_FILES['imgfile4']['tmp_name']); $imgfile_name4 = ($_FILES['imgfile4']['name']); $pext = getFileExtension($imgfile_name); $pext = strtolower($pext); if (($pext != "jpg")) { print "<h1>ERROR</h1>Image Extension Unknown.<br>"; print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>"; print "The file you uploaded had the following extension: $pext</p>\n"; unlink($imgfile); exit(); } $pext1 = getFileExtension($imgfile_name1); $pext1 = strtolower($pext1); if (($pext1 != "jpg")) { print "<h1>ERROR</h1>Image Extension Unknown.<br>"; print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>"; print "The file you uploaded had the following extension: $pext1</p>\n"; unlink($imgfile1); exit(); } $pext2 = getFileExtension($imgfile_name2); $pext2 = strtolower($pext2); if (($pext2 != "jpg")) { print "<h1>ERROR</h1>Image Extension Unknown.<br>"; print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>"; print "The file you uploaded had the following extension: $pext2</p>\n"; unlink($imgfile2); exit(); } $pext3 = getFileExtension($imgfile_name3); $pext3 = strtolower($pext3); if (($pext3 != "jpg")) { print "<h1>ERROR</h1>Image Extension Unknown.<br>"; print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>"; print "The file you uploaded had the following extension: $pext3</p>\n"; unlink($imgfile3); exit(); } $pext4 = getFileExtension($imgfile_name4); $pext4 = strtolower($pext4); if (($pext4 != "jpg")) { print "<h1>ERROR</h1>Image Extension Unknown.<br>"; print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>"; print "The file you uploaded had the following extension: $pext4</p>\n"; unlink($imgfile4); exit(); } $imgsize = GetImageSize($imgfile); $imgsize1 = GetImageSize($imgfile1); $imgsize2 = GetImageSize($imgfile2); $imgsize3 = GetImageSize($imgfile3); $imgsize4 = GetImageSize($imgfile4); /*== check size 0=width, 1=height ==*/ if (($imgsize[0] > 235) || ($imgsize[1] > 176)) if (($imgsize1[0] > 547) || ($imgsize1[1] > 366)) if (($imgsize2[0] > 182) || ($imgsize2[1] > 122)) if (($imgsize3[0] > 182) || ($imgsize3[1] > 122)) if (($imgsize4[0] > 182) || ($imgsize4[1] > 122)) { $tmpimg = tempnam("/tmp", "MKUP"); $tmpimg1 = tempnam("/tmp", "MKUP"); $tmpimg2 = tempnam("/tmp", "MKUP"); $tmpimg3 = tempnam("/tmp", "MKUP"); $tmpimg4 = tempnam("/tmp", "MKUP"); system("djpeg $imgfile >$tmpimg"); system("djpeg $imgfile1 >$tmpimg1"); system("djpeg $imgfile2 >$tmpimg2"); system("djpeg $imgfile3 >$tmpimg3"); system("djpeg $imgfile4 >$tmpimg4"); system("pnmscale -xy 235 176 $tmpimg | cjpeg -smoo 10 -qual 50 >$imgfile"); system("pnmscale -xy 547 366 $tmpimg1 | cjpeg -smoo 10 -qual 50 >$imgfile1"); system("pnmscale -xy 182 122 $tmpimg2 | cjpeg -smoo 10 -qual 50 >$imgfile2"); system("pnmscale -xy 182 122 $tmpimg3 | cjpeg -smoo 10 -qual 50 >$imgfile3"); system("pnmscale -xy 182 122 $tmpimg4 | cjpeg -smoo 10 -qual 50 >$imgfile4"); /*== remove temp image ==*/ unlink($tmpimg); unlink($tmpimg1); unlink($tmpimg2); unlink($tmpimg3); unlink($tmpimg4); } $final_file = str_replace(" ", "_", $imgfile_name); $final_filename = $newid.$final_file; $newfile = $uploaddir . "/$final_filename"; $final_file1 = str_replace(" ", "_", $imgfile_name1); $final_filename1 = $newid.$final_file1; $newfile1 = $uploaddir . "/$final_filename1"; $final_file2 = str_replace(" ", "_", $imgfile_name2); $final_filename2 = $newid.$final_file2; $newfile2 = $uploaddir . "/$final_filename2"; $final_file3 = str_replace(" ", "_", $imgfile_name3); $final_filename3 = $newid.$final_file3; $newfile3 = $uploaddir . "/$final_filename3"; $final_file4 = str_replace(" ", "_", $imgfile_name4); $final_filename4 = $newid.$final_file4; $newfile4 = $uploaddir . "/$final_filename4"; if (is_uploaded_file($imgfile)) { if (!copy($imgfile,"$newfile")) { print "Error Uploading File."; exit(); } } if (is_uploaded_file($imgfile1)) { if (!copy($imgfile1,"$newfile1")) { print "Error Uploading File."; exit(); } } if (is_uploaded_file($imgfile2)) { if (!copy($imgfile2,"$newfile2")) { print "Error Uploading File."; exit(); } } if (is_uploaded_file($imgfile3)) { if (!copy($imgfile3,"$newfile3")) { print "Error Uploading File."; exit(); } } if (is_uploaded_file($imgfile4)) { if (!copy($imgfile4,"$newfile4")) { print "Error Uploading File."; exit(); } } /*== delete the temporary uploaded file ==*/ unlink($imgfile); unlink($imgfile1); unlink($imgfile2); unlink($imgfile3); unlink($imgfile4); print("<img src=../usedcars/images/".$final_filename.">"); /*== DO WHATEVER ELSE YOU WANT SUCH AS INSERT DATA INTO A DATABASE ==*/ } ?> </head> <body bgcolor="#FFFFFF"> <h2>Add Used Car</h2> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="250000"> <p>Title: <input type="text" name="title" size="40" /> <p>Description: <input type="text" name="description" size="40" /> <p>Tags: <input type="text" name="tags" size="40" /> <p>Price: <input type="text" name="price" size="40" /> <p>Full details:<br /> <textarea cols="50" rows="10" name="notes"></textarea> <p>List Image: <input type="file" name="imgfile"> <p>Main Image: <input type="file" name="imgfile1"> <p>Page Image1 : <input type="file" name="imgfile2"> <p>Page Image2: <input type="file" name="imgfile3"> <p>Page Image3: <input type="file" name="imgfile4"> <br> <input type="submit" value="Add Entry"> </form> </body> </html> <?php /*== FUNCTIONS ==*/ function getFileExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } ?> Code: [Select] <?php // plm require_once (dirname(__FILE__) . "/inc/main.php"); $lang = load_language('view_post'); $id = intval($_GET['id']); if ( $id >= 1 ) { dbconn(); // la la la } else { echo "$id\n"; // for debugging die ("no id specified"); } ?>when it's executed of curse i get "0 no id specified" 1. i dont get why i get 0 as a result even if the url is /x.php?id=204 2. in error.log i get Quote PHP Notice: Undefined index: id in x.php i intend to inform that formerly the script was running smoothly on lighttpd webserver, now i use nginx ( so i wont use words ) i know that are people with more complicated things around here ... but still i'm struggling for 1 hour with this xxx thanks in advance btw : php version 5.3.x Good Evening Php Programmers, I am trying to build a pagination script with mysqli using procedural style programming. Am a beginner. Not into oop yet or pdo. Bear that in mind if you show code samples. Else, i won't understand your snippets.
Anyway, here's how my script works ... $query_2 = "SELECT * FROM users WHERE first_name = ? AND marital_status = ? LIMIT $offset,$last_row_on_page";
When you click any page numbers on the pagination section, like page 2, then the fetch_rows() is supposed to fetch the relevant rows again for page 2. Note, rows_count() doesn't play here as I deem not necessary to re-count all matched rows. $query_2 = "SELECT * FROM users WHERE first_name = ? AND marital_status = ? LIMIT $offset,$last_row_on_page"; It displays the matching rows using this WHILE loop: while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC)) BIG ISSUE:
The fetch_rows() or $query_2 fails to fetch any matching rows beyond page 1 no matter what page you click. Be it page 2, 3, 4, etc.
Code is set to display 1 row per page for testing purpose. You can easily see which lines I am having trouble with if you notice the CAPITALISED comments in my code. //Do following if "Search" button clicked. if($_SERVER['REQUEST_METHOD'] === 'POST') {echo __LINE__; echo "<br>";//DELETE //Do following if "Search" button clicked. if(isset($_POST['search'])) {echo __LINE__; echo "<br>";//DELETE rows_count(); //This function will forward script flow to fetch_rows() before halting the script. die(); } } echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS FAILS TO ECHO. IT IS LINE: 24. //Do following if "Search" button not clicked but pagination numbered links are clicked. Eg Page 1, 2, 3, etc.. fetch_rows(); //On PAGINATION PAGE 2, THIS FUNCTION IS NOT GETTING TRIGGERED! WHY ? echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 205.
If you really want to help then best fire-up your Xampp/Wampp and feed my code and test it. DEVMODE CONTEXT: <?php error_reporting(E_ALL); ?> <!DOCTYPE HTML"> <html> <head> <meta name="viewport" content="width-device=width, initial-scale=1"> </head> <body> <?php session_start(); if(!isset($_GET['query_type']) && empty($_GET['query_type'])) { die("Invalid Query!"); } else { $_SESSION['query_type'] = $_GET['query_type']; echo __LINE__; echo "<br>";//DELETE } echo __LINE__; echo "<br>";//DELETE if(!isset($_GET['form_type']) && empty($_GET['form_type'])) { die("Invalid Form!"); } else { $_SESSION['form_type'] = $_GET['form_type']; echo __LINE__; echo "<br>";//DELETE if(!function_exists($_SESSION['form_type'])) { die("Invalid Form!"); } else {echo __LINE__; echo "<br>";//DELETE if(!session_id() || !isset($_SESSION['form_step']) || $_SESSION['form_step'] != 'end') { $_SESSION['form_step'] = 'start'; echo __LINE__; echo "<br>";//DELETE $_SESSION['form_type'](); } } } //FUNCTIONS START FROM HERE function search() {echo __LINE__; echo "<br>";//DELETE function rows_count() { //Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME). $conn = mysqli_connect("localhost","root","","powerpage"); $conn->set_charset('utf8mb4'); //Always set Charset. if($conn === false) { die("ERROR: Connection Error!. " . mysqli_connect_error()); } $query_1 = "SELECT COUNT(id) FROM users WHERE first_name = ? AND marital_status = ?"; $stmt_1 = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt_1,$query_1)) { mysqli_stmt_bind_param($stmt_1,"ss",$_POST["first_name"],$_POST["marital_status"]); mysqli_stmt_execute($stmt_1); $result_1 = mysqli_stmt_bind_result($stmt_1,$row_count); mysqli_stmt_fetch($stmt_1); $_SESSION['row_count'] = $row_count; echo __LINE__; echo "<br>";//DELETE $_SESSION['form_step'] = 'end'; fetch_rows(); } } function fetch_rows() { echo __LINE__; echo "<br>";//DELETE $form_step = $_GET['form_step']; $page_number = $_GET['page']; $result_per_page = $_GET['page_limit']; $offset = (($page_number * $result_per_page) - $result_per_page); //Offset (Row Number that 'Starts' on page). $last_row_on_page = ($page_number * $result_per_page); //Max Result (Row Number that 'Ends' on page). $previous_page = $page_number-1; $next_page = $page_number+1; echo "Row Start: $offset";echo "<br>"; echo "Row End: $last_row_on_page";echo "<br>"; //Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME). $conn = mysqli_connect("localhost","root","","powerpage"); $conn->set_charset('utf8mb4'); //Always set Charset. if($conn === false) { die("ERROR: Connection Error!. " . mysqli_connect_error()); } $query_2 = "SELECT * FROM users WHERE first_name = ? AND marital_status = ? LIMIT $offset,$last_row_on_page"; $stmt_2 = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt_2,$query_2)) {echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 103. mysqli_stmt_bind_param($stmt_2,"ss",$_POST["first_name"],$_POST["marital_status"]); mysqli_stmt_execute($stmt_2); $result_2 = mysqli_stmt_get_result($stmt_2); if(!$result_2) { //Close Connection. mysqli_close($conn); die("<pre>2c. Statement Fetching failed!</pre>"); } else {echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 114. //Grab total number of pages to paginate. $row_count = $_SESSION['row_count']; //$total_pages = ceil($result_1/$result_per_page); $total_pages = ceil($row_count/$result_per_page); echo "TOTAL PAGES: $total_pages<br><br>"; while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC))//On PAGE 2, PHP IGNORING THIS AND BYPASSING THIS WHOLE WHILE LOOP ON PAGE 2. IT IS LINE: 122. {echo __LINE__; echo "<br>";//On PAGE 2, THIS FAILS TO ECHO. IT IS LINE: 123. PHP IGNORING IT BYPASSING IT ON PAGE 2. //Retrieve Values. $id = $row["id"]; $first_name = $row["first_name"]; $middle_name = $row["middle_name"]; $surname = $row["surname"]; $gender = $row["gender"]; $marital_status = $row["marital_status"]; $working_status = $row["working_status"]; echo "Id: $id<br>"; echo "First Name: $first_name<br>"; echo "Middle Name: $middle_name<br>"; echo "Surname: $surname<br>"; echo "Gender: $gender<br>"; echo "Marital Status: $marital_status<br>"; echo "Working Status: $working_status<br>"; echo "<br>"; echo "<br>"; $i = 1; while($i<=$total_pages) { if($i<$total_pages) { echo "<a href='http://localhost/power.page/pagination_test_simple_WORKING_ON_NOW.php?form_type=";?><?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&page_limit=1&page=<?php echo $i;?>'><?php echo " $i ";?></a><?php } elseif($i==$page_number) { echo "<a href='http://localhost/power.page/pagination_test_simple_WORKING_ON_NOW.php?form_type=";?><?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&page_limit=1&page=<?php echo $i;?>'><?php echo "<b> $i </b>";?></a><?php } $i++; } if($page_number>$total_pages) { echo "<a href='http://localhost/power.page/pagination_test_simple_WORKING_ON_NOW.php?form_type=";?><?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&page_limit=1&page=<?php echo $previous_page;?>'><?php echo "<b> Previous </b>";?></a><?php } } } } $_SESSION['form_step'] = 'end'; } ?> <form action="<?php echo $_SERVER['PHP_SELF'];?>?form_type=<?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&page_limit=1&page=1" method='post' enctype='plain/text'> <?php //Added '*' (asterisk) to indicate the 'Text Field' is a 'required' one. echo "<label for=\"first_name\">First Name *:</label> <input type=\"text\" name=\"first_name\" placeholder=\"First Name\" value = \"\">";?> <br> <?php echo "<label for=\"marital_status\">Marital Status *:</label>"; echo "<select name=\"marital_status\">"; echo "<option value=\"single\">Single</option>"; echo "<option value=\"married\">Married</option>"; echo "</select>"; echo "<br>"; ?> <input type="submit" name="search" value="Search"> <?php //$current_function = __FUNCTION__; //echo $current_function; //Do following if "Search" button clicked. if($_SERVER['REQUEST_METHOD'] === 'POST') {echo __LINE__; echo "<br>";//DELETE //Do following if "Search" button clicked. if(isset($_POST['search'])) {echo __LINE__; echo "<br>";//DELETE rows_count(); //This function will forward script flow to fetch_rows() before halting the script. die(); } } echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS FAILS TO ECHO. IT IS LINE: 24. //Do following if "Search" button not clicked but pagination numbered links are clicked. Eg Page 1, 2, 3, etc.. fetch_rows(); //On PAGINATION PAGE 2, THIS FUNCTION IS NOT GETTING TRIGGERED! WHY ? echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 205. } ?> What is wrong ? Why is fetch_rows() or $query_2 failing to fetch the matching rows for pages beyond page 1 ?
ECHOES 22 24 32 39 42 50 After clicking the SUBMIT button I get these echoed as expected: 193 71 78 Row Start: 0 Row End: 1 103 114 TOTAL PAGES: 5 123 After clicking the link for 'page 2' on pagination section, I get echoed the same line numbers I get echoed before clicking the SUBMIT button as if everything is starting all over with a new query (when not). That is not supposed to happen. I reckon line 200 is not taking action: fetch_rows(); //On PAGINATION PAGE 2, THIS FUNCTION IS NOT GETTING TRIGGERED! WHY ? IT IS LINE: 200. MAIN ISSUE HERE, I SUSPECT.
I need to check post values with existing database values and my check isn't working for the values below. Code: [Select] //This one works if ((isset($_POST['companystageas'])) && ($_POST['companystageas'] != $info['stage'])) { $details = ''; update_company_actions($info['companyid'], 10, $details); } //These all fail if ((!isset($_POST['companystateas'])) && (($_POST['companycountryas'] != $info['country']) || ($_POST['city'] != $info['city']))) { $details = $_POST['companycityas'].', '.$_POST['companycountryas']; update_company_actions($info['companyid'], 11, $details); } else if ((isset($_POST['companystateas'], $_POST['companycityas'])) && (($_POST['companystateas'] != $info['state']) || ($_POST['companycityas'] != $info['city']))) { $details = $_POST['companycityas'].', '.$_POST['companystateas']; update_company_actions($info['companyid'], 11, $details); } if ((isset($_POST['capitalrequestedas'])) && ($_POST['capitalrequestedas'] != $info['capitalrequested'])) { $details = ''; update_company_actions($info['companyid'], 12, $details); } hello dear experts
good day dear friend - i need your help. import urllib import urlparse import re # import peewee import json from peewee import * #from peewee import MySQLDatabase ('cpan', user='root',passwd='rimbaud') db = MySQLDatabase('cpan', user='root',passwd='rimbaud') class User(Model): name = TextField() cname = TextField() email = TextField() url = TextField() class Meta: database = db # this model uses the cpan database User.create_table() #ensure table is created url = "http://search.cpan.org/author/?W" html = urllib.urlopen(url).read() for lk, capname, name in re.findall('<a href="(/~.*?/)"><b>(.*?)</b></a><br/><small>(.*?)</small>', html): alk = urlparse.urljoin(url, lk) data = { 'url':alk, 'name':name, 'cname':capname } phtml = urllib.urlopen(alk).read() memail = re.search('<a href="mailto:(.*?)">', phtml) if memail: data['email'] = memail.group(1) data = json.load('email') #your json data file here for entry in data: #assuming your data is an array of JSON objects user = User.create(name=entry["name"], cname=entry["cname"], email=entry["email"], url=entry["url"]) user.save() guess that there a data-file must exist: one that have been created by the script during the parsing... is this right? ) martin@linux-70ce:~/perl> python cpan_100.py Traceback (most recent call last): File "cpan_100.py", line 47, in <module> data = json.load('email') #your json data file here File "/usr/lib/python2.7/json/__init__.py", line 286, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read' martin@linux-70ce:~/perl> this script does not work ) martin@linux-70ce:~/perl> python cpan_100.py Traceback (most recent call last): File "cpan_100.py", line 47, in <module> data = json.load('email') #your json data file here File "/usr/lib/python2.7/json/__init__.py", line 286, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read' martin@linux-70ce:~/perl>well i suppose that in the first part of the script - the parser - part we parse data and - therefore we should create a file. I guess that this file is taken up within the second part of the script... load data . well why the script does not work!? Hello All, I have been wrestling with a regex for a couple of hours now and I finally had to give in and ask for help. The weird thing is that it works if there are no new lines in the text, it fails if there is a new line(s) present. The code: $matches = array(); $pattern = '~\[CUSTOM_TAG(.*?)\](.*?)\[/CUSTOM_TAG\]~'; preg_match_all($pattern, $html, $matches); if (!empty($matches[0])){ foreach($matches[0] as $code){ $parameter = preg_replace($pattern, '$1', $code); $content = preg_replace($pattern, '$2', $code);//get the content between the pattern }//foreach($matches[0] as $code){ }else{ echo 'Match failed'; }//if (!empty($matches[0])){ So with that code in mind, if the $html variable (the text to be processed) is: $html = '<h1>Hello, world!</h1><p style="color:#ff0000;">Some red text</p>';A match is found. If the $html variable is: $html = '<h1>Hello, world!</h1> <p style="color:#ff0000;">Some red text</p>';Match not found Hopefully I'm just missing something simple in my regex. Thanks in advance! Twitch Folks, Tell me, do you see anything wrong in my INSERT ? If not, then why is it not INSERTING ? I get no php error, nor mysql error. Button I click. Then form data vanishes as if submitted. I check db and no submission came through! <?php //include('error_reporting.php'); ini_set('error_reporting','E_ALL');//Same as: error_reporting(E_ALL); ini_set('display_errors','1'); ini_set('display_startup_errors','1'); ?> <form name = "submit_link" method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="domain">Domain:</label> <input type="text" name="domain" id="domain" placeholder="Input Domain"> <br> <label for="domain_email">Domain Email:</label> <input type="email" name="domain_email" id="domain_email" placeholder="Input Domain Email"> <br> <label for="url">Url:</label> <input type="url" name="url" id="url" placeholder="Input Url"> <br> <label for="link_anchor_text">Link Anchor Text:</label> <input type="text" name="link_anchor_text" id="link_anchor_text" placeholder="Input Link Anchor Text"> <br> <textarea rows="10" cols="20">Page Description</textarea> <br> <label for="keywords">Keywords:</label> <input type="text" name="keywords" id="keywords" placeholder="Input Keywords related to Page"> <br> <button type="submit">Click me</button> <br> <input type="reset"> <br> </form> <?php if($_SERVER['REQUEST_METHOD'] === 'POST') { /* if(ISSET($_POST['submit_link'])) {*/ mysqli_report(MYSQLI_REPORT_ALL|MYSQLI_REPORT_STRICT); mysqli_connect("localhost","root","","test"); $conn->set_charset("utf8mb4"); if(mysqli_connect_error()) { echo "Could not connect!" . mysqli_connect_error(); } $query = "INSERT into links (domain,domain_email,url,link_anchor_text,page_description,keywords) VALUES (?,?,?,?,?,?)"; $stmt = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'ssssss',$_POST['domain'],$_POST['domain_email'],$_POST['url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keywords']); mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); mysqli_close($conn); } else { die("INSERT failed!"); } //} } ?>
@MacGuyver,
I will do the VALIDATIONS later. Remember, I was testing myself how much I can code without notes. What you see above was from my memory. Am still a beginner php student for 3yrs now, however! As for validation stuff will have to check notes and learn or relearn. Meaning, have to memorise the code before I add it here on current project. And so for now, ignore VALIDATIONS and let me know why it's not submitting data into db.
Php programmers, I am getting this error: Fatal error: Uncaught mysqli_sql_exception: No index used in query/prepared statement (null) in C:\xampp\htdocs\test\select_adv.php:70 Stack trace: #0 C:\xampp\htdocs\test\select_adv.php(70): mysqli_stmt_execute(Object(mysqli_stmt)) #1 {main} thrown in C:\xampp\htdocs\test\select_adv.php on line 70
Line 70 is:
if(mysqli_stmt_execute($stmt) === FALSE)
Context:
if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'s',$_SESSION['search_column']); if(mysqli_stmt_execute($stmt) === FALSE) { printf("Error: %s.\n", mysqli_stmt_error($stmt)); printf("Error: %d.\n", mysqli_stmt_errno($stmt)); }
This removes the error:
if($stmt) === FALSE) { printf("Error: %s.\n", mysqli_stmt_error($stmt)); printf("Error: %d.\n", mysqli_stmt_errno($stmt)); }
I still want to know why this works:
if($stmt) === FALSE) {
but this doesn't work:
if(mysqli_stmt_execute($stmt) === FALSE) {
Let me know.
Full Code in case you're wondering just what on earth is going on ....
<?php //include('error_reporting.php'); error_reporting(E_ALL); ini_set('error_reporting',E_ALL);//Same as: error_reporting(E_ALL); ini_set('display_errors','1'); ini_set('display_startup_errors','1'); require('conn.php'); echo __LINE__; ?> <form name = "search" method = "POST" action=""> <label for="keywords">Keywords:*</label> <input type="text" name="keywords" id="keywords" placeholder="Input Keywords" required> <br> <label for="search_column">Search in ... ?</label> <select name="search_column" id="search_column"> <option value="page_url">Page Url</option> <option value="link_anchor_text">Link Anchor Text</option> <option value="page_description">Page Description</option> <option value="keyphrases">Keyphrase</option> <option value="keywords">Keywords</option> </select> <br> <label for="tos_agreement">Agree to TOS or not ? *</label> <select name="tos_agreement" id="tos_agreement" required> <option value="Yes">Yes</option> <option value="No">No</option> </select> <br> <button type="submit">Submit</button><br> <button type="submit" value="submit">Submit</button><br> <input type="submit" value="submit"><br> <button name=submit value=" ">Submit</button><br> <br> <input type="reset"> <br> </form> <?php session_start(); echo __LINE__; if($_SERVER['REQUEST_METHOD'] === 'POST') { echo __LINE__; if(ISSET($_POST['submit'])) { echo __LINE__; if(ISSET($_POST['search_column'])) { $_SESSION['search_column'] = $_POST['search_column']; echo $_SESSION['search_column']; echo __LINE__; } //Re-write the following 4 lines ... mysqli_report(MYSQLI_REPORT_ALL|MYSQLI_REPORT_STRICT); $conn = mysqli_connect("localhost","root","","test"); $conn->set_charset("utf8mb4"); //$query = "SELECT page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE $_SESSION['search_column'] = ?"; $query = "SELECT page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE {$_SESSION['search_column']} = ?"; //$query = "SELECT page_url,link_anchor_text,page_description,keyphrases,keywords FROM links WHERE " . $_SESSION['search_column'] . " = ?"; $stmt = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'s',$_SESSION['search_column']); if(mysqli_stmt_execute($stmt) === FALSE) { printf("Error: %s.\n", mysqli_stmt_error($stmt)); printf("Error: %d.\n", mysqli_stmt_errno($stmt)); } $result = mysqli_stmt_bind_result($stmt,$page_url,$link_anchor_text,$page_description,$keyphrase,$keywords); mysqli_stmt_fetch($stmt); while(mysqli_stmt_fetch($stmt)) { echo "url"; echo "<br>"; echo "anchor_text"; echo "<br>"; echo "description"; echo "<br>"; echo "keyphrases"; echo "<br>"; echo "keywords"; echo "<br>"; echo "|"; echo "<br>"; } mysqli_stmt_close($stmt); mysqli_close($conn); } else { echo "1. QUERY failed!"; } if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'sssss',$_POST['page_url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keyphrases'],$_POST['keywords']); if(mysqli_stmt_execute($stmt) === FALSE) { printf("Error: %s.\n", mysqli_stmt_error($stmt)); printf("Error: %d.\n", mysqli_stmt_errno($stmt)); } $result = mysqli_stmt_get_result($stmt); while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) { $page_url = $row['page_url']; echo $page_url; echo "<br>"; $link_anchor_text = $row['link_anchor_text']; echo $link_anchor_text; echo "<br>"; $page_description = $row['page_description']; echo $page_description; echo "<br>"; $keyphrases = $row['keyphrases']; echo $keyphrases; echo "<br>"; $keywords = $row['keywords']; echo $keywords; echo "<br>"; echo "|"; echo "<br>"; } mysqli_stmt_close($stmt); mysqli_close($conn); } else { die("2. QUERY failed!"); } echo '<pre>' . print_r($_POST, 1) . '</pre>'; echo $_SESSION['search_column']; } } echo __LINE__; ?>
Hi All, I'm trying to incorporate a BBC Sport RSS Feed into my website. The following code will show me the news feeds as text and I can include the url's as text also but want to turn this into a clickable url. How do I do this, I cant work it? please help. $feed_url = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/s/shrewsbury/rss.xml"; // Get data from feed file $response = file_get_contents($feed_url); // Insert XML into structure $xml = simplexml_load_string($response); // Browse structure foreach($xml->channel->item as $one_item) echo $one_item->title."<BR>"; |