PHP - Problem Linking To Json File (i Think)
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; )); ?> Similar TutorialsI believe this is a PHP problem rather than a javascript one, but stand to be corrected. The following code shows two echo statements, with the second one commented out. The uncommented statement inside the javascript will not work, because while it calls up the check.php file it does not send the associated parameters correctly. I have left the commented echo in because it works perfectly. What's wrong? I know that javascript works client side, but the relevant php code has already run so the javascript should work. Code: [Select] <?php // code associated with a database query precedes this if ("{$row['passState']}" == 0) { ?> <script language="javascript" type="text/javascript" > <-- var newwindow; function popup() { newwindow = window.open('check/check.php?quizTitle=".urlencode($quizTitle)."','_blank','scrollbars=yes,top=0,left=0,width='+screen.width+',height='+screen.height); if (window.focus) {newwindow.focus()} } //--> </script> <?php echo '<form><input type="button" onClick="popup()" value="Check your answers"></form> '; //echo "<A HREF=\"check/check.php?quizTitle=".urlencode($quizTitle)."\" onClick=\"return popup(this, 'thoughts', 'scrollbars=1'); window.moveTo(0,0); window.resizeTo(screen.width,screen.height-100);\">Check your answers</A>."; } ?> My justification for presenting a full screen popup for students is so that they can see answers they have given in an earlier quiz. I find that if their popup is just a window over their working page, they can use the popup to just fill in their answers on a second attempt. Full screen mode will limit this. Hi, 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 :-) Hi Everyone, i need some help how can i save this jsonfile to the webserver? my code // Load initial values from JSON 'file' jsonfile = '[{"lane 1":"1","lane 2":"1","lane 3":"5","lane 4":"2"}]'; var initialstate = JSON.parse(jsonfile); setLaneState("lane1",initialstate[0]['lane 1']) setLaneState("lane2",initialstate[0]['lane 2']) setLaneState("lane3",initialstate[0]['lane 3']) setLaneState("lane4",initialstate[0]['lane 4'])
Hello I am using curl to get a json file which can be located he (It's way too long to copy paste it): http://www.opap.gr/web/services/rs/betting/availableBetGames/sport/program/4100/0/sport-1.json?localeId=el_GR After that i use json_decode to get the assosiative array.Till here everything seems ok.When i am using var_dump the characters inside the array are in Greek.After that i am using the following code: Code: [Select] class ArrayToXML { public static function toXML( $data, $rootNodeName = 'ResultSet', &$xml=null ) { // turn off compatibility mode as simple xml throws a wobbly if you don't. if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 ); if ( is_null( $xml ) ) //$xml = simplexml_load_string( "" ); $xml = simplexml_load_string("<?xml version='1.0' encoding='UTF-8'?><$rootNodeName />"); // loop through the data passed in. foreach( $data as $key => $value ) { $numeric = false; // no numeric keys in our xml please! if ( is_numeric( $key ) ) { $numeric = 1; $key = $rootNodeName; } // delete any char not allowed in XML element names `enter code here`$key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key); // if there is another array found recrusively call this function if ( is_array( $value ) ) { $node = ArrayToXML::isAssoc( $value ) || $numeric ? $xml->addChild( $key ) : $xml; // recrusive call. if ( $numeric ) $key = 'anon'; ArrayToXML::toXml( $value, $key, $node ); } else { // add single node. $value = htmlentities( $value ); $xml->addChild( $key, $value ); } } // pass back as XML return $xml->asXML(); } public static function isAssoc( $array ) { return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array))))); } And here comes the problem .All the greek characters inside the result are in some strange characters Code: [Select] Î?Î?Î¥Î?Î?ΡΩΣÎ?Î? for example.I really don't know what am i doing wrong.I am really bad with encoding /decoding things . Thanks in advance for your replies. PS:I have also Code: [Select] <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> in the page i display the result but it doesnt help. I actually have two parts to this post. One which describes just my understanding on how a multipart request should look with a REST API and gives a little context, and the second how to actually implement it using Sympony and api-platform. Part 1 Looking to simultaneously upload a file, some file meta data, and identifier of the uploading user to a REST API, and will do so using a multipart request. Based on swagger, looks like the request should look something like the following: POST /upload HTTP/1.1 Content-Length: 428 Content-Type: multipart/form-data; boundary=abcde12345 --abcde12345 Content-Disposition: form-data; name="id" Content-Type: text/plain 123e4567-e89b-12d3-a456-426655440000 --abcde12345 Content-Disposition: form-data; name="address" Content-Type: application/json { "street": "3, Garden St", "city": "Hillsbery, UT" } --abcde12345 Content-Disposition: form-data; name="profileImage "; filename="image1.png" Content-Type: application/octet-stream {…file content…} --abcde12345-- Background noise... The above example shows three parts which include the text ID, JSON address and octet-stream file. Doing so doesn't make sense to me and I will probably just have two parts for the meta data JSON. Note that potentially, I will be removing the user from the JSON payload and including it in some JWT header. Also, showing resources as links such as /api/users/1 in the request and response JSON is new to me, but I guess makes sense. Regardless, my meta data JSON will look like: { "projectId": 1234, "documentDescription": "bla bla bla", "specification": "230903.2.4.D", "user": "/api/users/1" } and the response will look like: { "projectId": 1234, "documentDescription": "bla bla bla", "specification": "230903.2.4.D", "uploadAt": "2021-01-27 08:41:17", "fileName": "pressuresensor.pdf". "user": "/api/users/1". "file": "/api/uplodaed_files/1234" } Am I somewhat going down the right path? Part 2 Wow, should have looked into Sympony before now! Entities, validation, the API, etc were a breeze. Still confused with some of the "magic", but understanding what is under the hood more and more. As stated initially, I am utilizing api-platform and am looking at api-platform's file-upload. I guess the first question is whether my POST request with both the file and JSON meta data can be performed in a single request. Per making-a-request-to-the-media_objects-endpoint: QuoteYour /media_objects endpoint is now ready to receive a POST request with a file. This endpoint accepts standard multipart/form-data-encoded data, but not JSON data. What? Am I reading this correct? Do I first need to make a multipart requests using either a standard HTML form or a XMLHttpRequest which just sends the file, receive the document locator, and then send a second request with the location and my meta data? If so, I guess I have enough to go forward. I would rather, however, perform the work in a single request. My previous mentioned swagger multipart-requests shows both in the same request. symfonycasts's api-uploads also describes doing so, but not with api-platform. Is there a way to do so with api-platform? Does it make sense to use api-platform for all other routes but then make a custom route for document with meta data uploads? Any recommendations are much appreciated. Thanks This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=322125.0 I want to add a note field and a checkbox to my list/grid page and save this information to a json file using uomptrucknumber as the key. The note information will be information for the whole truck not by order. The check box will let them know that the truck is ready to have paper work printed. I have not add the note field or checkbox because I did not want to start off wrong. echo "<table>"; echo "<tr style='background:#82fbfd'>"; echo "<th>ShipDate</th>"; echo "<th>ShipMeth</th>"; echo "<th>Name</th>"; echo "<th>LoadID</th>"; echo "<th>Drop</th>"; echo "<th>OrderID</th>"; echo "<th>Status</th>"; echo "<th>FGI</th>"; echo "<th>FGM</th>"; echo "<th>TotalBox</th>"; echo "<th>Cubes</th>"; echo "<th>Total</th>"; echo "<th>Notes \n</th>"; //echo "<table>"; echo "<tr style='background:#82fbfd'>"; $result =odbc_exec($connect,$sql); if(!$result){ exit("Error in SQL"); } function ShowDetail($row){ if($row['ompclosed']==-1){ $theColor="#AAF0D2"; }else{ $theColor="#FFFFFF"; } if($row['ompclosed']==0 && $row['date'] < date("m/d/Y")) { $theColor="#FF0000"; } echo "<tr style='background-color :$theColor'><td>" .$row['date'] ."</td>"; echo "<td>" .$row['ompshippingmethodid'] ."</td>"; echo "<td style='text-align:left'>" .$row['cmoname'] ."</td>"; echo "<td>" .$row['uomptrucknumber'] ."</td>"; echo "<td>" .$row['uompdropsequence'] ."</td>"; echo "<td>" .$row['ompsalesorderid'] ."</td>"; echo "<td>" .$row['ompclosed'] ."</td>"; echo "<td>" .round($row['FGIqty'],0) ."</td>"; echo "<td>" .round($row['FGMqty'],0) ."</td>"; echo "<td>" .round($row['uomptotalboxcount'],0) ."</td>"; echo "<td>" . number_format($row['uompvolumetotal'],2) ."</td>"; echo "<td>" . number_format($row['ompordertotalbase'],2) ."</td>"; echo "<td style='text-align:left'>" .$row['ompordercommentstext'] ."</td></tr>" ; } //**************************************************************** while ($row = odbc_fetch_array($result)) { if($row['ompclosed']==-1){ $theColor="#AAF0D2"; }else{ $theColor="#FFFFFF"; } if($row['ompclosed']==0 && $row['date'] < $today) { $theColor="#FF0000"; } if($row['uomptrucknumber'] != $loadid) { if ($loadid !== 0) { echo "<tr style='background:#eee'> <td colspan='7'>TOTAL</td> <td>$TotalFGI</td> <td>$TotalFGM</td> <td> </td> <td> </td> <td>$loadTotal</td> </tr>"; } $TotalFGI=0; $TotalFGM=0; $loadTotal=0; } ShowDetail($row); $loadid = $row['uomptrucknumber']; $TotalFGI+=round($row['FGIqty'],0); $TotalFGM+=round($row['FGMqty'],0); $loadTotal +=$row['ompordertotalbase']; } echo "<tr style='background:#eee'> <td colspan='7'>TOTAL</td> <td>$TotalFGI</td> <td>$TotalFGM</td> <td> </td> <td> </td> <td>$loadTotal</td> </tr> </table>"; odbc_close($connect); ?>
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 Hi, I have an issue with a banner I integrated in a page (http://hostelsuites.com) if you go to the page you'll see a banner on the left side , called "Combo Andes". The problem I am encountering is that this banner is linking to inside pages, and it works all fine for me but does not on some other computers, although they are using the same explorer or firefox versions.... I have no idea as to what could trigger this type of error, any help would be muche welcome. Some details that might help : The link is winthin the flash movie The code that brings the banner up depending on the chosen language is <div class="subtitulo"><?= ucfirst($lang["combomendoza"]) ?></div> Thank you very much in advance 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 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? 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 hello i have problems refreshing this: <?php header("Refresh: 2;"); $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = '02071987'; $dbname = 'ProvoleasDB'; mysql_connect($dbhost,$dbuser,$dbpass) or die ("I could not connect!"); mysql_select_db($dbname) or die (mysql_error()); header("Content-type: text/xml"); echo '<?xml version=\'1.0\' encoding=\'UTF-8\'?>'; echo ' <rss version=\'2.0\'> '; echo ' <channel> <title></title> <description></description> <link></link>'; $data = mysql_query('SELECT * FROM UploadItem ORDER BY IID DESC LIMIT 10'); while($row = mysql_fetch_array($data)) { echo ' <item> <title>'.$row['FileName'].'</title> <link>localhost/items.php?iid='.$row['IID'].'</link> <description>'.$row['IID'].'</description> <guid>http://localhost/items.php?iid='.$row['IID'].'</guid> </item>'; } echo ' </channel> </rss>'; ?> <html> <head> </head> <body> </body> </html> could you help me?? Hello erveryone. I am new in programming and i have the following problem i cant figure out! i want to make a search into my database. i have prepared my html-js-php files but it seems i have a php problem. When i search and i type whatever letter then i get those results only.. name: brand: price //my php file Code: [Select] <?php require_once('../Connections/Mysitedb.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $colname_Recordset1 = "-1"; if (isset($_GET['productname'])) { $colname_Recordset1 = $_GET['productname']; } mysql_select_db($database_Mysitedb, $Mysitedb); $query_Recordset1 = sprintf("SELECT manufacturer, productname, price FROM products WHERE productname = %s", GetSQLValueString($colname_Recordset1, "text")); $Recordset1 = mysql_query($query_Recordset1, $Mysitedb) or die(mysql_error()); $row_Recordset1 = mysql_fetch_assoc($Recordset1); $totalRows_Recordset1 = mysql_num_rows($Recordset1); ?> <!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> <body> <?php do { ?> <form id="form1" name="form1" method="post" action=""> <table width="353"> <tr> <td width="59">name:</td> <td width="282"><?php echo $row_Recordset1['productname']; ?></td> </tr> <tr> <td>brand:</td> <td><?php echo $row_Recordset1['manufacturer']; ?></td> </tr> <tr> <td>price</td> <td><?php echo $row_Recordset1['price']; ?></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> </tr> </table> </form> <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?> </body> </html> <?php mysql_free_result($Recordset1); ?> I have 4 websites http://www.mercurymagazines.com/pr1/101/101395 http://www.mercurymagazines.com/pr1/169/16000 http://www.mercurymagazines.com/pr1/101/101396 http://www.mercurymagazines.com/pr1/169/16001 I am trying to write a program that will open each webpage one at a time, look for a unique word such as 'FREE' and if it is found the write the URL to a file, if not then no output and the next webpage is opened. I know this word exists only on one of the pages above (http://www.mercurymagazines.com/pr1/101/101396). When http://www.mercurymagazines.com/pr1/101/101396 appears last in the list located in source.txt the programs WORKS. When http://www.mercurymagazines.com/pr1/101/101396 appears in any other position such as first, or second, the program does NOT work. My head is sore from banging against my desk. Any assistance would be appreciated. <?php $file_source = fopen("source.txt", "r"); $file_target = fopen("targets.txt", "w"); while (!feof($file_source) ) { $url = fgets($file_source); echo '<br>'.$url; $raw_text = file_get_contents($url); mb_regex_encoding( "utf-8" ); $words = mb_split( ' +', $raw_text ); foreach ($words as $uniques) { echo $uniques; if ($uniques == 'FREE') { fwrite($file_target, $url); } } } ?> Hi, I am trying to insert the contents of a csv file into a table, this is my code: public function InsertCSVFileToDB(){ $has_title_row = true; $not_done = array(); if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){ $filename = basename($_FILES['csvfile']['name']); if(substr($filename, -3) == 'csv'){ $tmpfile = $_FILES['csvfile']['tmp_name']; if (($fh = fopen($tmpfile, "r")) !== FALSE) { $i = 0; while (($items = fgetcsv($fh, 10000, ",")) !== FALSE) { if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file $i++; continue; } $sql = "INSERT INTO ConfPaper SET CPRid = ".$items[0].", Pid = ".$items[1].", CPtitle = '".mysql_real_escape_string($items[2])."', CPabstract = '".mysql_real_escape_string($items[3])."', CPspage = ".mysql_real_escape_string($items[4]).", CPepage = ".mysql_real_escape_string($items[5]).", CPlastesited = now()"; if(!mysql_query($sql)){ $not_done[] = $items; } $i++; } } // if there are any not done records found: if(!empty($not_done)){ echo "<strong>There are some records could not be inserted</strong><br />"; print_r($not_done); } } else{ die('Invalid file format uploaded. Please upload CSV.'); } } else{ die('Please upload a CSV file.'); } } This is the csv file: http://www.prima.cse.salford.ac.uk:8080/~ibrarhussain/ConfPaper.csv But i keep getting this: Quote Array ( => Array ( => 9 [1] => 1 [2] => CSV1 [3] => 4 [4] => 4 [5] => 01625 584412 ) [1] => Array ( => 9 [1] => 1 [2] => CSV2 [3] => 14 [4] => 24 [5] => 01625 584412 ) ) Any ideas what the problem might be? Hope someone can help.. Thanks I am having trouble getting my upload file to work... Form HTML: Code: [Select] <form action="" method="POST"> <input type="file" name="file" /> <input type='"submit" name="upload" value="Upload" /> </form> PHP: Code: [Select] if($_POST["upload_avatar"]){ $upload_path = "images/users/"; $file = $_FILES["file"]["name"]; $extension_types = array("gif","jpg","jpeg","png"); if($file){ $filename = stripslashes($_FILES["file"]["name"]); $extension = getExtension($filename); $extension = strtolower($extension); $size = filesize($_FILES["file"]["tmp_name"]); if(in_array($extension, $extension_types)){ if($size <= $max_file_size){ $file_search = glob($upload_path . strtolower($username) . '*'); array_map("unlink", $file_search); $file_name = $upload_path . strtolower($username) . "." . $extension; $copied = copy($_FILES["file"]["tmp_name"], $file_name); if (!$copied){ $r_error = "Upload has failed"; } } else{$r_error = "File too big";} } else{$r_error = "Unknown file extension";} } else{$r_error = "No file chosen";} } Every time, it gives me the "No File Chosen" error. It doesn't seem to be actually uploading the file... I hope this isn't just some stupid thing I am looking over, can someone help me? How do I write a bit of code to check if a file is NOT readable...and if (and only if) it is NOT readable (doesn't exist) , wget the file. Here's what I tried...but it loops forever and ever...even if the file does exist. Code: [Select] $filename = "file.mp3"; while(!is_readable($filename)) { $url = "domain.com" . ".mp3"; echo system('wget '.escapeshellcmd($url)); echo system('sleep 30'); } ?> I Googled...and couldn't find the correct syntax for IS NOT READABLE. Thanks! |