How to make side - category system - php

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.

Related

Wpforms dropdown menu populate with SQL

I am creating form in Wpforms. I am adding code to make dropdown menu populated with data from database.
I have code next:
function wpforms_sql_list(){
$hostname = "localhost";
$username = "username";
$password = "password";
$dbName = "DB name";
$connect = mysqli_connect($hostname, $username, $password, $dbName);
$query = "SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'DB name'";
$result = mysqli_query($connect, $query);
$sqlitem = array();
while($row1 = mysqli_fetch_array($result)){
array_push( $sqlitem, $row1);
}
foreach($sqlitem as $raw1){
return apply_filters( 'wpforms_sql_list', $raw1);
}
}
Now I have problems because if I run in wordpress I get only dubled first database table in dropdown menu.
If I make:
return apply_filters( 'wpforms_sql_list', $sqlitem);
I get correct number of table but instead of names is written array.
Picture of result
Can anybody help me?
Thank you in advance.
Please Follow the wordpress structure to retrieve data from wordpress database like below way :
1) wordpress table see(https://prnt.sc/q71e1q)
2) Fetch data from wordpress table
global $wpdb;
$data = $wpdb->get_results("SELECT * FROM `table_name`");
echo "<select>";
foreach($data as $damenu){
echo "<option>".$damenu->name."</option>";
}
echo "</select>";
3) Output :

JSON from mysql not display properly through PHP

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'

Create nested JSON objects using PHP

I have the following MySQL table:
id desc qty
--------------------
10 abc 5
20 xyz 12
30 qwe 9
How can I use PHP/MySQL query to create the following JSON file?
{
"10":{"desc":"abc","qty":"5"},
"20":{"desc":"xyz","qty":"12"},
"30":{"desc":"qwe","qty":"9"}
}
Here is my attempt
$query="SELECT id,desc,qty FROM table";
$result = #mysql_query($query);
while ($row=mysql_fetch_object($result))
{
$data[]=$row;
}
echo json_encode($data);
The result is an array and I am not sure how to display it correctly
[
{"id":"10","desc":"abc","qty":"5"},
{"id":"20","desc":"xyz","qty":"15"},
{"id":"30","desc":"qwe","qty":"9"}
]
Any help is appreciated
There are many ways to achieve this.One of them is below. changes your database credentials and table name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM TableName";
$result = $conn->query($sql);
$results_array =array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results_array[$row['id']] = array(
'desc'=>$row['desc'],
'qty'=>$row['qty'],
);
}
} else {
echo "0 results";
}
$json_array = json_encode($results_array);
echo $json_array;
Results should be look alike
{
"1":{"desc":"abc","qty":"12"},
"2":{"desc":"xyz","qty":"54"}
}
Thanks for editing your question. You can change the structure of your results with another loop:
foreach($data as $d)
$r[$d->id] = ['desc' => $d->desc, 'qty' => $d->qty];
$data = $r;
right above:
echo json_encode($data);
or you could adjust your while loop to get the same result:
$data[$row->id] = ['desc' => $row->desc, 'qty' => $row->qty];
or you could use array column (again right above json_encode):
$data = array_column($data, null, 'id');
The last example produces a slightly different output, but you can still use it in many situations. If you can't the first two options are preferable.

How to get only last iteration value while fetching data from the database,I've tried Getting values as JSON format

Here's what i tried.
I've Tried fetch the data from DB.It shows data from the start of the iteration to the End of iteration.I need only last iteration value.I'm a complete noob. A help would be appreciated
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
$conn = new mysqli($servername, $username, $password, $dbname);
$myarray=array();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myarray[]= $row;
// echo "<pre>";
// print_r($myarray);
echo "<pre>";echo json_encode($myarray);
// echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Description :" . $row["description"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Change your SQL query to
SELECT id, name, description FROM products order by id desc limit 1
That will work for you.
Finally, I got your point that what you want-
You need to get all record in one variable.Which you can encode at last
For that do like below:-
1.Initialize array outside of the loop
2.Assign each record to the array inside the loop
3.Encode array outside the loop
Do like below:-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
$conn = new mysqli($servername, $username, $password, $dbname);
$myarray=array();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM products";
$result = $conn->query($sql);
$myarray = []; //Initialize array outside of the loop
if ($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myarray[] = $row; //Assign each record to the array inside the loop
}
} else {
echo "0 results";
}
$conn->close();
echo json_encode($myarray);//Encode array outside the loop
?>
While it looks like a duplicate to me, I would suggest the following, assuming that you are not intending to sort the dataset from the DBMS.
Use mysqli_data_seek ( mysqli_result $result , int $offset ) to move cursor that traverses the dataset. So for your case it would be
$nor = mysqli_num_rows($result); //Number of rows
mysqli_data_seek($resutl, ($nor - 1)); //Indices are based on 0
Basically $nor contains the total number of records. So the index of the last ever record would be $nor-1.
Of course if you are sorting the dataset in your query using ORDER BY, then the best way to do this is appending ORDER BY id DESC LIMIT 1.

