Android connecting to MySQL json_encode - php

I am trying to get data from MySQL database but in the php file I get this error:
Fatal error: Call to undefined function: json_encode() in /homez.100/pizzapar/www/clic/marwa/test/base.php on line 13
Here is my php file:
<?php
echo"welcom <br>";
$conn = mysql_connect('xxx.xxx.xxx.xxx','xxx','xxx');
if ($conn) {
mysql_select_db('zak', $conn);
$sql=mysql_query("select * from zak_user");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
}
else
{
echo"erreur connexion";
}
Can some one help?

According to the manual, json_encode() is available in PHP >= 5.2.0 only. You are probably running an older version.

See here:
http://www.boutell.com/scripts/jsonwrapper.html
This is a replacement for JSON in earlier PHP versions.
Usage:
require 'jsonwrapper.php';
At the top of your code and you're ready to go. Of course,
jsonwrapper.php must be in the same folder. If not, adjust the require
command.
json_encode example
Just to give you a sense of the possibilities:
$data = array(
array('name' => 'Jane', 'age' => 35),
array('name' => 'Steve', 'age' => 37)
);
<script>
var data = <?php echo json_encode($data) ?>;
</script>
And this is the direct download:
http://www.boutell.com/scripts/jsonwrapper.tar.gz

json_encode used to be not part of PHP, you might have to compile an extension to enable this function.
It's been awhile that json_encode is shipped with PHP(since 5.2), I advise you to upgrade.

Related

PHP Included Array Warning

