URL API (JSon) store in MySql - mysql

i want to store API result in database
i am new to this API php coding things,
<?php
$account_id = 1122;
$api = "http://url&account_id";
$json = file_get_contents($api);
print_r($json);
?>
here is the output
{"status":"ok","count":1,"meta":{"count":1},"data":{"1122":{"statistics":{"all":{"wins":112,"losses":118},"xp":721},"nickname":"nickie"}}}
now i want to store data in variables and as well want to show in Tables.
for saving it in variables i am using this method.
$nickname = $decoded->{'data'}->{$account_id}->{'nickname'};
$max_xp = $decoded->{'data'}->{$account_id}->{'statistics'}->{'xp'};
how can i show all data in tables. or anywhere on main body page.
sorry for my bad poor programming, i am trying to so learn it.

in this case if I understand correctly, it is necessary to create an HTML form you with two text boxes, you can later send this form in a PHP page that can retrieve the values of these input fields and create the URL for the API:
An HTML page
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Your page title</title>
</head>
<body>
<div>
<form method="post" action="/your/php/file">
<div>
<label for="name" />
<input type="text" name="username" id="name" />
</div>
<div>
<label for="location" />
<input type="text" name="location" id="location" />
</div>
<div>
<button>Submit</button>
</div>
</form>
</div>
</body>
</html>
A PHP page
<?php
if (isset($_POST['username'], $_POST['location']) && !empty($_POST['username']) && !empty($_POST['location'])) {
$username = htmlspecialchars($_POST['username']);
$location = htmlspecialchars($_POST['location']);
$account_id = 1122;
$api = "http://url?account_id&username={$username}&location={$location}";
$json = file_get_contents($api);
//now you have result as associative array
$result = json_decode($json, true);
//you can do what you want now
}
?>

Try to json_decode your results like this:
<?php
$account_id = 1122;
$api = "http://url&account_id";
$json = file_get_contents($api);
//now you have result as associative array
$result = json_decode($json, true);
//print_r($result);
$nickname = $result['data'][$account_id]['nickname'];
?>
try and tell me what

Related

Uploading images to database in codeigniter?

