Convert MySQL query into JSON object using PHP - php

I am new to programming and have a question about converting a MYSQL query with a Join into a JSON object using PHP. When running the statement through phpMyAdmin I get results. However, when attempting the convert it into a JSON object I am getting a blank screen. Any help is greatly appreciated! Here is my code:
$myquery = "SELECT track_ticseverity.date, track_ticseverity.ticnum, track_ticseverity.user_id, track_fatigue.date, track_fatigue.fatiguenum, track_fatigue.user_id
FROM track_ticseverity
INNER JOIN track_fatigue
ON track_ticseverity.date=track_fatigue.date
WHERE track_ticseverity.user_id=1
AND track_fatigue.user_id=1;"
$query = mysqli_query($conn, $myquery);
if ( ! $query ) {
echo mysqli_error();
die;
}
$data = array();
for ($x = 0; $x < mysqli_num_rows($query); $x++) {
$data[] = mysqli_fetch_assoc($query);
}
echo json_encode($data);
mysqli_close($server);

Did you connect to your database? (mysqli_connect)
It's not in your code example, but maybe you did anyway and didn't copy it.
If you did, to which variable did you assign the connection? Once you're using $conn in mysqli_query and once youre using $server in mysqli_close.
Maybe this is helping already even I think PHP should show errors in this case?
Another Tipp
You can easily write the following:
while($datarow = mysqli_fetch_assoc($query)) {
$data[] = $datarow;
}
Like this, you can save the for-loop.

I just figured it out. I ended my Query with ;" instead of ";
Thanks for your replies! Sorry I did not catch that before posting!

Related

How to combine multiple arrays obtained from mysql queries and then traverse through the new array

So I'm trying to build an image uploading website and wish to access a mysql table using a query ..now I wish to store all the arrays obtained from these queries into one single array. I then wish to access all the elements of this array. How should I do it?
This is what I tried:
$allimages = array();
$sql="SELECT uploaderId FROM foostable WHERE foo='bar'";//a query which fetches the image uploader's id from the foostable ..you don't need to worry about this part just know that this query returns more than one uploaderIds
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result)){
$uploaderId=$row['uploaderId'];
$sql1="SELECT uploader FROM imagestable WHERE uploaderId='$uploaderId' ORDER BY datetime DESC";
$result1=mysqli_query($conn, $sql1);
$row1=mysqli_fetch_assoc($result1);
$allimages=$allimages+$row1;
}
foreach ($allimages as $ai) {
echo $ai['uploader'];
}
When I run this code, I get the following error:
Warning: Illegal string offset 'uploader' in...
I'm definitely doing something wrong but am not able to figure out what that is.
I've been looking everywhere for this but am not able to find it therefore I posted this question! I'm really new to this and any help would be really really appreciated! Thank you! :)
You're adding new elements to your array the wrong way.
Change
$allimages=$allimages+$row1;
to
$allimages[] = $row1; // Short for array_push($allimages, $row1)
Read more about array_push() in the manual
SELECT i.uploader
FROM foostable f
JOIN imagestable i
ON i.uploaderid = f.uploaderId
WHERE f.foo = 'bar'
ORDER
BY i.datetime DESC
You could write a single query to obtain the desired results. Please try the following code:
$allimages = array();
$sql = "SELECT i.uploader, i.datetime
FROM imagestable i INNER JOIN foostable f
ON i.uploaderId = f.uploaderId
AND f.foo = 'bar'
ORDER BY i.datetime DESC";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result)){
$allimages[] = $row['uploader'];
}
print_r($allimages);
You should just be able to do:
$allImages[] = $row1;
This should just push the new array to the end of allImages array everytime the loop runs.

How to fetch long text type data in Android?

I need to fetch long text type data from mysql server for Android application. It is showing NULL after encoding in JSON. Code is given below.
<?php
require_once('dbConnect.php');
$sql = "select tips from health_tips order by number";
$res = mysqli_query($con, $sql);
$result = array();
while ($row = mysqli_fetch_array($res))
{
array_push($result, array('url' => $row['tips']));
}
echo json_encode(array("result" => $result));
mysqli_close($con);
How to solve this problem?
Any help will be appreciated.
Thanks.
first try debugging ..so that u can get the idea whether they are fetching any value or showing null..do debugging ur app.or else do on those line where u think need any change

Get column information from results of mysql query in php?

