json data not showing - php

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
}

Related

$_post isset not working. Used the same syntax on other examples and works perfectly. Value not able to be posted for where claus MYSQL PHP

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

php script to get data from database android

i m trying to build a JSON array from mysql. it does not get the information from mysql
<?php
$host="localhost";
$pwd="";
$user="root";
$db="mydb";
$con=mysqli_connect($host,$user,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo"failded to connect";
}
$query = mysqli_query($con,"select * from product");
if ($query)
{
while($row = mysqli_fetch_array($query))
{
$flag[] = $row;
}
print(json_encode($flag));
}
mysqli_close($con);
?>
Notice: Array to string conversion in C:\wamp\www\new\count.php on line 19
What does this error mean and how do I fix it?
Please initialize $flag something like this $flag = array()
hope it was helpful to you.
change print to print_r(json_encode($flag)) you won't get any error
You are converting your array to a json array so you have to use var_dump or print_r().

JSON ["data","pre database"]

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.

JSON returns [null,null] in my app

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

Having problems with cannot redeclare

I just finished writing this script and getting it to work but I need to use it a total of 8 times on 1 page. It works fine the first time but the second time I get: Fatal Error cannot redeclare get_names(). I've been told the way around this is to use include_once but I can't seem to figure out how exactly I'm supposed to do that. I've tried cutting both of the get_names parts out of the code and putting them into separate php files then using the include_once command. I got it to work but once again I got the same error after trying to use the script twice. I also tried putting the whole script into a php file and then using the include_once("scriptname.php") command and the same thing happened. So my questiion is how exactly do I cut this script up so I don't get this error anymore?
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
} ?>
put getNames function in afile.php and include that once at the start. take getNames function out of your current file.
so things goes like this
in first php file (say) you have this code - filea.php
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
you second file will have fileb.php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
..... rest of source code excluded. Make sure you get rid of getNames in this file
Now just include as per normal
include 'filea.php'; // include it once only
include 'fileb.php'; // as many times as your wish
or just wrap your code in a function and call that instead
If you are using this script 8 times, then put the entire thing inside a function and call that function 8 times instead of copy pasting.

Categories