I tried searching but no success i want to upload max 5 images to database along with user form data.I have table where all user data of form posted is saved along with images uploaded[image upload is attached with user form] picture fields in database are named as pic1,pic2,pic3.. pic5 + email,password etc I am successfull in uploading image data to database but not images.
//controller
if ($this->form_validation->run()!=true) {
$data['countryDrop'] = $this->Country_states_cities->getCountries();
$this->load->view('header');
$this->load->view('register',$data); //Display page
$this->load->view('footer');
}else{
$form=array();
$form['first_name']=$this->input->post("first_name",true);
$form['last_name']=$this->input->post("last_name",true);
$form['dob']=date('Y-m-d',strtotime($this->input->post("dob",true)));
$form['email']=$this->input->post("email",true);
$form['password']=sha1($this->input->post("password",true));
$form['phone']=$this->input->post("phone",true);
$form['addline2']=$this->input->post("addressline2",true);
$form['zip']=$this->input->post("zip",true);
$result = $this->Couch_reg->insert_new_user($form); //call to model
//model
function insert_new_user($form)
{
$this->db->insert('tbl_usrs',$form);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
//view
<input type="file" name="uploadfile[]" accept = "image/*" multiple = "multiple" size="20" /> <br />
as we can see model part is very short i want to collect images name in array form and send it to database.
You need to save the images in the upload folder and save the image name in the database.
<html>
<body>
<form method="POST" action="<?php echo site_url('my-controller/file_upload');?>" 'enctype'=>'multipart/form-data'>
<label for="file">Filename:</label>
<input type="file" name="userfile[]" id="file" multiple>
<input type="submit" value="upload"></form>
</body>
</html>
Then create controller
make funtion inside it:
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
Hope this will help you.
For more you can try this: http://w3code.in/2015/09/upload-file-using-codeigniter/

Accessing data from Wikidata JSON file

I'm trying to access the following properties from the Wikidata API: id, url, aliases, description and label but so far have been unsuccessful. I'm sure I'm making basic mistakes and so far only have the following code. Any suggestions as to the best way to access this data is much appreciated.
<html>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=Google&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
}
?>
</body>
</html>
Edit - I have managed to get a string ($jsonArr) containing particular data that I would like. However I would like to get the first instance of the particular elements from the string specifically id, url, alias, description and label i.e. specifically: variable1 - Q95, variable2 - //www.wikidata.org/wiki/Q95, variable3 - Google.Inc, varialbe4 - American multinational Internet and technology corporation, variable5 - Google/ Please see code below:
<HTML>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=$search&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
var_dump($doc);
echo "<p>";
$jsonArr = $doc->documentElement->nodeValue;
$jsonArr = (string)$jsonArr;
echo $jsonArr;
}
?>
</body>
</HTML>
You need to show the JSON you want to parse...
Basicly you can get values out of JSON in PHP like this...
If $doc is the JSON you want to parse
$jsonArr = json_decode($doc, true);
$myValue = $jsonArr["keyYouWant"];
Edit after understanding what you are doing there :-)
Hi, Im sorry I was completely confused of what you were doing there... So I have testet your code on my server and just get what you want...
Following the code you wanted... I took clear var names, so they are a little bit longer, but easier to understand...
$searchString = urlencode($_POST['q']); //Encode your Searchstring for url
$resultJSONString = file_get_contents("https://www.wikidata.org/w/api.php?action=wbsearchentities&search=".$searchString."&format=json&language=en"); //Get your Data from wiki
$resultArrayWithHeader = json_decode($resultJSONString, true); //Make an associative Array from respondet JSON
$resultArrayClean = $resultArrayWithHeader["search"]; //Get the search Array and ignore the header part
for ($i = 0; $i < count($resultArrayClean); $i++) { //Loop through the search results
echo("<b>Entry: ".$i."</b>");
echo("<br>");
echo($resultArrayClean[$i]["id"]); //Search results value of key 'id' at position n
echo("<br>");
echo($resultArrayClean[$i]["url"]); //Search results value of key 'url' at position n
echo("<br>");
echo($resultArrayClean[$i]["aliases"]); //Search results value of key 'aliases' at position n
echo("<br>");
echo("<br>");
echo("<br>");
}

How do I get codeIgniter 2, Bradley - SignaturePad and DomPDF to work correctly