I am trying to print out the column headers for any query entered. I have other code that connects to the database and actually prints the results, but I am having trouble with the line
'$result .= $heading->name;'
I keep getting this error:
'Catchable fatal error: Object of class mysqli_result could not be converted to string in...'
Could someone explain what the problem is? According to the php manual this should give me the right information. I am fairly new to php though, so if you improve the code could you please explain how you did it?
I have the following code so far that gets a result from a query:
$result = mysqli_query($conn,$query);
if($result){
if( mysqli_num_rows($result)>0){
$columnNo = mysqli_num_fields($result);
for($i=0;$i<$columnNo;$i++){
$heading = mysqli_fetch_field_direct($result,$i);
$result .= $heading->name;
}
}
}
$result is an object being used by mysqli. Then you try to append a string onto the end of it.
Just use a different variable name besides $result which will be a string in which you will collect the names of your columns. Or you might save the names in an array like this:
$var[] = $heading->name;
since $result is an object you are using for executing the query, i won't be able to store any other data coming from db. you have to take another variable (say $variable) to store the data coming from db. Follow the below code:
$result = mysqli_query($conn,$query);
$variable=''; // add this
if($result){
if( mysqli_num_rows($result)>0){
$columnNo = mysqli_num_fields($result);
for($i=0;$i<$columnNo;$i++){
$heading = mysqli_fetch_field_direct($result,$i);
$variable .= $heading->name; //modify here
}
}
}
I hope this will solve the issue..

PHP probletm with appending new property into object?

I am starting to learn php for interaction with mysql db.
I have to fetch data from two unrelated tables and form an array of stdClass objects then dump it as json array.
I have so far managed to fetch data from table1 and added some columns from it into an
myobjects[], as follows..
Here $array is an array of primary keys , also i pass a reference to myobjects array
function load_from_table1($array , &$myobjects)
{
foreach($array as $num)
{
$obj=(object)null;
$obj->prop1 = $num;
$sql="SELECT * FROM `table1` WHERE col1=".$num;
$result = mysqli_query($con, $sql);
if($result!=null)
{
$row = mysqli_fetch_assoc($result);
//inserting data into object
$obj->prop2 = $row['col2'];
$obj->prop3 = $row['col3'];
$obj->prop4 = $row['col4'];
}
$myobjects[]=$obj;
}
}
It is fine so far now i need add two more properties to all items in myobjects array obtained from table2.
function load_from_table2(&$data)
{
for($i=0;$i<sizeof($data);$i++)
{
$obj=(object)$data[$i];
$id=$obj->prop1;
$sql="SELECT * FROM `table2` WHERE col1=".$id;
$result = mysqli_query($con, $sql);
if($result!=null)
{
$row = mysqli_fetch_assoc($result);
//$temp=$row['name'];
//echo $temp;
//$obj->name = "test1";
$obj->name = $row['name'];
//$temp=$row['description'];
//echo $temp;
//$obj->description = "test2";
$obj->description = $row['description'];
}
}
When i dump myobjects as json there is no output. But $temp echos properly , also when i us direct values every thing seems to work fine.
Can some one help me with this, also an explanation on what i am doing wrong would be greatly appreciated. Thank You.
Some Details on the working Environment , Because of the answer i provided ,
I am using wampserver 2.5 64 bit , and for now executing the php file off firefox browser.
The situation is quiet confusing as i can read the value and print it or save to variable , but not save it as object property.
I got it to work, But the problem was not with the code. It seems that the column in the table that i was reading has collation set to ' utf8_general_ci ' not sure what that means. But when i removed that setting , it all worked as expected. But i feel the collation is not the actual underlying reason. So i will keep this question open in hopes some might provide an explanation.
It seems i was looking for the wrong issues. Reading up on collation i found that some character sets are not supported fully , so i tried to echo the contents of the object array instead of json_encode and found it printed.
searching to that end i found another qst here on stackoverflow that solved my problem.
Simply added this line :: mysqli_set_charset($con,'utf8'); before i started any queries on that table and json_encode started working.

Blank result for some columns when php mysql_query, works in phpmyadmin

I've run into a problem that is making me go a bit crazy. I have imported some csv data into a table in my phpadmin database and am now using a php script with mysql_query() to run a simple select query on the database and convert the result into json format - e.g. SELECT clients FROM TABLE 29.
Basically, some of the columns in the table result in a json string after passing them through mysql_query() but others simply return a blank. I have fiddled for hours now and can't figure out why this is. The last bit of my code looks like this:
$myquery = "SELECT `clients` FROM `TABLE 29`";
$query = mysql_query($myquery) or die(mysql_error());
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
Any help would be greatly appreciated. Could it be something about the data in the table? I'm at a loss.
thank you!
UPDATE: the length of the strings in the column clients seems to be having an effect. When I replace all the text with something shorter (e.g. aaa instead of something like company name 111 - 045 - project name - currency - etc) it works. However, I need it to be able to handle long strings as I want it to just take whatever users happen to import into it... what am I doing wrong?
No, its not about the table, its about how you loop them. Example:
$data = array();
while($row = mysql_fetch_assoc($query)) { // While a row of data exists, put that row in $row as an associative array
$data[] = $row;
}
echo json_encode($data);
mysql_close($server);
exit;
Note: mysql is depreacted and no longer maintained. Use the improved version of the mysql extension which is mysqli or use PDO instead.
After checking all the rows of the data I discovered that the source of the problem was a 'é' - yes, an 'e' with an accent. Once I replaced it with a regular 'e' the problem went away. So much lost time for something so tiny :(

Categories