Iterate through fetched SQL data

I am adding a database to my event website with the webpages mon-sun each with its own SQL table. Each page can have any number of events. The table has 6 columns (ID,name,club,location,host,description). Currently I am using a tiresome method to call the data. I'm looking for an addition to my code so that calling the data is a bit more automated. My code so far.
<?php
$dbhost = 'localhost';
$dbname = 'events';
$dbuser = 'max';
$dbpass = '';
$appname = "Dundaah";
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);
function queryMysql($query)
{
global $connection;
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
}
$row = queryMysql("SELECT * FROM monday WHERE ID=1");
$one = $row->fetch_array(MYSQLI_ASSOC);
$row2 = queryMysql("SELECT * FROM monday WHERE ID=2");
$two = $row2->fetch_array(MYSQLI_ASSOC);
?>
Then to call for the first event I use.
<?php echo ucwords(strtolower($one['name']));?>
<?php echo ucwords(strtolower($one['club']));?>
<?php echo ucwords(strtolower($one['location']));?>
<?php echo ucwords(strtolower($one['host']));?>
<?php echo ucwords(strtolower($one['description']));?>
For the second event I use the same method but I'm looking for a way to loop through instead of declaring a new fetch array every time. Thank you.
Something along these lines may help.
First you create an array that contains the days of the week, then you loop through the array in a foreach and perform a query on the database for each day. In this example I'm storing the results for each day in a single array with the Day name as the key (untested but hopefully it'll help).
$dbhost = 'localhost';
$dbname = 'events';
$dbuser = 'max';
$dbpass = '';
$appname = "Dundaah";
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);
$daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
$resultsFromDB = [];
foreach ($daysOfTheWeek as $day) {
$query = "SELECT * FROM events WHERE day = '$day'";
$result = $connection->query($query);
$resultsFromDB[$day] = $result->fetch_all(MYSQLI_ASSOC);
}
// Display the results in a page
echo "<h1>Events</h1>";
foreach ($daysOfTheWeek as $day) {
echo "<h2>$day</h2>";
foreach ($resultsFromDB[$day] as $event) {
echo $event['name'];
}
}
You can use IN sql statement get rows with several different ids.
$row = queryMysql("SELECT * FROM monday WHERE ID IN (1, 2) ORDER BY ID ASC");
$one = $row->fetch_assoc(); // same as fetch_array( MYSQLI_ASSOC )
$two = $row2->fetch_assoc();
ORDER BY ID ASC required if you want to get first row as row with id=1 (least ID), without it mysql (as well as any other db) doesn't guarantee any order.
If you need (for example) all rows with id less then 1000. You can use "less or equeal" comparison and save all rows into array.
$result = queryMysql("SELECT * FROM monday WHERE ID<=1000 ORDER BY ID ASC");
$all_rows = $result->fetch_all( MYSQLI_ASSOC );
// then
//$one = $all_rows[0];
//$two = $all_rows[1];
Also you don't need to materialize all results immediatly. Mysqli_result is traversable object. You can write foreach( $result as $row ) and get all rows any time. During foreach all raws will be fetched as assoc array.
Got it.
$query = "SELECT * FROM events WHERE day='mon'";
$result = $conn->query($query);
if (!$result) die($conn->error);
$rows = $result->num_rows;
$j = 0;
$name_array='';
$club_array='';
$location_array='';
$host_array='';
$description_array='';
while ($j < $rows )
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_ASSOC);
$event_name = $row['name'];
$event_club = $row['club'];
$event_location = $row['location'];
$event_host = $row['host'];
$event_description = $row['description'];
$name_array[]=$event_name;
$club_array[]=$event_club;
$location_array[]=$event_location;
$host_array[]=$event_host;
$description_array[]=$event_description;
++$j;
}
echo $name_array[0];
echo $club_array[0];
echo $location_array[0];
echo $host_array[0];
echo $description_array[0];

Categories