This is my database of mysql on the web
This is my database on the web
This is the PHP file to access the database to get a JSON file, first I select all the "category" cell in the table, then loop through the category, and then loop through the other columns of a category, and assign to an array of $data2, after that assign $data2 and category to br an array of $data, which is the json I want to display.
<?php
header("Access-Control-Allow-Origin: *");
$user = "u348833238_rest"; /* User */
$password = "a!23286029"; /* Password */
$dbname = "u348833238_rest"; /* Database name */
$host = "localhost";
$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
// $sel = mysqli_query($con,"select * from restaurant");
// $data = array();
// while ($row = mysqli_fetch_array($sel)) {
// $data[] = array("dishes" => ["name"=>$row['food'], "price"=>$row['price']] , "category"=>$row['category']);
// }
// echo json_encode($data);
$sel = mysqli_query($con,"select distinct category from restaurant");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$c = $row['category'];
$sel2 = mysqli_query($con,"select * from restaurant where category = $c ");
$data2 = array();
while ($row2 = mysqli_fetch_array($sel2)){
$data2[] = array("name"=>$row2['food'], "price"=>$row2['price']);
}
// echo $data2;
$data[] = array("category"=>$row['category'], "dishes"=>$data2);
}
// echo $data;
echo json_encode($data);
?>
How the JSON is not displayed properly as the array of property "dishes" is empty as below:
the array is empty
I’d recommend turning errors on so you can see where the problem is.
At a guess it’s here:
select * from restaurant where category = $c
Should be:
select * from restaurant where category = '$c'
Related
Soo, I need to make a side category system but I am litlle bit confused about it. Can someone help me out ?
Here is my PHP
<?php
// Conncetion to database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "shop";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// SQL Query
$sql = "SELECT category_id, category_name, category_link, parent_id, sort_order FROM category2 ORDER BY parent_id, sort_order, category_name";
$result = mysqli_query($conn, $sql);
//Create a multidimensional array to hold a list of category and parent category
$category = array(
'categories' => array(),
'parent_cats' => array()
);
//Build the array lists with data from the category table
while ($row = mysqli_fetch_assoc($result)) {
//creates entry into categories array with current category id ie. $categories['categories'][1]
$category['categories'][$row['category_id']] = $row;
//creates entry into parent_cats array. parent_cats array contains a list of all categories with children
$category['parent_cats'][$row['parent_id']][] = $row['category_id'];
}
function buildCategory($parent, $category) {
//Code HERE...
}
echo buildCategory(0, $category);
Soo, when you are on homepage then I just need every parent elements with "category_id = 0", then if someone click any parent category should shows up his children, but these childrens has another childrens and etc. etc. but it needs to show always parent elements with "category_id = 0".
I found live example here: https://papiernictvotriomat.sk
Also posting here image of my database:
You can change your database a little and add a field with all the way up to the root category separated by comma, but this is not a "good option" in the relational world.
The simples way is just get all categories you have - like you're doing - and create the hierarchy with a recursive function:
<?php
$conn = mysqli_connect('localhost', 'root', 'l2mago666', 'stack');
# This ensure the root one come first
$res = mysqli_query($conn, 'SELECT * FROM categories ORDER BY parent');
$categories = [];
while($rs = mysqli_fetch_assoc($res)) {
if (!$rs['parent'])
$categories[$rs['id']] = $rs;
else
$rows[] = $rs;
}
function lookup(&$set, $r) {
foreach($set as &$s) {
if ($s['id'] == $r['parent']) {
if(!isset($s['childs']))
$s['childs'] = [];
$s['childs'][$r['id']] = $r;
} else {
if(isset($s['childs']))
lookup($s['childs'], $r);
}
}
}
foreach($rows as $r)
lookup($categories, $r);
print_r($categories);
This should help you create the HTML, of course, with another recursive function.
I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
I have the following already working great, but would like to add a parameter as this returns the whole data set.
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "00000";
$mysql_db_password = "00000";
$mysql_db_database = "000000";
$con = #mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,
$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM mns";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"mns":'.json_encode($var).'}';
?>
For clarification, I was hoping to add a parameter in the url that is passed through to the php so that I get specific records. For example, if there is a field called [Customer], I would like to pass a customer id to it.
I am new to PHP.
I followed this to Display JSON data from Mysql Tables
Here I am getting one table as output at a time..
So,in this I want to display tables from user input.
like
www.google.com/myjson.php?/tablename
www.google.com/myjson.php?=tablename
Here is the code
<?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);
?>
Here its for the part of Table name of employee
so this should be like
www.google.com/myjson.php?/employee
please suggest me of this kind,because I have n number of tables to Display and I want to use them in the Android/iphone.
<?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);
$tableNm = isset($_GET['tablename']) ? trim($_GET['tablename']) : '';
if($tableNm){
//Replace * in the query with the column names.
$result = mysql_query("select * from $tableNm", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($row as $key=>$val){
$row_array[$key] = $val;
}
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
}
//Close the database connection
mysql_close($db);
Assumes you have input url's in the below formats.
$url ="www.google.com/myjson.php?/tablename";
//or
$url ="www.google.com/myjson.php?=tablename";
You can parse it using parse_url and str_replace to retrieve the table name.
Then assign tablename into query and make it run.
$url = parse_url($url);
if ($url['query'] <> '') {
$table = str_replace(array("/","="),'',$url['query']);
}
//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 $table", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($row as $key=>$val){
$row_array[$key] = $val;
}
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
mysql_close($db);
P.S. Usage of mysql_* functions is not recommended.
Instead you can use mysqli* or pdo* functions.
I edit my code working good but still one problem ... the data that selected from my database and displayed in my suggestion input ( only one row and last ID ) !!! How can I do it to display all data rows from my database ????
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$host = "localhost";
$user = "root";
$password = "";
$database = "private_message_system";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)){
$items = array($row["user_name"] => $row["user_email"]);
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key,
"to" => $value
));
}
}
echo json_encode($result);
?>
As I know mysql doesn't have a array type like postgres so you have to fetch it one by one:
// here is where you get your to connection to the database
$conn = mysql_connect("your IP", "username", "password");
mysql_select_db("mydb", $conn);
// here you have to do the select to retrieve data from the table.
$query = "SELECT `name`, `to` from mytable";
// now you got all the records but you still need to iterate over this result
$result = mysql_query($query, $conn);
$array = array();
// retrieve a record and append it to the array
while($record = mysql_fetch_assoc($result)):
$array[] = $record;
endwhile;
// please close the door....
mysql_close($conn);
echo json_encode($array);
See below for a basic implementation of connecting to MySQL and searching for your $q, I've left a few comments for you to make it clearer what's going on!
<?php
// Get the query term from the url
$q = strtolower($_GET["q"]);
// Do nothing if it's empty or not set
if (empty($q)) return;
// Result array which we are going to get from MySQL
$result= array();
// Make a SQL Connection
mysql_connect("localhost", "admin", "password") or die(mysql_error());
// Try to connect to your DATABASE (change the name) or throw an error
mysql_select_db("DATABASE") or die(mysql_error());
// Get data from the "email" table
// Where the name field is LIKE the search term
$result = mysql_query("SELECT * FROM email WHERE name LIKE '%".mysqli_real_escape_string($q)."%'")
or die(mysql_error()); //throw an error if something went wrong
//Read all the results ($row) in a loop and put them in the result array
while($row = mysql_fetch_array( $result )) {
$result[] = array('name' => $row['name'], 'to' => $row['to']);
}
// Output the array as JSON
echo json_encode($result);
?>
For the more PHP experienced I am aware you can get an array from MySQL but have left it like this to make it clearer.
Enable error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);