I'm having a problem with an array in php, which I use to store configuration data for different environments. The idea is that I only have to switch out the file with the config data when going from local testing to using it on the server. The file looks like this:
<?php
$_ENV = array(
'MySQL' => array(
'database'=>'<DATABASENAME>',
'server'=>'<SERVERNAME>',
'username'=>'<USERNAME>',
'password'=>'<PASSWORD>'
)
);
?>
And I include it this way:
include('../env.php');
For the connection to the database I use it like this:
$conn = mysql_connect($_ENV['MySQL']['server'], $_ENV['MySQL']['username'],$_ENV['MySQL']['password']) or die("No connection possible: " . mysql_error());
Ignoring the fact that I'm still using mysql instead of PDO or mysqli, which is a thing I'm going to change soon, this should work. But it does not:
Notice: Undefined index: MySQL in D:\data\dev\applications\wtc-feedback\dashboard\include\SQLrequest.php on line 36
The strange thing is that when I dump the environment variable onto the screen with var_dump() the indexes and the contents are all just fine.
Does anyone know how to fix this?
If You want to work with environmental variables use getenv, putenv
or use .env files (package here, docs here) and add .env to .gitignore
in fact Your code must be like this:
env.php:
<?php
putenv('DB_NAME=DATABASENAME');
putenv('DB_HOST=SERVERNAME');
putenv('DB_USER=USERNAME');
putenv('DB_PASS=PASSWORD');
connection.php:
<?php
include('../env.php');
$conn = mysql_connect(getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASS'))
OR die("No connection possible: " . mysql_error());
".env" way:
.env file:
DB_NAME=DATABASENAME
DB_HOST=SERVERNAME
DB_USER=USERNAME
DB_PASS=PASSWORD
connection.php:
<?php
require_once('../vendor/autoload.php');
use Symfony\Component\Dotenv\Dotenv;
(new Dotenv())->load(__DIR__.'/../.env');
$conn = mysql_connect(getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASS'))
OR die("No connection possible: " . mysql_error());
Simple solution wouuld be, return the simple array from the file. as
<?php
return array(
'MySQL' => array(
'database'=>'<DATABASENAME>',
'server'=>'<SERVERNAME>',
'username'=>'<USERNAME>',
'password'=>'<PASSWORD>'
)
);
?>
In other file
$credentials = require_once "../env.php";
Use the $credentials array to supply parameters to mysql connection function

Insert data in MongoDB using PHP

I am on php 5.6 using WAMP and want to insert a document into MongoDB using PHP. I am doing it in this way:
<?php
require 'vendor/autoload.php';
$con = new MongoDB\Client("mongodb://localhost:27017");
echo "successfully";
$db = $con->selectDatabase('DB');
echo "Selected";
$col = $db->selectCollection('myCol');
$document = array(
"name" => "Deny",
"password" => "1234"
);
$col->insert($document);
echo "successfully";
?>
But it is giving the error
Fatal error: Call to undefined method MongoDB\Collection::insert() in C:\wamp64\www...
I have read http://php.net/manual/en/mongocollection.insert.php and when I use the same insert function, it doesn't work for me.
Instead of MongoDB\Client use MongoClient .
This works for me.
You have to install MongoClient library:
http://php.net/manual/en/mongo.installation.php
Instead of method MongoDB\Collection::insert() using insertOne() or insertMany() would work!

Fatal error: Cannot use object of type PDO as array

Here is the error Log
Fatal error: Cannot use object of type PDO as array in /Applications/XAMPP/xamppfiles/htdocs/php/blog/single.php on line 13
Here is 13 number line
$post = DB\query('SELECT * FROM posts WHERE id = :id LIMIT 1', array('id' => $_GET['id']), $conn [0] );
i got this error when i try to get post title.
<?= $post['title'];?>
Full Code
<?php
require 'functions.php';
use blog\DB;
// Connect to the DB
$conn = DB\connect($config);
if( !$conn ) die('Problem Connecting to the DB');
// Fetch all the posts
$post = DB\query('SELECT * FROM posts WHERE id = :id LIMIT 1', array('id' => $_GET['id']), $conn [0] );
// Filter throgh and display in the view
$view_path = 'views/single.view.php';
include 'views/layout.php';
Instead of $conn[0], Try using $conn.
For future issues, always remember you can output the datatypes, content, and structures of variables in php.
Use the following to output the content in human readable format.
echo "<pre>";
print_r($variable);
echo "</pre>";
die();
Use the following to output the content with datatype and extra info
echo "<pre>";
var_dump($this);
echo "</pre>";
die();
Remember functions like gettype() etc.
Also based on your further comments, I'd recommend that you first grab a book or an online course of the language.
About your next error, remember that in php the variable needs to be defined before you can call/use it.
So on the line, where you care calling $post['title']; remember to first make sure that that variable is defined and has the index that you intend to call. Also use the above snippets to verify and you should be writing the handling code if that index is not set.
something like..
if(isset($post) && !empty($post) && isset($post['title'])) {
....

Access a PHP array with Perl

I am primarily a PHP developer and have limited experience with Perl.
I was tasked with writing a queue script in Perl which checks against a database, and that is all working out great.
The problem I have is that in the Perl script I need to include a database hostname and password.
Right now I have them hard coded, which works fine, but my PHP application uses a global PHP array which holds the database hostname and password.I'd like to be able to use this PHP array in my Perl script.
Here is my PHP array
<?php
return array(
'database' => array(
'master' => array(
'hostname' => 'fd35:4776:6804:2:a::1',
'password' => 'password'
),
'slave' => array(
'hostname' => 'fd35:4776:6804:2:2::2',
'password' => 'password',
'profile' => true
)
)
);
I've tried searching with Google and have read many random posts on line, but I have yet been able to come up with a solution.
Does anyone have any ideas which I could try? If I'm missing any additional input, let me know and I can provide it.
Edit
Hopefully I worded this properly. How would I go about including this PHP array file so that I can manipulate it with Perl?
Alternative solutions are welcome too!
You've discovered one of the many reasons why code makes for bad config files. You should move the information to an actual config file, and access that file from both that .php file and from Perl.
JSON would make a decent file format here.
{
"database": {
"master": {
"hostname": "fd35:4776:6804:2:a::1",
"password": "password"
},
"slave": {
"hostname": "fd35:4776:6804:2:2::2",
"password": "password",
"profile": true
}
}
}
The Perl code would be
use JSON::XS qw( decode_json );
open (my $fh, '<:raw', $config_path)
or die("Can't open config file $config_path: $!\n");
my $file; { local $/; $file = <$fh>; }
my $config = decode_json($file);
On the PHP side, just replace the contents of the file you showed in your post with code to read the config file. I don't know PHP, but it should be quite simple. A quick search shows it might be
return json_decode(file_get_contents($config_path));
It would be simple to provide a short PHP program that dumps the array to a file in JSON format. That file can then be read from Perl using the JSON module.
This is all that is necessary.
<?php
$array = include 'array.php';
$fh = fopen('array.json', 'w');
fwrite($fh, json_encode($array));
fclose($fh);
?>
The resultant JSON file can then be read in a Perl program, like so:
use strict;
use warnings;
use JSON 'from_json';
my $data = do {
open my $fh, '<', 'array.json' or die $!;
local $/;
from_json(<$fh>);
};
use Data::Dump;
dd $data;
output
{
database => {
master => { hostname => "fd35:4776:6804:2:a::1", password => "password" },
slave => {
hostname => "fd35:4776:6804:2:2::2",
password => "password",
profile => bless(do{\(my $o = 1)}, "JSON::XS::Boolean"),
},
},
}
There is PHP::Include, which uses a source filter to let you have PHP blocks in your Perl code to declare variables. It also has a read_file() function that applies such a filter to a single PHP file.
But it seems to expect that your PHP has assignments (e.g. $config = array('database' => array(...) and changes those to Perl variable declarations.
In a few minutes of playing with it, I couldn't get it to do anything useful with your PHP code that uses return.
If you want a more "native Perl" solution, you can pretty much* just search and replace all your "array(" and their matching ")" to "{" and "}". That'll give you a perl datastructure called a "hash of hashes" (note: Unlike PHP, Perl refers to arrays with integer indicies as arrays (and uses the # sigil to denote variables containing them), but refers to array-like things with string indicies as "hashes" (and uses the % sigil to denote variables containing them)). The Perl keywords/concepts you probably want to read up on are:
Perl Data Structures: http://perldoc.perl.org/perldsc.html
and specifically the Hash Of Hashes section: http://perldoc.perl.org/perldsc.html#HASHES-OF-HASHES
and if you dont understand what $hashref = \%hash and %hash{key} and $hashref->{key} mean in Perl, you'd want to read http://perldoc.perl.org/perlref.html
Example code (note how similar the getConfig subroutine is to your PHP code):
#!/usr/bin/perl
use strict;
use warnings;
my $config=getConfig();
print "Database master host = " . $config->{database}{master}{hostname};
print "\n";
print "Database master password = " . $config->{database}{master}{password};
print "\n";
print "Database slave profile = " . $config->{database}{slave}{profile};
print "\n";
sub getConfig{
return {
'database' => {
'master' => {
'hostname' => 'fd35:4776:6804:2:a::1',
'password' => 'password'
},
'slave' => {
'hostname' => 'fd35:4776:6804:2:2::2',
'password' => 'password',
'profile' => 'true'
}
}
};
}
I said "pretty much", because your sample data used the bare word 'true' for the slave->profile value - that's a syntax error in Perl - you can change it to a bare 1, or quote the value as "true" to make it work. In Perl, the digit zero, the string "0" or the empty/nul string "" all evaluate to "false" in a boolean context, anything else evaluates to "true". Take care if you choose to automate PHP to Perl translation, there may be other PHP-isms which could catch you out like that.
So much good information here and it helped me out quite a bit to come up with a working solution.
Here is the perl script I've got working:
#!/usr/bin/perl
use PHP::Include;
include_php_vars( 'config.local.php' );
my $test = \%config;
print $test->{'database'}->{'master'}->{'hostname'};
I also took the PHP array and changed it so that it no longer return array() but $config = array() and then return $config;
This did the trick for me. Thank you!

xslt_create() with PHP5

I am currently trying to display a RSS feed in a PHP page, but it seems to have a problem between the xslt_create() function and PHP5.
<?php
$xh = xslt_create();
$file=fopen(WEB_DIR . 'assets/_xml/rss.xml','r');
$xml=fread($file,16384);
fclose($file);
$file=fopen(WEB_DIR . 'assets/_xml/rss.xslt','r');
$xsl=fread($file,16384);
fclose($file);
$arguments = array(
'/_xml' => $xml,
'/_xsl' => $xsl
);
$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
xslt_free($xh);
print "$result";
?>
I get the error
Fatal error: Call to undefined
function xslt_create() in
What do I have to do to correct this issue ?
xslt_create only exists in PHP 4 - as this approach to parsing XML was removed in PHP 5.
As such, I'd recommend updating your code to use one of the current PHP 5 approaches as listed within the XML Manipulation section of the manual. (The XSL extension provides a XSLTProcessor class that is probably the nearest direct equivalent.)

Categories