Getting NULL in JSON - php

I'm following this website to create mySQL table and php in order to convert data to JSON
SQL:
CREATE TABLE IF NOT EXISTS `employee` (
`id_employee` int(3) unsigned NOT NULL AUTO_INCREMENT,
`emp_name` varchar(10) DEFAULT NULL,
`designation` varchar(9) DEFAULT NULL,
`date_joined` date DEFAULT NULL,
`salary` decimal(7,2) DEFAULT NULL,
`id_dept` int(2) DEFAULT NULL,
PRIMARY KEY (`id_employee`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
INSERT INTO `employee` (`id_employee`, `emp_name`, `designation`, `date_joined`, `salary`, `id_dept`) VALUES
(1, 'SMITH', 'CLERK', '2010-12-17', 2500.00, 20),
(2, 'ALLEN', 'SALESMAN', '2005-02-20', 3500.00, 30),
(3, 'WARD', 'SALESMAN', '2009-02-22', 3550.00, 30),
(4, 'JONES', 'MANAGER', '2010-04-02', 3975.00, 20),
(5, 'MARTIN', 'SALESMAN', '2011-09-28', 3300.00, 30);
PHP:
<?php
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from employee", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id_employee'] = $row['id_employee'];
$row_array['emp_name'] = $row['emp_name'];
$row_array['designation'] = $row['designation'];
$row_array['date_joined'] = $row['date_joined'];
$row_array['salary'] = $row['salary'];
$row_array['id_dept'] = $row['id_dept'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
However, i get 2 results with null and no other errors:
[{"id_employee":null,"emp_name":null,"designation":null,"date_joined":null,"salary":null,"id_dept":null},{"id_employee":null,"emp_name":null,"designation":null,"date_joined":null,"salary":null,"id_dept":null}]
I just copied the code and try to run it, how come there is no return in the result??
Can someone points out what's wrong with my code??
Or it is my server problem??
PHP version:5.2
MySQL ver. :5.1
Thank you

Please have a look at mysql_set_charset(). As about JSON itself, last error can be fetched with json_last_error().

You should replace mysql_fetch_array to mysql_fetch_assoc so you can access the variable by column name.
Also, you should start using mysqli instead of mysql, to connect and interact wth mysql database from php.

Related

Which of these 2 PHP & MySQL methods for displaying credits from a table is more logical to use?

I'm working on a site that uses PHP & MySQL to display credits. I've made 2 versions of the same thing and I'm having a hard time deciding which of them is the best one to use. One uses 2 tables, the other uses just 1. I have things set up where it lists the name of the position and then places the people below it. I can't decide if it's easier to look at the credits_position table and then grab what is needed from credits_people or if I should use just the credits_people to hold everything. Which version would be easier to keep updated?
SQL
CREATE TABLE `credits__topic` (
`topic_id` INT(11) NOT NULL AUTO_INCREMENT,
`category_id` INT(11) DEFAULT NULL,
`name` VARCHAR(48) DEFAULT NULL,
`category` VARCHAR(48) DEFAULT NULL COMMENT 'Job name',
PRIMARY KEY (`topic_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 26;
CREATE TABLE `credits__category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(48) DEFAULT NULL COMMENT 'Job name',
PRIMARY KEY (`category_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 6;
INSERT INTO `credits_people` (`topic_id`, `category_id`, `name`, `category`)
VALUES
(1, 1, 'Matthew Campbell', 'Creator'),
(2, 2, 'Godzilla', 'Assistant'),
(3, 1, 'Billy Bob', 'Creator'),
(4, 4, 'Martha Stewart', 'Tester'),
(5, 2, 'Mothra', 'Designer'),
(6, 2, 'Rodan', 'Contributing'),
(7, 2, 'King Ghidorah', 'Designer'),
(8, 3, 'Mechagodzilla', 'Assistant');
INSERT INTO `credits_position` (`category_id`, `name`)
VALUES
(1, 'Creator'),
(2, 'Designer'),
(3, 'Assistant'),
(4, 'Tester'),
(5, 'Contributing');
PHP
<?php
$connection = mysqli_connect ("localhost", "root", "root", "main");
// Version 1:
$data = mysqli_query ($connection, "SELECT `mc`.`name` AS 'category_name', `mt`.`name` AS 'topic_name', `mt`.`category` AS 'topic_category' FROM `credits_position` AS `mc` INNER JOIN `credits_people` AS `mt` USING (`category_id`);");
// Version 2:
$data = mysqli_query ($connection, "SELECT `name` AS 'category_name', `category` AS 'topic_category' FROM `credits_people`;");
// Works with both versions
$responses = array ();
while ($row = mysqli_fetch_array ($data)) {
array_push ($responses, $row);
}
// This loads the 1st category name.
$category = $responses [0] ["category_name"];
echo "<p>" . $category . "</p>\n";
echo "<ol>\n";
foreach ($responses as $response) {
// This loads when it finds that the category is different from the previous loop.
if ($category !== $response ["category_name"]) {
$category = $response ["category_name"];
echo "</ol>\n";
echo "<p>" . $response ["category_name"] . "</p>\n";
echo "<ol>\n";
}
echo "<li>" . $response ["topic_name"] . "</li>\n";
}
echo "</ol>";
mysqli_close ($connection);
?>
On big databases you want to save space, to have it for the relevant data.
So a normalized Tables, where you only have category_id(and of course many more such tables) you save a lot of space.
But i doubt that you will have millions of categories so you should start small and if the need arises you can increase it.

Android listview image and text from mysql using php

I'm trying to fetch images and text from mysql using php with this example
example.
The result from php code is empty, where is the error in this php code?
I store my images in server folder and add links in the database.
<?php
require_once('dbConnect.php');
$sql = "SELECT * FROM androidosnames";
$r = mysqli_query($con,$sql);
$result = array();
while($res = mysqli_fetch_array($r)) {
array_push($result,array(
"AndroidNames"=>$res['AndroidNames'],
"ImagePath"=>$res['ImagePath']
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
using your code and this dbConnect.php
<?php
$con = new mysqli('localhost', 'broadcasting', 'broadcasting', 'broadcasting', 3306);
and this database information
CREATE TABLE IF NOT EXISTS `androidosnames` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`AndroidNames` varchar(50) NOT NULL,
`ImagePath` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
INSERT INTO `androidosnames` (`id`, `AndroidNames`, `ImagePath`) VALUES
(1, 'myname', '/ports/links');
yields following result when executing on command line (php -f test.php)
{"result":[{"AndroidNames":"myname","ImagePath":"\/ports\/links"}]}
So everything works as intended. It looks to me like the information from the database cannot be retrieved in your environment.

Json encode return nothing for certain column

I have 1700 rows in my table. Problem is I can't get the json output if i try to use des column, no output is showing in the browser. If i try to get other columns except des, output is showing. Then i tried with limit key word and i limited to 1240 , then gave me an output even with the des column. But I need all the records with des column. I have put my php scripts in XAMPP server.
This is my php.
<?php
require_once 'include/Configg_t.php';
//header('Content-Type: application/json');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
mysql_select_db(DB_DATABASE,$con) or die("db selection failed");
$r=mysql_query("SELECT * from tbl_mas_material LIMIT 1240");
$result = array();
while($row=mysql_fetch_array($r)){
array_push($result,
array('des'=>$row[1]));}
echo json_encode(array("feed" => $result));
json_last_error();
mysql_close($con);
?>
problem is occur with the des column in the table.
this is my table structure
CREATE TABLE `tbl_mas_material` (
`material` varchar(18) NOT NULL,
`des` varchar(45) DEFAULT NULL,
`code` varchar(45) NOT NULL,
`matgrp` varchar(9) DEFAULT NULL,
`type` varchar(4) DEFAULT NULL,
PRIMARY KEY (`material`,`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
If I add des to my query no output is showing.
array_push($result, array('des'=>$row[1]));}
Can you please check, des value refers to the $row[1]?
Try changing it to
array_push($result, array('des' => $row['des']));

MySQL Select statement not outputting anything

my SQL statement is not outputting anything when run. Just an empty screen.
Here is my PHP code:
<?php
$con = mysqli_connect("localhost", "root", "root","payBills");
$paidBills = "SELECT * FROM houseBills WHERE houseID = '20'";
$resultset = mysqli_query($con, $paidBills);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysqli_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
?>
and here is my SQL tables
CREATE TABLE `houseBills` (
`houseBillID` int(11) NOT NULL AUTO_INCREMENT,
`houseID` varchar(11) NOT NULL,
`name` varchar(50) NOT NULL,
`amount` varchar(10) NOT NULL,
`date` varchar(50) NOT NULL,
`addedBy` varchar(100) NOT NULL,
PRIMARY KEY (`houseBillID`),
UNIQUE KEY `houseBillID` (`houseBillID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `houseBills`
--
INSERT INTO `houseBills` (`houseBillID`, `houseID`, `name`, `amount`, `date`, `addedBy`) VALUES
(1, '20', 'Loo roll', '£10', '10', 'samstone920#googlemail.com'),
(2, '20', 'toothpaste', '3', 'egreg', '44tq');
Is there any plainly obvious that I am missing?
Table is currently set as CHARSET=latin1 JSON_ENCODE doesn't except this. See this post: json_encode is returning NULL?. ALTER TABLE houseBills CONVERT TO CHARACTER SET utf8;
Because the table already contains data before the alteration this stills give a problem. In this case (test phase project) the solution is to re-enter data. For large existing table perhaps try copying data to new table might offer a solution. Please note this is untested.

Get data from a table with my foreign key?

Currently I want to get data from another table with my foreign key.
I have already setup my foreign key.
I have tables setup like this:
CREATE TABLE IF NOT EXISTS `album` (
`album_ID` int(11) NOT NULL AUTO_INCREMENT,
`album_navn` varchar(150) NOT NULL,
PRIMARY KEY (`album_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
--
INSERT INTO `album` (`album_ID`, `album_navn`) VALUES
(1, 'Nytår'),
(2, 'Berlin'),
(3, 'Færøerne'),
(5, 'TEST');
CREATE TABLE IF NOT EXISTS `billeder` (
`billeder_ID` int(11) NOT NULL AUTO_INCREMENT,
`billeder_navn` varchar(150) NOT NULL,
`billeder_fotograf` varchar(150) NOT NULL,
`billeder_sti` varchar(150) NOT NULL,
`fk_album_ID` int(11) NOT NULL,
PRIMARY KEY (`billeder_ID`),
KEY `fk_album_ID` (`fk_album_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=54 ;
--
--
INSERT INTO `billeder` (`billeder_ID`, `billeder_navn`, `billeder_fotograf`, `billeder_sti`, `fk_album_ID`) VALUES
(24, 'Vi tester4', 'Nytår', 'full_nytaar.jpg', 1),
(25, '', 'Nytår', 'full_nytaar2.jpg', 1),
(26, '', 'Nytår', 'full_nytaar4.jpg', 1),
Where I want to get ALBUM_NAVN via my fk_album_ID
so it will be possible to get it like this:
$row[album_navn]
I have tried to do it, but im lost.
Thanks in advance.
Regards, Kristian
Please try this query
SELECT * FROM billeder LEFT JOIN album ON billeder.fk_album_ID = album.album_ID
Try:
select * from billeder left join album where billeder.fk_album_ID=album.album_ID
This query will bring the desired result.
SELECT b . * , a.album_navn FROM `billeder` b, album a WHERE b.fk_album_ID = a.album_ID
Please try this php code as well. This is working and tested. You need to use join in query.
// CONNECT TO THE DATABASE
$DB_NAME = 'test';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//query
$query = " SELECT b . * , a.album_navn FROM `billeder` b, album a
WHERE b.fk_album_ID = a.album_ID";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
// show data
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo ($row['album_navn']);
}
}
else {
echo 'No record found';
}
//close conn
mysqli_close($mysqli);

Categories