Hello: I am using signaturePad [http://thomasjbradley.ca/lab/signature-pad/]and have created a short web form in codeIgniter 2, located here: [http://gentest.lfwebz.com/crd/open_form3], that requires the users to actually sign the form.
I have also installed mPDF and domPDF and I have them working, sort of, but not quite the way I want it to.
The functionality I want is this: User opens web form, fills it out, signs it,
using signPad mentioned above. I then want to click a button that runs mPDF/domPDF and
captures the page and of course the embedded signature.
When I run mpdf/domPDF and pass it the view that houses the form, I think I have figured out it is just grabbing a fresh view, one without the signature, but several parts
of the form are missing. So after digging around, I think I have determined that I have to use image conversion of the signaturePad - this is where I am stuck. I have the code in, using the reference here: Signature pad and dompdf, but it does not work.
If you go to my page here: http://gentest.lfwebz.com/crd/open_form3, sign the page, click the "I accept" button
Here is my view
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../assets/jquery.signaturepad.css" media="screen">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="../jquery.signaturepad.min.js"></script>
</head>
<body>
<?php echo base_url(); ?>
<form method="post" action="<?php echo base_url(); ?>pdf.php" class="sigPad">
<label for="name">Print your name</label>
<input type="text" name="name" id="name" class="name">
<p class="typeItDesc">Review your signature</p>
<p class="drawItDesc">Draw your signature</p>
<ul class="sigNav">
<li class="typeIt">Type It</li>
<li class="drawIt">Draw It</li>
<li class="clearButton">Clear</li>
</ul>
<div class="sig sigWrapper">
<div class="typed"></div>
<canvas class="pad" width="198" height="55"></canvas>
<input type="text" name="output" class="output">
<input type="text" name="imgOutput" class="imgOutput">
</div>
<br /><br /><br />
<button type="submit">I accept the terms of this agreement.</button>
</form>
<script>
var sig;
$( document ).ready( function ( ) {
sig = $('.sigPad').signaturePad({defaultAction:'drawIt'});
} );
$( '.sigPad' ).submit( function ( evt ) {
$( '.imgOutput' ).val( sig.getSignatureImage( ) );
} );
</script>
</body>
</html>
here is the controller or the pdf.php mentioned above:
<?php
if(isset($_POST['imgOutput'])){$img_output = $_POST['imgOutput'];}
echo "position 1";
$bse = preg_replace('#^data:image/[^;]+;base64,#', '', $img_output );
echo "position 2";
echo $bse;
if ( base64_encode( base64_decode( $bse) ) === $bse ) {
require_once 'dompdf/dompdf_config.inc.php';
$html = '<!DOCTYPE html><html><head></head><body><p>Your signature:</p><br /><img src="'. $img_output .'"></body></html>';
$dompdf = new DOMPDF;
$dompdf->load_html( $html );
$dompdf->render( );
$dompdf->stream("test.pdf");
}
else{
echo ("ERROR !");
}
?>
What am I missing here? Please could some one point me in the right direction?
Let me know if you need more info.
Thank you in advance.

How To Display Error Messages With Wufoo API V3?

I am using the Wufoo API V3 to submit data from a form hosted on my website to my Wufoo account. I followed the example on the [Entries POST API][1] page, and I was able to successfully the data to my account.
I was wondering how I am able to check for error messages, and display the ErrorText for each text input field using PHP?
For example, if someone does not provide their email address in a required email field.
Here is the code I have so far:
<?
function submit() {
$ref = curl_init('https://myname.wufoo.com/api/v3/forms/xxxxxx/entries.json');
curl_setopt($ref, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
curl_setopt($ref, CURLOPT_POST, true);
curl_setopt($ref, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ref, CURLOPT_POSTFIELDS, getPostParams());
curl_setopt($ref, CURLOPT_USERPWD, 'XXXX-XXXX-XXXX-XXXX');
curl_setopt($ref, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ref, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ref, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ref, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ref, CURLOPT_USERAGENT, 'Wufoo.com');
$response = curl_exec($ref);
echo $response;
}
function getPostParams() {
return array( 'Field4' => "you#company.com");
}
submit();
?>
UPDATE (Nov 12, 2011):
MinisterOfPower,
Thanks for [the reply and advice][2] about the Wufoo PHP API Wrapper. I am now using the API Wrapper and it rocks. I am having some challenges integrating the code you provided with my form.
For example, if I have a form on index.php (see below) with an email required field. How would I be able to set up the API wrapper to display an error next to the appropriate input field after the form is submitted?
Here's the code for index.php:
<? require_once('my-wrapper.php'); ?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form1" name="form1" autocomplete="off" enctype="multipart/form-data" method="post" action="">
<div>
<label id="email" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg"/>
</div>
<div>
<label id="name" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg"/>
</div>
<input type="submit" name="saveForm" value="Submit" id="submit" class="submit" />
<input type="hidden" id="idstamp" name="idstamp" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" />
</form>
</body>
</html>
Here's the code for my-wrapper.php:
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('XXXXXX', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
UPDATE (Nov 20, 2011):
I am now able to display the error messages with the help of MinisterofPower's code and the Wufoo API wrapper. I have a couple of follow up questions:
I was wondering how I do set up the form below with PHP so that it posts the entries upon pressing the submit button?
Is it possible to do this using AJAX so the page does not refresh?
Here's the code:
<?
// API
require_once('WufooApiExamples.php');
// Wufoo
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
// Post Entries
$postArray = array();
foreach ($this->postValues as $key => $value) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('xxxxxx', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
$fieldError[$value->ID] = $value->ErrorText;
}
}
} catch (Exception $e) {
//Read the error message.
}
// Add Errors
function addErrors($fieldName, $fieldError, $add){
if($fieldError[$fieldName] != ''){
if ($add == 'message') return '<p class="errors">'.$fieldError[$fieldName].'</p>';
else if ($add == 'class') return 'class ="errors"';
}
}
?>
<!--Begin Form-->
<div <? echo addErrors('Field4', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field4', $fieldError, 'message')?>
</div>
<div <? echo addErrors('Field6', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field6', $fieldError, 'message')?>
</div>
<!--End Form-->
The process of retrieving the response is outlined in the API docs. Also, the markup for field errors in found the Dealing With Failure section.
Is is worth nothing that Wufoo offers API Wrappers for PHP and many other languages. I highly suggest using one of those since they make the process so much easier.
Using the Wufoo API, you'd search for a Success value of 0 in the response object and then parse the Field Errors node, as shown here:
$wrapper = new WufooApiWrapper($this->apiKey, $this->subdomain, 'wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost($this->formHash, $postArray);
if (!$result->Success) {
foreach ($result->FieldErros as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
A followup question was posted above, so I'll add my answer here.
You asked how to display an error next to the form in question. You could do this with either javascript or php. I'll show you the PHP way only.
Using PHP, you could redirect back to the form with a value in the GET param of the URL, enumerating the error fields and messages. So, for example, you could do this:
for($result->FieldErrors as $name => $value) {
$str.="$name=$value&";
}
if($str) {
$str = '?errors=true&'.$str;
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/$str");
exit;
}
Then, you'd wrap the above code in this if statement to check for error values on postback, like so:
if($_GET['errors']) {
require_once('my-wrapper.php');
else
//Your HTML HERE
endif
After that, add some PHP conditions which append class names to your fields if they contain errors. For example:
<label id="Field4" class="icons <?php if ($_GET['Field4']) echo 'error'; ?>" for="Field4">Email</label>
Finally, add some CSS to call out the error fields with a color or other indicator.
The other way to do this is with javascript.
Use the same logic as above, but add the following script to your page (grabbed from here and here.)
<script type="text/javascript" charset="utf-8">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return 'error';
}
}
}
function changeClass (elementID, newClass) {
var element = document.getElementById(elementID);
element.setAttribute("class", newClass); //For Most Browsers
element.setAttribute("className", newClass); //For IE; harmless to other browsers.
}
changeClass('Field4', 'error');
</script>
Then use this markup instead:
<label id="Field4" class="icons" for="Field4">Email</label>
Good luck.
PS: This code was written here in SO, so it will probably contain syntax errors. But you can get the point...

Displaying unnecessary HTML when showing content from MySQL database

My homepage pulls in content from my MySQL database to create a blog. I've got it so that it only displays an extract from the posts. For some reason it displays HTML tags as well rather than formatting it using the tags (See picture below).
Any help is appreciated.
Homepage:
<html>
<head>
<title>Ultan Casey | Homepage</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<div class="wrapper">
<div id="upperbar">
Home
About Me
Contact Me
Twitter
<form id="search-form" action="/search" method="get">
<input type="text" id="textarea" size="33" name="q" value=""/>
<input type="submit" id="submit" value="Search"/>
</form>
</div>
<div id="banner">
<img src="images/banner.jpg">
</div>
<div class="sidebar"></div>
<div class="posts">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
$sql = "SELECT * FROM php_blog ORDER BY timestamp DESC LIMIT 5";
$result = mysql_query($sql) or print ("Can't select entries from table php_blog.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", $row['timestamp']);
$title = stripslashes($row['title']);
$entry = stripslashes($row['entry']);
$id = $row['id'];
?>
<?php echo "<p id='title'><strong>" . $title . "</strong></p>"; ?><br />
<div class="post-thumb"><img src="thumbs/<?php echo $id ?>.png"></div>
<?php echo htmlspecialchars(substr($entry, 0, 1050)) ?>...
<br>
<hr><br />
Posted on <?php echo $date; ?>
</p>
</div>
</div>
</p
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
Image:
You're passing your post through htmlspecialchars, which encodes < as < and > as >, among other things. This means they display as < and > instead of being parsed as html tags.
The whole point of htmlspecialchars is to produce text that's inert in HTML... to make it display as-is.
A better way to do this is to NOT store <br /> (or any other html) in your post. Instead, use regular line breaks, and echo nl2br(htmlspecialchars($text)) into your page.
If you absolutely need to allow html, you might consider something like HTML Purifier to handle escaping nasty stuff, in which case you'd skip the htmlspecialchars call. Just beware: It's not a good idea to write your own filter to stop malicious code when displaying user-supplied HTML.
echo substr($entry, 0, 1050)