PHP/MYSQL : get unlimited data - php

i have a large data in my mysql database (500 rows), when i am trying to get all of them , the data is not coming from database.
Working Code
<?php
include '../db/db.php';
$categoriesDataQuery = mysqli_query($conn, "SELECT * FROM subcategories LIMIT 268");
while ($row = mysqli_fetch_assoc ($categoriesDataQuery)) {
$categoryData [] = $row;
}
$categoryNewData = $categoryData;
print (json_encode ($categoryNewData)) ;
mysqli_close ($conn);
?>
Not Working Code
<?php
include '../db/db.php';
$categoriesDataQuery = mysqli_query($conn, "SELECT * FROM subcategories");
while ($row = mysqli_fetch_assoc ($categoriesDataQuery)) {
$categoryData [] = $row;
}
$categoryNewData = $categoryData;
print (json_encode ($categoryNewData)) ;
mysqli_close ($conn);
?>
Maybe Mysql database have some limitation when user select a large data ?!
Who ever encountered this?

The problem is not with the SQL query or the amount of data that you're trying to encode. For some reason, json_encode can return an empty string instead of throwing an error when it encounters an invalid character.
You have to make sure that the SQL connection's charater encoding matches your database table's encoding. For example if you're using UTF-8 encoding on your table, you need to call the following function to force the same encoding on the PHP client:
mysqli_set_charset($conn, "utf8");
See the PHP docs for more information.

Related

Get data from MYSQL using PHP returns no results

