PHP - Problem Parsing Valid Json In Php
Hey there,
I am using prototype to send JSON information to a PHP file which will then use the data to update a database, the AJAX presently looks as follows: Code: [Select] function saveprofile() { var email = document.getElementById("email").value; var profileDetails = { "email":email, "titleitalic":titleitalic, "profileDetails":titlefontcolor, "titlefontcolor":titleunderline, "titleoffsettop":titleoffsettop, "titleoffsetleft":titleoffsetleft, "aboutbackgroundcolour":aboutbackgroundcolour, "aboutunderline":aboutunderline, "aboutfontfamily":aboutfontfamily, "aboutbold":aboutbold, "aboutitalic":aboutitalic, "aboutfontcolor":aboutfontcolor, "aboutoffsettop":aboutoffsettop, "aboutoffsetleft":aboutoffsetleft, "statusoffsetleft":statusoffsetleft, "statusinfooffsetright":statusinfooffsetright, "pictureoffsetleft":pictureoffsetleft, "profilebold":profilebold, "profileunderline":profileunderline, "profileitalic":profileitalic, "profilefontcolor":profilefontcolor, "profilefontfamily":profilefontfamily, "profilebackgroundcolour":profilebackgroundcolour } var jsonstring = JSON.stringify(profileDetails); alert(jsonstring); var request = new Ajax.Request ('scripts/updateprofile.php', { method: 'POST', parameters: jsonstring, onComplete: responseReturned } ); } Which outputs the following JSON which has been tested on http://www.jsonlint.com/ as valid: Code: [Select] { "email": "l-wilson-1986@hotmail.co.uk", "titleitalic": "normal", "profileDetails": "#d0deea", "titlefontcolor": "none", "titleoffsettop": 100, "titleoffsetleft": 100, "aboutbackgroundcolour": "transparent", "aboutunderline": "none", "aboutfontfamily": "Arial", "aboutbold": "normal", "aboutitalic": "normal", "aboutfontcolor": "#d0deea", "aboutoffsettop": 325, "aboutoffsetleft": 100, "statusoffsetleft": 450, "statusinfooffsetright": 250, "pictureoffsetleft": 100, "profilebold": "normal", "profileunderline": "none", "profileitalic": "normal", "profilefontcolor": "#fff", "profilefontfamily": "Arial", "profilebackgroundcolour": "#2c3c49" } The PHP file which receives the JSON looks as follows: Code: [Select] <?php $myjson = $_POST['jsonstring']; $jsonchars = json_decode(($myjson), true); $json_errors = array( JSON_ERROR_NONE => 'No error has occurred', JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded', JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded', JSON_ERROR_SYNTAX => 'Syntax error', ); echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL; // do something with the data ?> The problem is the PHP constantly returns the following error: Last error : Syntax error and any attempts to access the JSON data returns NULL values. I have looked at several online examples and cannot see where I might be going wrong, and although users have had problems with syntax errors it normally relates to incorrect JSON. Any advice on this topic would be greatly appeciated Leanne Similar TutorialsHi, As I am new to PHP and JSON my Interest in the field pushes me to know further. I have successfully parsed a JSON file: { "birthdays": [ "319507200" :"Kyle", "1390435200" :"Noah", "307843200" :"Carla" ] } Using this PHP file: <?php $jsondata = file_get_contents("birthdays.json"); $json = json_decode($jsondata,true); echo $json["birthdays"][0]['1390435200']; ?> Now I would like to know how to display when Noah’s birthday is, in the form yyyy/MM/dd. Can an expert tell me how this would be done? Thank you :-) i am trying to get values from the json array that get direct messages from twitter but i am getting the message error "Parse error: syntax error, unexpected T_AS, expecting '(' " in relation to the line "foreach (array as $direct_message) {" Also should i convert the array into a linear php array? Code: [Select] // create new instance $OAuth = new TwitterOAuth($consumer_key,$consumer_secret, $oAuthToken, $oAuthSecret); $direct_message = $OAuth->get('https://api.twitter.com/1/direct_messages.json?count=1&page='); function write_into_database ($direct_message) { $conn = mysql_connect("127.0.0.1", "Diego", "frafra") or die(mysql_error()); mysql_select_db('bot', $conn) or die(mysql_error()); foreach(array as $direct_message) { mysql_query("INSERT INTO 'followers' ('user_id', 'user_alias'), VALUES ('{$direct_message->sender_id}', '{$direct_message->sender_screen_name}, INSERT INTO 'd_messages'('message_id', 'message'), VALUES ('{$direct_message->id}' ,'{$direct_message->text})"); } write_into_database($direct_message); I am having a nightmare sending / recieving some JSON..... I have a test page which creates a JSON packet and posts it to another page. This page then processes it and returns a response... the data is in the post, but after decoding it the data seems to be lost.... Here is the code for the sending page: Code: [Select] <!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>Untitled Document</title> </head> <?php require_once ("inc/jsonwrapper/JSON/JSON.php"); $RequestID ='121'; // :ID to which this request relates to allow site to keep track of things $Method = 'login'; //:Which method the call is directed at $referer = 'abc'; // :Name of referring network $affiliateid =2468; // :ID of referring site in affiliate network if any $user_Country ='gb'; // :Users two letter country code $UserID = '12345'; // :Numeric ID to identify players in game database belonging to network or portal $GameuserID = '1' ; // UserID in game database $params = array ( 'referer' => $referer , 'affiliateid' => $affiliateid , 'userCountry' => $user_Country , 'UserID' => $UserID , 'GameuserID' => $GameuserID); $response = array ( 'jsonrpc'=>'2.0', 'id'=> $RequestID , 'Method' => $Method , 'params' => $params) ; $data = json_encode($response); // URL of web api page $url = 'http://xxx.com/webapi.php'; $reply = do_post_request($url, $data); // setup new JSON service $json = new Services_JSON(); $jsonPacket = $json->decode($reply,true); //THIS IS WHERE I PRINT THE RESPONSE echo print_r ($jsonPacket,1); function do_post_request($url, $data, $optional_headers = null) { $params = array('http' => array( 'method' => 'POST', 'header'=>"Content-Type: text/xml; charset=utf-8", 'content' => $data )); if ($optional_headers !== null) { $params['http']['header'] = $optional_headers; } $ctx = stream_context_create($params); $fp = @fopen($url, 'rb', false, $ctx); if (!$fp) { throw new Exception("Problem with $url, $php_errormsg"); } $response = @stream_get_contents($fp); if ($response === false) { throw new Exception("Problem reading data from $url, $php_errormsg"); } return $response; } ?> And the replying page Code: [Select] <!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>Untitled Document</title> </head> <? //setup database connection require_once('globals.php'); //setup JSON require_once ("inc/jsonwrapper/JSON/JSON.php"); $secret_Key = '12345';//SECRET KEY $app_Id = '6789';//APP ID $token = ''; // setup new JSON service $json = new Services_JSON(); // accept incoming POST data $input = $GLOBALS['HTTP_RAW_POST_DATA']; //hashes $hash = $_GET['authHash']; $sHash = strtolower(md5($input . $secret_Key)); $hash = 0; $sHash = 0; if (strcmp($sHash, $hash) == 0) { //check if incoming is JSON as we MIGHT use XML later too $isJSON= substr_count($input,"json"); if ($isJSON > 0){ processJSON ($input); } global $hash, $sHash; } //JSON FUNCTION TO PARSE JSON function processJSON($input){ global $json; $jsonPacket = $json->decode($input,true); $json_RequestId = $jsonPacket->id; //check method and go to correct function switch ($jsonPacket->Method){ case 'Game.login': game_login ($jsonPacket, $json_RequestId) ; break; } } //JSON FUNCTIONS function game_login($jsonPacket, $json_RequestId){ $aid = ($jsonPacket->params->affiliateid); $country_code = ($jsonPacket->params->userCountry); $GameuserID = ($jsonPacket->params->GameuserID); $UserID = ($jsonPacket->params->UserID); //mail ("martyn@staggan.com" , "SNSUserID" , $UserID ); $result_userIDcheck = mysql_query("SELECT snsUserid FROM player where player_id = $GameuserID;"); $result_UserID = mysql_result ($result_userIDcheck, 0); if ($UserID == $result_UserID){ $result = 'OK'; $id = $json_RequestId; //create token global $secret_Key ; $token = hash ('md5', $secret_Key.$aid.$GameuserID); $logindetails = array ( 'token=' => $token , 'UID'=> $GameuserID , 'snsUID' => $UserID , 'aid' => $aid , 'name' => $name); $params= array ('result'=>$result, 'logindetails'=> $logindetails, 'GameuserID'=>$GameuserID); $response = array ( 'jsonrpc'=>'2.0', 'id'=> $id , 'result' => $params) ; echo json_encode($response); } else mail ("test@test.com", "login", 'false'); } ?> If I print the $reply var I see this: {"jsonrpc":"2.0","id":"121","result":{"result":"OK","logindetails":{"token=":"68c49918c353a3e5d86d165da1cb2f72","UID":"1","snsUID":"12345","aid":"6789","name":null},"GameuserID":"1"}} But trying to decode to an array leaves me with nothing.... Any help would be greatly appreciated Folks, I want to parse a particular element from an array and nothing else. Here is the Class (RecursiveTwitterSearch.php): <? /** * Wrapper class around the Twitter Search API for PHP * Based on the class originally developed by David Billingham * and accessible at http://twitter.slawcup.com/twitter.class.phps * @author Ryan Faerman <ryan.faerman@gmail.com> * @version 0.2 * @package PHPTwitterSearch */ class TwitterSearch { /** * Can be set to JSON (requires PHP 5.2 or the json pecl module) or XML - json|xml * @var string */ var $type = 'json'; /** * It is unclear if Twitter header preferences are standardized, but I would suggest using them. * More discussion at http://tinyurl.com/3xtx66 * @var array */ var $headers=array('X-Twitter-Client: PHPTwitterSearch','X-Twitter-Client-Version: 0.1','X-Twitter-Client-URL: http://ryanfaerman.com/twittersearch'); /** * Recommend setting a user-agent so Twitter knows how to contact you inc case of abuse. Include your email * @var string */ var $user_agent=''; /** * @var string */ var $query=''; /** * @var array */ var $responseInfo=array(); /** * Use an ISO language code. en, de... * @var string */ var $lang; /** * The number of tweets to return per page, max 100 * @var int */ var $rpp; /** * The page number to return, up to a max of roughly 1500 results * @var int */ var $page; /** * Return tweets with a status id greater than the since value * @var int */ var $since; /** * Returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile. The parameter value is specified by "latitide,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers) * @var string */ var $geocode; /** * When "true", adds "<user>:" to the beginning of the tweet. This is useful for readers that do not display Atom's author field. The default is "false" * @var boolean */ var $show_user = false; /** * @param string $query optional */ function TwitterSearch($query=false) { $this->query = $query; } /** * Find tweets from a user * @param string $user required * @return object */ function from($user) { $this->query .= ' from:'.str_replace('@', '', $user); return $this; } /** * Find tweets to a user * @param string $user required * @return object */ function to($user) { $this->query .= ' to:'.str_replace('@', '', $user); return $this; } /** * Find tweets referencing a user * @param string $user required * @return object */ function about($user) { $this->query .= ' @'.str_replace('@', '', $user); return $this; } /** * Find tweets containing a hashtag * @param string $user required * @return object */ function with($hashtag) { $this->query .= ' #'.str_replace('#', '', $hashtag); return $this; } /** * Find tweets containing a word * @param string $user required * @return object */ function contains($word) { $this->query .= ' '.$word; return $this; } /** * Set show_user to true * @return object */ function show_user() { $this->show_user = true; return $this; } /** * @param int $since_id required * @return object */ function since($since_id) { $this->since = $since_id; return $this; } /** * @param int $language required * @return object */ function lang($language) { $this->lang = $language; return $this; } /** * @param int $n required * @return object */ function rpp($n) { $this->rpp = $n; return $this; } /** * @param int $n required * @return object */ function page($n) { $this->page = $n; return $this; } /** * @param float $lat required. lattitude * @param float $long required. longitude * @param int $radius required. * @param string optional. mi|km * @return object */ function geocode($lat, $long, $radius, $units='mi') { $this->geocode = $lat.','.$long.','.$radius.$units; return $this; } /** * Build and perform the query, return the results. * @param $reset_query boolean optional. * @return object */ function results($reset_query=true) { $request = 'http://search.twitter.com/search.'.$this->type; $request .= '?q='.urlencode($this->query); if(isset($this->rpp)) { $request .= '&rpp='.$this->rpp; } if(isset($this->page)) { $request .= '&page='.$this->page; } if(isset($this->lang)) { $request .= '&lang='.$this->lang; } if(isset($this->since)) { $request .= '&since_id='.$this->since; } if($this->show_user) { $request .= '&show_user=true'; } if(isset($this->geocode)) { $request .= '&geocode='.$this->geocode; } if($reset_query) { $this->query = ''; } return $this->objectify($this->process($request))->results; } /** * Returns the top ten queries that are currently trending on Twitter. * @return object */ function trends() { $request = 'http://search.twitter.com/trends.json'; return $this->objectify($this->process($request)); } /** * Internal function where all the juicy curl fun takes place * this should not be called by anything external unless you are * doing something else completely then knock youself out. * @access private * @param string $url Required. API URL to request * @param string $postargs Optional. Urlencoded query string to append to the $url */ function process($url, $postargs=false) { $ch = curl_init($url); if($postargs !== false) { curl_setopt ($ch, CURLOPT_POST, true); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs); } curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_NOBODY, 0); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); $response = curl_exec($ch); $this->responseInfo=curl_getinfo($ch); curl_close($ch); if( intval( $this->responseInfo['http_code'] ) == 200 ) return $response; else return false; } /** * Function to prepare data for return to client * @access private * @param string $data */ function objectify($data) { if( $this->type == 'json' ) return (object) json_decode($data); else if( $this->type == 'xml' ) { if( function_exists('simplexml_load_string') ) { $obj = simplexml_load_string( $data ); $statuses = array(); foreach( $obj->status as $status ) { $statuses[] = $status; } return (object) $statuses; } else { return $out; } } else return false; } } class RecursiveTwitterSearch extends TwitterSearch { var $request_count = 0; var $max_request_count = 5; var $max_id; function recursive_results() { $request = 'http://search.twitter.com/search.'.$this->type; $request .= '?q='.urlencode($this->query); if(isset($this->rpp)) { $request .= '&rpp='.$this->rpp; } if(isset($this->page)) { $request .= '&page='.$this->page; } if(isset($this->lang)) { $request .= '?='.$this->lang; } if(isset($this->since)) { $request .= '&since_id='.$this->since; } if($this->show_user) { $request .= '&show_user=true'; } if(isset($this->geocode)) { $request .= '&geocode='.$this->geocode; } if(isset($this->max_id)) { $request .= '&max_id='.$this->max_id; } $response = $this->objectify($this->process($request)); $this->request_count++; if ($response) { $results = $response->results; if(!empty($response->next_page)) { preg_match('|\?page=([0-9]*)&max_id=([0-9]*)&|', $response->next_page, $matches); $this->page = $matches[1]; $this->max_id = $matches[2]; if ($this->request_count < $this->max_request_count) { $results = array_merge($results, $this->recursive_results()); } } return $results; } else return false; } function max_request_count($n) { $this->max_request_count = $n; return $this; } } ?> Here is how i am calling it: <?php require ("RecursiveTwitterSearch.php"); $rts = new RecursiveTwitterSearch('paintball mask'); echo '<pre>'; print_r($rts->recursive_results()); echo '</pre>'; echo 'It took ' . $rts->request_count . ' request(s) to get this result.'; ?> If you observer the Output, u will see lot of array, i want to extract only "[text]" portion. So the desired output should be like: Quote vPaintball Mask http://bit.ly/czBA6S The Paintball Republic does a short video about mask safety. LEARN. http://fb.me/KkMvjDWF airsoft vs paintball mask http://goo.gl/fb/tyoxk @mmorgansmithh like wearing a paintball mask on your head to starbucks Tippmann US Army Ranger Paintball Goggle Mask - Camo: Tippmann US Army Ranger Paintball Goggle Mask - Camo ... http://bit.ly/9hFi3p and so on......... Infact, i prfer to use "foreach" to each each element so i can do further operation on it. Can anyone help to achieve this? Natty I have a situation were I need to just get a simple location. I don't want any while loops or any of that jazz. I just want 1 string location every time. <?php $ider = $_GET['id']; $conn = mysqli_connect("localhost", "Me", "pass", "MyDB"); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT Location FROM LifeSaver1 WHERE id =$ider"; $result = $conn->query($sql); $obj = mysqli_fetch_object($result); $obj2 = $obj->Location; var_dump($obj); ?> This is what it outputs Quotestring(11) "Boston" I just need Boston. Can anyone give me a hint? I'm practicing some code here Code: [Select] reset($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "";) $val = "NULL"; $arVals[$key] = (get_magic_qqotes_gpc()) ? $val : addslashes($val); if($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($key != "access_period" && $key != "passwd") $arVals[$key] = "'".$arVals[$key]."'"; } And it's giving me error Quote Parse error: parse error in C:\wamp\www\php\user_registration\registered.php on line 26 line 26 is the Code: [Select] if ($val == "";) $val = "NULL"; I wonder what the problem is... So when I load my paginator it returns No Results Found. 1) My query is only returning 1 array entry, should be hundreds, maybe I'm not builing it correctly, 2) There is at least 1 array set but its still saying data not found. Heres the template array: Code: [Select] array('id'=>'0', 'name'=>'xmlqoyzgmykrphvyiz', 'date'=>'13-Sep-2002', 'price'=>'8370', 'number'=>'8056', 'address'=>'qdfbc', 'company'=>'taufrid', 'desc'=>'pppzhfhcdqcvbirw', 'age'=>'5512', 'title'=>'zticbcd', 'phone'=>'hvdkltabshgakjqmfrvxo', 'email'=>'eodnqepua', 'zip'=>'eodnqepua', 'country'=>'pdibxicpqipbsgnxyjumsza'), array('id'=>'1', 'name'=>'rbdmbabficcre', 'date'=>'10-Sep-2004', 'price'=>'3075', 'number'=>'3627', 'address'=>'oxcm', 'company'=>'xyzwzv', 'desc'=>'rwndyoedxh', 'age'=>'2134', 'title'=>'lxxyfgdtdffjce', 'phone'=>'zeejvbwy', 'email'=>'ldcikhxwfuulaxeedkogpxftb', 'zip'=>'ldcikhxwfuulaxeedkogpxftb', 'country'=>'pcmobxrdfclcyrx'), array('id'=>'2', 'name'=>'yr', 'date'=>'04-Mar-2007', 'price'=>'7129', 'number'=>'6614', 'address'=>'i', 'company'=>'gcpvrshftfxxlz', 'desc'=>'nyalrdjjl', 'age'=>'4728', 'title'=>'ddfl', 'phone'=>'mnhifzqltvirgiaug', 'email'=>'f', 'zip'=>'f', 'country'=>'epipbmtfsfxetenyedjxzsog'), etc Here is my arry: Code: [Select] $echoarray = array(); $resultsql = mysql_query("SELECT * FROM clients")or die(mysql_error()); while($row = mysql_fetch_array($resultsql)){ $echoarray['id'] = $row['ID']; $echoarray['name'] = $row['First_Name'] . " " . $row['Last_Name']; $echoarray['price'] = $row['Status']; $echoarray['number'] = $row['Sex']; $echoarray['address'] = $row['Phys_Street']; $echoarray['company'] = $row['Agency']; $echoarray['desc'] = $row['Notes']; $echoarray['age'] = $row['Date_Birth']; $echoarray['title'] = $row['Occupation']; $echoarray['phone'] = $row['Phone']; $echoarray['email'] = $row['Email']; $echoarray['zip'] = $row['Phys_Zip']; $echoarray['country'] = $row['Phys_City']; } Here is the template return: Code: [Select] function initArray() { return array( array('id'=>'0', 'name'=>'xmlqoyzgmykrphvyiz', 'date'=>'13-Sep-2002', 'price'=>'8370', 'number'=>'8056', 'address'=>'qdfbc', 'company'=>'taufrid', 'desc'=>'pppzhfhcdqcvbirw', 'age'=>'5512', 'title'=>'zticbcd', 'phone'=>'hvdkltabshgakjqmfrvxo', 'email'=>'eodnqepua', 'zip'=>'eodnqepua', 'country'=>'pdibxicpqipbsgnxyjumsza'), array('id'=>'1', 'name'=>'rbdmbabficcre', 'date'=>'10-Sep-2004', 'price'=>'3075', 'number'=>'3627', 'address'=>'oxcm', 'company'=>'xyzwzv', 'desc'=>'rwndyoedxh', 'age'=>'2134', 'title'=>'lxxyfgdtdffjce', 'phone'=>'zeejvbwy', 'email'=>'ldcikhxwfuulaxeedkogpxftb', 'zip'=>'ldcikhxwfuulaxeedkogpxftb', 'country'=>'pcmobxrdfclcyrx'), array('id'=>'2', 'name'=>'yr', 'date'=>'04-Mar-2007', 'price'=>'7129', 'number'=>'6614', 'address'=>'i', 'company'=>'gcpvrshftfxxlz', 'desc'=>'nyalrdjjl', 'age'=>'4728', 'title'=>'ddfl', 'phone'=>'mnhifzqltvirgiaug', 'email'=>'f', 'zip'=>'f', 'country'=>'epipbmtfsfxetenyedjxzsog'), array('id'=>'3', 'name'=>'bhqggvwolybfdtk', 'date'=>'26-Dec-2000', 'price'=>'1867', 'number'=>'4288', 'address'=>'jo', 'company'=>'goevufkvmbct', 'desc'=>'zhixinabyazbfleozrvovr', 'age'=>'3423', 'title'=>'b', 'phone'=>'odhh', 'email'=>'g', 'zip'=>'g', 'country'=>'idxvdztezvkkaz')); } And Mine: Code: [Select] function initArray() { return $echoarray; } Where am I going wrong here? I got some code to make a simple quiz, but I'm struggling to get it to work. I think the form and the following JavaScript code are set up correctly, but I'm running into problems with the PHP code at the end. I'm especially confused by the JSON reference at the very end; I don't have a clue what it means or what do do with it.
Does anyone know how to fix/complete this script?
On another note, why is it necessary to use JSON in the first place? Aren't the answers already provided in the PHP code (e.g. $answer1 = $_POST['A']?
Thanks.
<form action=""> <fieldset> What color is an apple? <label>blue <input type="radio" value="A" name="question-1"></label> <label>red <input type="radio" value="B" name="question-1"></label> <label>yellow <input type="radio" value="C" name="question-1"></label> <label>gray <input type="radio" value="D" name="question-1"></label> </fieldset> <fieldset> What color is a banana? <label>yellow <input type="radio" value="A" name="question-2"></label> <label>blue <input type="radio" value="B" name="question-2"></label> <label>red <input type="radio" value="C" name="question-2"></label> <label>gray <input type="radio" value="D" name="question-2"></label> </fieldset> <fieldset> What color is the sky? <label>yellow <input type="radio" value="A" name="question-3"></label> <label>blue <input type="radio" value="B" name="question-3"></label> <label>red <input type="radio" value="C" name="question-3"></label> <label>gray <input type="radio" value="D" name="question-3"></label> </fieldset> <fieldset> What color is snow? <label>white <input type="radio" value="A" name="question-4"></label> <label>blue <input type="radio" value="B" name="question-4"></label> <label>red <input type="radio" value="C" name="question-4"></label> <label>gray <input type="radio" value="D" name="question-4"></label> </fieldset> <input type="button" value="Submit" class="submit" id="Submit2"> </form> <script> $(function(){ // Trap the form submit event $('form').submit(function(e){ e.preventDefault() // Prevent browser refresh var answers = $(this).seralize() // Manually send the data with AJAX $.post({ url: $(this).attr('action'), data: answers, // Stuff to do after we get a response success: function(response){ $('#results').text(response.correct) } }) }) }) </script> <?php $answer1 = $_POST['A']; $answer2 = $_POST['A']; $answer3 = $_POST['C']; $answer4 = $_POST['D']; $totalCorrect = 0; if ($answer1 == "B") { $totalCorrect++; } if ($answer2 == "A") { $totalCorrect++; } if ($answer3 == "B") { $totalCorrect++; } if ($answer4) { $totalCorrect++; } // Send the data back as JSON die json_encode(array( 'correct' => $totalCorrect; )); ?> First, apologies if this is in the wrong section, basically I am not sure what language my problem lies! Here is the general over view. I have a jquery script that automatically selects a group of sub categorys and pus them in a select list depending on the input of a first select list, so you can choose you main cat and then the sub cats for this cat appear in the next list, this all works fine, the basic code is below: Code: [Select] <script type="text/javascript"> $(document).ready(function() { $('#wait_1').hide(); $('#drop_1').change(function(){ $('#wait_1').show(); $('#result_1').hide(); $.get("scripts/func.php", { func: "drop_1", drop_var: $('#drop_1').val() }, function(response){ $('#result_1').fadeOut(); setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400); }); return false; }); }); function finishAjax(id, response) { $('#wait_1').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } </script> <form action='do.php' method='post'> <select name="drop_1" id="drop_1"> <option value="" selected="selected" disabled="disabled">Select a Category</option> <?php getTierOne(); ?> </select> <span id="wait_1" style="display: none;"> <img alt="Please Wait" src="images/ajax-loader.gif"/> </span> <span id="result_1" style="display: none;"></span> This calls scripts/func.php Code: [Select] <?php //************************************** // Page load dropdown results // //************************************** function getTierOne() { $result = mysql_query("SELECT * FROM blog_cats") or die(mysql_error()); while($tier = mysql_fetch_array( $result )) { echo '<option value="'.$tier['cat_id'].'">'.$tier['cat_name'].'</option>'; } } //************************************** // First selection results // //************************************** if($_GET['func'] == "drop_1" && isset($_GET['func'])) { drop_1($_GET['drop_var']); } function drop_1($drop_var) { include_once('../connect.php'); $result = mysql_query("SELECT * FROM blog_subs WHERE cat_id='$drop_var'") or die(mysql_error()); echo '<select name="tier_two" id="tier_two"> <option value=" " disabled="disabled" selected="selected">Select Sub Catergory</option>'; while($drop_2 = mysql_fetch_array( $result )) { echo '<option value="'.$drop_2['sub_id'].'">'.$drop_2['sub_name'].'</option>'; } echo '</select> '; } ?> The problem I am having is getting the second select (tier_two) to pass to my form processing page. I just get an undefined variable error Many Thanks Hallo I'm having a problem inserting $messageorder into mysql datebase. Otherwise works good. So there is no problem with database itself or mysql command too. I suspect there must be something in this code that mysql doesnt like. Also have to say that im able to sent email with $messageorder. Please take a look at the codee. Code: [Select] $messageorder = "\r\n" . 'Order:' . '<br><br><table>' . "\r\n"; $result3 = mysql_query("SELECT * FROM orderslist WHERE supplier='$supplier'") or die(mysql_error()); $data = array(); $data['' . $row3['id']] = $_POST['' . $row3['id']]; while($row3=mysql_fetch_array($result3)) { $value = $_POST['' . $row3['id']]; if ( $value == ""){ } else { $messageorder .= " <tr> <td class='H4'><strong>$row3[name]</strong></td> <td class='H4' align='center'>$value</td> <td class='H4'>$row3[unit]</td> </tr> "; } } $messageorder .= "</table>"; echo $messageorder; date_default_timezone_set('Europe/London'); $supplier=$_GET['order']; $delivery=$_POST['delivery']; $timestamp = date("H:i:s"); $datestamp = date('Y/m/d'); mysql_query ("INSERT INTO orders (id, datestamp, timestamp, supplier, ordertext, delivery ) VALUES ('', '$datestamp', '$timestamp', '$supplier', '$messageorder', '$delivery')"); If someone could help to find a solution I will appriciate ! Thank you very much Hi,
Well, I've been wondering if I can get answer to my problem here...
I'd used curl to fetch information from other site and then I need to parse the data to be displayed in our own. However I found something odd...I can't parse it to get what I want...however should I put the result into a html file, n parse the file itself...it's fine.
Basically I just need to find whether a word/phrase is there or not...n I'm using preg_match to do it so far. Since the time it first arises...I'd been googling n saw some posts...something similar to how regex is doing poorly in doing such thing...
However it does work when I just make a php file just to do that regex from the curl-result html file, it just not work on the actual php file which handle the process even if it's from the same curl-result html file. FYI, I'm using codeigniter.
I wonder if it got something to do with codeigniter or something...or is there any other better way to parse a html file from a curl result. In my opinion it's just the same...be it a curl result or just a normal html...so I really can't figure out where it went wrong.
I appreciate if there's anyone who can shed a light on this problem, even a little bit is a great help to me
Thanks in advance,
Hi, This is an odd one (to me anyway). I've created an API for deploying gig information in either XML or JSON format. It works fine as it is, both formats of output giving me what I want. When I take out the mySQL login information and replace it with "include 'connect_include.php';" (where the file connect_include.php contains the exact login code that I replced). The JSON output works fine but the XML output doesn't run. What could be causing this?? JSON API: -http://www.api.the-guards.co.uk/jsontest.php?apikey=123456&format=json XML API: - http://www.api.the-guards.co.uk/jsontest.php?apikey=123456&format=xml API code: Code: [Select] <?php if (($_GET['apikey'])==123456 and isset($_GET['format'])){ //Set variables $format = strtolower($_GET['format']); //Connect to the Database include 'connect_include.php'; //Run our query $result = mysql_query(' SELECT * FROM tg_gig_list where gl_date >= curdate() and gl_publish = 1 order by gl_date '); //Preapre our output if($format == 'json') { while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { $array[] = array($row['gl_date']=>($row['gl_venue'].', '.$row['gl_city'])); }; $output = json_encode($array); //Output the output. echo $output; header('Content-type: application/json'); } elseif($format == 'xml') { header('Content-type: text/xml'); $output = "<?xml version=\"1.0\"?>\n"; $output .= "<tggiglist>\n"; for($i = 0 ; $i < mysql_num_rows($result) ; $i++){ $row = mysql_fetch_assoc($result); $output .= "<giglist> \n"; $output .= "<giglist_date>" . $row['gl_date'] . "</giglist_date> \n"; $output .= "<giglist_venue>" . $row['gl_venue'] . "</giglist_venue> \n"; $output .= "<giglist_city>" . $row['gl_city'] . "</giglist_city> \n"; $output .= "</giglist> \n"; } $output .= "</tggiglist>"; } } else { die ('no way'); } //output the output echo $output; ?> Contents of 'connect_include.php: Code: [Select] <?php mysql_connect("database.lcn.com", "dbname", "password") or die(mysql_error()); mysql_select_db("db") or die(mysql_error()); ?> .....this is the same code that I replaced. Obviously, the 'connect' works ok as the JSON version runs fine. There's something being added to the scripting when I use the include file that isn't there when the code goes straight in.....I think???? This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=315198.0 Hi, it's my first post so hello to you and i hope you will be forgiving:) I've made a basic script, which takes a urls from the form(each of them is the new row) and then search each of those urls for an email. The problem is that only the email from the last url is returned. print_r("show link:". $urls[$i]."<br>"); shows all urls in the form, but the print_r("show current_url:". $current_url); shows only the last one. Code: [Select] <?php $urls = explode("\n", $_POST['urls']); $db = new mysqli('localhost', 'root', 'root', 'urls'); if (mysqli_connect_errno()) { echo 'Błąd: '; exit; } for ($i=0; $i<count($urls); $i++){ print_r("show link:". $urls[$i]."<br>"); $current_url = file_get_contents($urls[$i]); print_r("show current_url:". $current_url); preg_match( "/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $current_url, $email);//email print_r ("show email:".$email[0]); $zapytanie = "INSERT INTO urle set adres = '$email[0]' "; $wynik = $db->query($zapytanie); } if ($wynik) { echo $db->affected_rows ."pozycji dodano."; } else { echo mysql_errno() . ":" . mysql_error() . "Wystąpił błąd przy dodawaniu urli "; } $db->close(); ?> My error happens on line #81 $ARR[$i] == $NEEDLE ? $Count++ : $Count I am using it in: private function _countIf($ARR, $NEEDLE){ $Count = 0; for($i = 0; $i < count($ARR); i++){ $ARR[$i] == $NEEDLE ? $Count++ : $Count } return $Count; }Edited March 25, 2019 by Karaethon Hello! First... I'm sorry about my english skills.. Seems that with my own language I don't get a correct or good answer So.. I have a site where visitors can put there favorite links to other sites and show them to others. My problem is multiple urls to same locations in sites-table. example: http://google.com http://google.com/ http://www.google.com http://www.google.com/ http://www.google.com/index.php (?) they all lead to same... is there any light and powerfull way to check these? I'm trying to use query with "like" but it only works if there is exactly same url. I use fopen to check that url really exicst.. table: Sites (basic information for link) -id -url -title +some meta tags if found -timestamp I'm not asking to do me this code. But if someone can tell me just what functions and others I'm looking for and what I need for this... My coal is to keep sites-table as clean as it can be. If visitor adds a url that is already in sites-table only thing that happens is updating timestamp. Thank you all for helping me! -Roosterr With the following code i can create an xml file. Code: [Select] <?php $myXML = new SimpleXMLElement("<myroot></myroot>"); $title= $myXML->addChild('title'); $title->addAttribute('number','12'); $titleName= $title->addChild('titleName', 'title1'); $titleLink= $title->addChild('titleLink', 'link1'); Header('Content-type: text/xml'); echo $myXML->asXML(); ?> But when i check the validity of xml file http://www.validome.org/xml/validate/ This error occurs: Can not find declaration of element 'myroot'. I suppose that the problem is missing of !DOCTYPE and !ELEMENT lines. How can i create valid XML documents with PHP automatically?? Is it possible to make it without writing doctype and element types for the whole element types of xml by hand $title, $titleName and $titleLink Thank you I'm trying to list all the tables in my database. I got this code pretty much "word" for word from the example at php.net, but I get: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in E:\wamp\www\test\test-in.php on line 67 <?php $db= $_POST['db']; $sql= "SHOW TABLES FROM $db"; $result=mysql_query($sql); while ($tblarray = mysql_fetch_row($result)){ ?><a href="?tablename=<?php echo $tblarray[0];?>"><?php echo $tblarray[0];?></a><?php } ?> What is wrong? Warning: mysql_select_db(): supplied resource is not a valid MySQL-Link resource in /home/rweekly/public_html/2012/view_arguments.php on line 41 Warning: mysql_query(): supplied resource is not a valid MySQL-Link resource in /home/rweekly/public_html/2012/view_arguments.php on line 43 Code: [Select] mysql_select_db($database_news, $news); $query_news = "SELECT * FROM news WHERE id = '$id'"; $news = mysql_query($query_news, $news) or die(mysql_error()); $row_news = mysql_fetch_assoc($news); $totalRows_news = mysql_num_rows($news); mysql_select_db($database_news, $news); $query_arguments = "SELECT * FROM argue WHERE pid = '$id'"; $arguments = mysql_query($query_arguments, $news) or die(mysql_error()); $row_arguments = mysql_fetch_assoc($arguments); $totalRows_arguments = mysql_num_rows($arguments); |