So, I put my php page to connect to my android app on a hosted server (Hostgator). Now my PHP script for the JSON data seems to not be returning properly.This was working on my wamp server just fine. Example below of issue...
["data","pre database"][{"email":"thomas#wiregrass.edu","password":"test","fname":"Thomas","lname":"Cummings","phone":"5052030822","temppass":"15151","alert":"B"}]
Any ides as to what I did wrong or what is going on would be appreciated.
PHP script (might be outdated, this project is old):
<?php
$user = "ab73953_test";
$pass = "H3#ther78";
$db = "ab73953_testdb";
$out = array('data', 'pre database');
echo json_encode($out);
$db = mysqli_connect('localhost', $user, $pass, $db) or die("did not work");
$email=$_POST['username'];
$email = "thomas#wiregrass.edu"; // testing
$qry = 'SELECT * FROM users WHERE email = "'. $email .'"' ;
$result = mysqli_query($db, $qry) or die(" did not query");
$count = mysqli_num_rows($result);
$output = array();
if($count > 0){
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
echo json_encode($output);
}
else
echo json_encode("Could not find user");
mysqli_close($db);
?>
That's not valid JSON. JSON is basically javascript: If the json you generate would be a javascript syntax error, then it's not valid json.
You have two separate echo json_encode(...) blocks, so you're producing two entirely separate/distinct json strings. Your output can only be one SINGLE json string.
e.g. [...][...] is two separate arrays that have gotten glued together. It's a javascript syntax error, therefore it's also invalid json. If you had something like
$arr1 = array(...);
$arr2 = array(...);
echo json_encode(array($arr1, $arr2));
you'd end up with
[[...],[...]]
and be ok
But you have
echo json_encode($arr1);
echo json_encode($arr2);
and end up with
[...][...]
which is an outright syntax error.
And note that you're vulnerable to sql injection attacks.
Related
Ok so I am trying to select values from a table in mysql using a $_post. Below I have included a basic php file without post that seems to be working fine and returns json as expected with the value of username just manually set.
echo "connection";
$connection = mysqli_connect("localhost","root","","simplifiedcoding") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
echo "statement";
$sql = "select * from volley where username = 'cmac '";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
But then when I try to set the value of username with $_Post in another tester file it doesnt work. The value is not being set as seen below. The code is meant to check if the username has been set, then execute the function using the set data.I really dont know where this is going on and I appreciate that this is a common subject matter but I have no idea what is causing this to not be set.
require_once 'connection.php';
class Get_game
{
private $db;
private $connection;
function __construct()
{
$this->db = new DB_Connection();
$this->connection = $this->db->get_connection();
echo "connected";
}
public function get_game_id($username)
{
echo "query";
//$query = "select * from volley";
$query = "select game_id from volley WHERE username = '".$username."'";
echo "result";
$result = mysqli_query($this->connection, $query) or die ("Error in Selecting " . mysqli_error($this->connection));
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
return json_encode($emparray);
//close the db connection
mysqli_close($this->connection);
}
}
echo "class";
$game = new Get_game();
if (isset($_POST['username'])) {
$username = $_POST['username'];
echo "set";
if (!empty($username)) {
$game->get_game_id($username);
} else {
echo("error");
}
}
I have looked on previous answers on here but nothing seems to work. It is also quite annoying that I have other files with the same syntax but different variables to $_post that are working fine. I included a couple of echos to see where the code was failing as no errors are showing. The code creates the class fine but wont set the values. I will include a file that works fine with the same syntax below. I just can't figure out why one piece of code works fine in one instance and seems to not work at all in another with barely anything being changed.The first snippet of code works fine but I want to be able to execute the querying with a $_post value. I have tried different ways of doing this and none of them seem to work. The code is meant to return json and display it. The first snippet of code does this perfectly. I know that there is something wrong withh the $_post and issett() but i cannot figure it out
i'm trying to connect mysql database server xampp to android studio,i wrote php code and when i run the code ,the result not showing anything.
here is my code:
connection.php
<? php
define ('hostname','localhost');
define ('user','root');
define ('password','1993');
define ('dbname','mat');
$connect = mysqli_connect(hostname,user,password,dbname);
$mysqli->query("set character_set_server='utf8'");
$mysqli->query("set NAMES 'utf8'");
?>
php to fetch data from database:
show.php
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
include 'connection.php';
ShowMat();
}
function ShowMat()
{
global $connect;
$query = "Select * from mat;";
$result = mysqli_query($connect, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows > 0) {
while ($row = mysqli_fetch_assoc($result))
{
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("mata"=>$temp_array));
mysqli_close($connect);
}
How can I solve this?
I think your REQUEST_METHOD is GET so your code :
if($_SERVER["REQUEST_METHOD"]=="POST"){
so this condition will fail that is why you are not getting any echo.
You can use POSTMAN to test your apis give it a try its really useful.
You change this line mysqli_fetch_assoc to this line while ($row = mysqli_fetch_array($result))
This line is creating problem :if($_SERVER["REQUEST_METHOD"]=="POST").Check what type of data are you sending.Are you sending raw data or structured data.Try isset($_REQUEST['']). Example :
$action=isset($_REQUEST['action'])?$_REQUEST['action']:"";
switch($action)
{
case "ShowMat":
ShowMat();
}
function ShowMat()
{
// code
}
I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author
i am developing a php server sending arrays response to Android client using JSON. Now i simply testing the php code but the result is empty. Please help!!
<?php
#Connect to Database
$con = mysqli_connect("localhost","root","", "leoonline");
#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
//Check already exist account
$allaccount = mysqli_query($con, "SELECT * FROM usersacc");
$results = array();
while($row = mysqli_fetch_array($allaccount))
{
$results[] = array(
'id' => base64_decode($row['id']),
'phone' => $row['phone'],
'password'> $row['password']
);
}
$json = json_encode($results);
?>
Is this your final code? You are not outputting anything apart from the connection error message if it happens.
Change
$json = json_encode($results);
to
echo json_encode($results);
If its still blank, then it could be a db data problem.
i am experiencing some weird behaviour here.
i am using the following code to reference the facebook api.
$query = "SELECT msg, user_id, comment_time FROM comments WHERE aid = '$aid' ORDER BY comment_time DESC";
$result = mysql_query($query) or die("ERROR: $query.".mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_object($result)){
$uidval = $row->user_id;
$posterInfo = $facebook->api_client->users_getInfo($uidval, array('name', 'pic_square_with_logo', 'profile_url'));
$nameuser = $posterInfo[0]['name']; //this is line 50
$pic = $posterInfo[0]['pic_square_with_logo'];
$profile_url = $posterInfo[0]['profile_url'];
echo '<img src="'.$pic.'" />';
echo ''.$nameuser.'';
echo '<br>';
echo $row->comment_time;
echo '<br>';
echo $row->msg;
}
}
it gives me this error:
Fatal error: Cannot use string offset as an array in /home/amitver/public_html/roadies/comments.php on line 50
but surprisingly i am using the exact same code successfully at the top of my page. why this weird behaviour. this is the code at the top of page:
//connect to fB
$uid = $user_id;
$userInfo = $facebook->api_client->users_getInfo($user_id, array('name', 'pic_square'));
$nameuser = $userInfo[0]['name'];
$pic = $userInfo[0]['pic_square'];
I think that sometimes theusers_getInfo is returning an array, while other times it is returning a string. Probably it only returns a simple string if only one result is available.
Try this:
$nameuser = ($posterInfo[0]) ? $posterInfo[0]['name'] : $posterInfo['name'];
this will happen if $posterInfo is actually an empty string ('').
can you var_dump($posterInfo) in the loop and check what it's doing...