So I am using this tutorial: https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ to try and get data from my local MYSQL server (using Wamp64). I had the undefined index error at first, which I fixed using the isset() statement.
But now it just returns:
{"result":[]}
I have, however, a lot of data in the set column of that database.
Here is the code:
<?php
//Getting the requested klas
$klas = isset($_GET['klas']) ? $_GET['klas'] : '';
//Importing database
require_once('dbConnect.php');
//Creating SQL query with where clause to get a specific klas
$sql = "SELECT * FROM lessen WHERE klas='$klas'";
//Getting result
$r = mysqli_query($con,$sql);
//Pushing result to an array
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
//Displaying the array in JSON format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I tried out the
SELECT * FROM lessen WHERE klas='$klas'
statement in my database and it seems to return the correct data.
Any idea what is causing this?
Thanks in advance!
Point 1 is:
isset function only checks if klas is set in the $_GET global array. So if somehow $klas is blank - your query will return empty (without giving error).
So please check values in the $_GET and possibly from where it is accessed. Or you can add condition to avoid empty query like --
if (!empty($_GET['klas'])) {
// rest of the code block upto return
Point 2 is:
You have mentioned if you echo the sql it returns
SELECT * FROM lessen WHERE klas=''{"result":[]}
Here the second part (the JSON) is from echoing the result at the end of your code. So for the first part (i.e. echoing $sql) we see that klas=''. That actually goes to the Point 1 as mentioned above.
So finally you have to check why the value at $_GET is showing blank. That will solve your problem.
UPDATE:
From #GeeSplit's comment For the request
"GET /JSON-parsing/getKlas.php?=3ECA"
There will be nothing in $_GET['klas'] cause the querystring in the url doesn't contain any key.
So either you have to change the source from where the file is called. Or you can change how you are getting the value of klas.
Example:
$tmpKlas = $_SERVER['QUERY_STRING'];
$klas = ltrim($tmpKlas, '=');
Rest of your code will work.
Use this code
<?php
$klas ='';
if(isset($_GET['klas']) && !empty($_GET['klas']))
{
$klas = $_GET['klas'];
require_once('dbConnect.php');
$sql = 'SELECT * FROM lessen WHERE klas="'.$klas.'"';
$r = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
?>

PHP Mysql query data not correct

I am a newbie Programmer here, I want to know why my code does not get the correct data from my Mysql DB.
mysql_connect('localhost',"root","password");
mysql_select_db("Torch");
$playerbal = mysql_query("SELECT money FROM table WHERE name = '$player'");
If I use this code, then I get the $playerbal as Resource id #7
I have found some solutions for this Resouce id #7 error. If I use mysql_fetch_array, I get just "Array"
mysql_* functions are now deprecated and shouldn't be used anymore.
Your code isn't working because you need to use mysqli_fetch_array() in order to retrieve the actual data in the table using a DB connection handler
Try using something like this :
//Create DB connection
$con=mysqli_connect("localhost","root","password","Torch");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
$result = mysqli_query($con, "SELECT money FROM table WHERE name = '$player'") or die(mysqli_error($con));
//Retrieve the info(row) from the retrieved recordset and loop through it
while($row = mysqli_fetch_array( $result )) {
//Retrieve the needed field from the row
$data=$row['money'];
//do your stuff here
}
//Close connection
mysqli_close($con);
BTW Don't forget to sanitize your inputs.
mysql_query() statement returns a resource pointer to the result set, not the data itself. You'll need to use mysql_fetch_array() in order to retrieve the actual data in the table.
here's the sol
$row = mysql_fetch_array($playerbal);
$data = $row['money'];
echo $data;
If you want to get all rows of money column then use this code-
mysql_connect('localhost',"root","password");
mysql_select_db("Torch");
$playerbal = mysql_query("SELECT money FROM table WHERE name = '{$player}'");
while($data = mysql_fetch_array($playerbal)){
echo $data[0]; //there is only one column so this column is stored into 0 index.
}

echo statement not showing result after getting variable from $_post in php mysql

I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.

PHP script for getting data from mysql only getting a portion of the values

I'm trying to get data from a mysql table and send it via a php script as a json string so it later can be used by for example ios apps.
The code i have so far is:
<?php
$con = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("FreeSir_MarinaLaroverket") or die("Unable to select database");
$arr = array();
$rs = mysql_query("SELECT * FROM Nyheter");
while($obj = mysql_fetch_assoc($rs))
{
$arr[] = $obj;
}
echo json_encode($arr);
?>
But when i use the script i get the following:
[{"Index":"1","Title":null,"News":null,"Date":"11\/1"},{"Index":"2","Title":"Andra nyheten","News":null,"Date":"22\/2"}]
As you might see there, i have some null values that pops up there from nowhere. I've doublechecked that i have the correct values inserted and all, but it still just gives me null.
I would appreciate it if anyone of you could see what is making this code not giving me all the values i want.
Best Regards
FreeSirenety
If your var_dump($arr) statement displays the correct data, so you probably have a problem with the JSON representation. Check the manual for json_encode(), and look for the $options parameter.

why Printing JSON in PHP via echo json_encode() Not show values but NULL some time?

I am using Android to create a app. Where user answer are store on mySQL on server via PHP code.
function fetch_all_complaints_by_packet($packet) {
global $dBConnection;
$query = "SELECT * FROM ".DB_PREFIX ."complaint ORDER BY id DESC LIMIT 0 , 10";
$result = mysql_query($query,$dBConnection) or die('Errant query: '.$query);
$complaints = array();
if(mysql_num_rows($result)) {
$i = 0;
while($complaint = mysql_fetch_assoc($result)) {
$complaints[$i] = $complaint;
echo ($complaint['details'].'<br>');
$i++;
}
}
//echo json_encode($complaints);
}
The following line
echo json_encode();
Cause error it show details as NULL, but
echo json_encode($complaint['details'].'<br>');
Print the correct data. What the problem is?
I've had something similar to this maybe check on your side if the problem is the same:
When you have an invalid UTF-8 string (invalid utf-8 characters) and try to JSON_Encode that data, it will return NULL.
It took me hours to find that in my code because after all it is AJAX call so you can't really see the errors coming out.
My suggestion is to turn error logging on and display all errors, you will probably see an error about UTF-8 encoding that failed. If not, try to utf8_decode your data and see if it shoots out the error i told you about.

Categories