I have a database table I have to build a UL list from
the table is setup like
cat-id
parent-id (is the cat-id of whatever the parent is)
cat-name
cat-image
I can get the root cat easily which has a parent-id of "0"
but for the life of me I can't figure out how to do it so the end result is
rootcat
--childParent
---child
function cats(){
$sql = "SELECT * FROM `cats";
$cats;
$con = mysqli_connect($this->vars["host"], $this->vars["user"], $this->vars["pass"], $this->vars["db"]);
if(mysqli_connect_errno()){
print "START MYSQLI ERROR<br/>".
mysqli_connect_error() .
"<br/>ENDMYSQLI ERROR";
}else{
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0){
while($cat = $res->fetch_array(MYSQLI_ASSOC)){
if($cat["parent-id"] == "0"){
$cats[] = $cat["cat-name"];
}
}
}
mysqli_free_result($res);
mysqli_close($con);
return $cats;
}
You can parse a sub category like this, but it does requirer to make a sql connection every time you check what categories does parent has:
function cats(){
$sql = "SELECT * FROM `cats";
$cats;
$con = mysqli_connect($this->vars["host"], $this->vars["user"], $this->vars["pass"], $this->vars["db"]);
if(mysqli_connect_errno()){
print "START MYSQLI ERROR<br/>".
mysqli_connect_error() .
"<br/>ENDMYSQLI ERROR";
}else{
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0){
while($cat = $res->fetch_array(MYSQLI_ASSOC)){
if($cat["parent-id"] == "0"){
$cats[$key] = $cat["cat-name"];
$sql_subCategory = "SELECT * FROM cats where parent_id=". $cat["id"];
$res_sub = mysqli_query($con, $sql_subCategory);
if(mysqli_num_rows($res_sub) > 0){
while($cat_sub = $res_sub->fetch_array(MYSQLI_ASSOC)){
$cats[$cat["cat-name"]] = $cat_sub["cat-name"];
}
}
}
}
}
mysqli_free_result($res_sub);
mysqli_free_result($res);
mysqli_close($con);
return $cats;
}
That should give you the array:
array(
'cat1' => 'Some Category',
'cat2' => array(
'sub1' => 'name',
),
);
This is what i ended with is totally recursive
public function cats($id){
$con = mysqli_connect($this->vars["host"], $this->vars["user"], $this->vars["pass"], $this->vars["db"]);
$cats;
if(mysqli_connect_errno()){
print "START MYSQLI ERROR<br/>".
mysqli_connect_error() .
"<br/>ENDMYSQLI ERROR";
}else{
$cats[] = $this->child($id, $con);
mysqli_close($con);
return $cats;
}
}
function child($id,$con){
$sql = "SELECT * FROM `cats` WHERE `parent-id`= '".$id."'";
// print $sql ."<br/>";
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0){
while($cat = $res->fetch_array(MYSQLI_ASSOC)){
$cats[]["cat-name"] = $cat["cat-name"];
$sql_subCat = "SELECT * FROM `cats` WHERE `parent-id` = '".$cat["cat-id"]."'";
$res_sub = mysqli_query($con, $sql_subCat);
if(mysqli_num_rows($res_sub) > 0){
while($cat_sub = $res_sub->fetch_array(MYSQLI_ASSOC)){
$cats[$cat["cat-name"]][] = $cat_sub["cat-name"] ;
$cats[$cat["cat-name"]]= $this->child($cat["cat-id"],$con);
}
}
}
}
mysqli_free_result($res_sub);
mysqli_free_result($res);
return $cats;
}
Related
how would i get this to display a message in place of the Query if no result is found i updated the code but its just showing "N"
<?php
$hostname = "...";
$username = "";
$password = "";
$db = "";
$dbconnect=mysqli_connect($hostname,$username,$password,$db);
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$query=mysqli_query($dbconnect,"SELECT DISTINCT companyname,client_id,feedback,status from review WHERE status=1 ORDER BY RAND() LIMIT 4");
$rows_get = mysqli_num_rows($query);
if ($rows_get >0)
{
$query2=mysqli_query($dbconnect,"SELECT DISTINCT companyname,client_id,feedback,status from review WHERE status=1 ORDER BY RAND() LIMIT 4");
$row1 = mysqli_fetch_assoc($query2);
$row2 = mysqli_fetch_assoc($query2);
$row3 = mysqli_fetch_assoc($query2);
$row4 = mysqli_fetch_assoc($query2);
$row5 = mysqli_fetch_assoc($query2);
}else {
$row1 = "N0 Data";
$row2 = "N0 Data";
$row3 = "N0 Data";
$row4 = "N0 Data";
$row5 = "N0 Data";
}
?>
Do as follows:
After $query insert this:
$rows_get = mysqli_num_rows($query);
if ($rows_get >0)
{
//do all database operation
}else {
echo " No data found";
}
Hope this helps.
Amend your code for example..
if ($row_get>0){
//i assume you are getting multiple rows
while ($data =mysqli_fetch_assoc ($query))
{
//run this loop and you will get all you rows.
}
}
I'm a learner of PHP. This commit and rollback process does the task at each line. How can I commit and rollback all at once?
<?php
$con = mysql_connect('localhost','user', 'abcdefg');
if(!con)
{
echo "Can't connect to db.";
}else {
mysql_select_db('test');
}
if(!file_exits('test.csv')
{
echo "Can't find the file.";
}
$ar_1 = file('test.csv', FILE_IGNORE_NEW_LINES);
foreach ($ar_1 as $ar1)
{
$test = explode(",", $ar1);
$sql = "SELECT * FROM DB WHERE CD = '$test[0]'";
$result = mysql_query_($sql);
$sql = "INSERT INTO DB(CODE) VALUES ('$test[0]');";
$result = mysql_query($sql);
if($result === true)
{
//Commit
$sql = "commit";
mysql_query($sql);
echo "Committed";
}else {
//Rollback
$sql = "rollback";
mysql_query($sql);
echo "Rollback";
}
}
mysql_close($con);
?>
you need to commit out of the loop, i used $bool to see if there somewhere the $result isn't true
it will look something like :
edit:
breaking from the loop when something is wrong as you don't need to continue looping to other elements.
$bool = 1;
foreach ($ar_1 as $ar1)
{
$test = explode(",", $ar1);
$sql = "SELECT * FROM DB WHERE CD = '$test[0]'";
$result = mysql_query_($sql);
$sql = "INSERT INTO DB(CODE) VALUES ('$test[0]');";
$result = mysql_query($sql);
if($result === false)
{
//Rollback
$bool = 0;
$sql = "rollback";
mysql_query($sql);
echo "Rollback";
break;
}
}
if($bool == 1)
{
//Commit
$sql = "commit";
mysql_query($sql);
echo "Committed";
}
mysql_close($con);
<?php
$link = mysql_connect("localhost:8889", "root", "root", "Testdata");
if(!link) {echo "Database connexion not possible"; exit;}
$id = $_GET('testeId');
$jsonData = [];
The first query is working:
$jsonData['table1'] = [];
$sql = "SELECT * FROM registerData WHERE testeId = $id";
if ($result = mysqli_query($link, $sql){
while ($row = mysqli_fetch_assoc($result)) {
$jsonData['table1'][] = $row;
}
}
else {
$jsonData['table1'][] = "Error 1";
}
This second query is not working:
$jsonData['table2'] = [];
$sql = "SELECT * FROM factsData WHERE factsId = $id";
if ($result = mysqli_query($link, $sql){
while ($row = mysqli_fetch_assoc($result)) {
$jsonData['table2'][] = $row;
}
}
else {
$jsonData['table2'][] = "Error 2";
}
mysqli_free_result($result);
echo json_encode($jsonData);
The jsonData string only includes the 1st query:
mysqli_close($link);
The responseText of the ajax request only has data from "table1" array
I have a problem switching from MYSQL to MYSQLi. The codes work fine with MYSQL but when i change the connection to MYSQLi, I received the error as stated above when I'm fetching my query. How can i fetch my queries using mysqli functions?
Code:
function __construct(){
$this->link = mysqli_connect('localhost', 'root', '', 'ajax_rating');
if (!$this->link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($this->link) . "\n";
}
function getItems($id = null){
if(isset($_GET['id']))
{
$query = $this->link->query("SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = $this->link->query("SELECT * FROM items");
}
$rowCount = $query->rowCount();
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
Use num_rows
Read MySQLi row_count
So final answer would be
function getItems($id = null)
{
if(isset($_GET['id']))
{
$query = $this->link->query("SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = $this->link->query("SELECT * FROM items");
}
$rowCount = $query->num_rows;//change here
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
}
EDIT 01
use mysqli_fetch_all instead of fetchAll()
mysqli_fetch_all($query,MYSQLI_ASSOC);
so answer world be
if($rowCount >= 1)
{
$result = mysqli_fetch_all($query,MYSQLI_ASSOC);
}
you can use num_rows for counting rows in DB and you can direct call connection like this :-
//for connection
$con = mysqli_connect("localhost", "root", "", "ajax_rating");
if(!$con)
{
echo "connection error";
}
//query
function getItems($id = null)
{
if(isset($_GET['id']))
{
$query = mysqli_query($con,"SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = mysqli_query($con,"SELECT * FROM items");
}
if (mysqli_num_rows($query) > 0)//change here
{
while($row = mysqli_fetch_assoc($query))
{
$result=$row;
}
}
else
{
$result = 0;
}
return $result;
}
I'm trying to run a MYSQL query that will return all services with an id above a particular value. The query works fine when I use a static value as the comparative to 'id' such as:
$query = "SELECT id, name FROM services WHERE id > '14'";
if ($query_run = mysqli_query($link, $query)) {
while ($results = mysqli_fetch_array($query_run)) {
echo $service_id = $results['id'].'<br>';
echo $service_name = $results['name'].'<br>';
}
} else {
echo mysqli_error($link);
}
However if i use a variable like this:
$query = "SELECT id, name FROM services WHERE id > $service_id";
if ($query_run = mysqli_query($link, $query)) {
while ($results = mysqli_fetch_array($query_run)) {
echo $service_id = $results['id'].'<br>';
echo $service_name = $results['name'].'<br>';
}
} else {
echo mysqli_error($link);
}
the query does not return any values
When you hard coded the value you put quotes around it.
Make sure that $service_id is represented as a string.
Try
$query = "SELECT id, name FROM services WHERE id > '$service_id'";
if ($query_run = mysqli_query($link, $query)) {
while ($results = mysqli_fetch_array($query_run)) {
echo $service_id = $results['id'].'<br>';
echo $service_name = $results['name'].'<br>';
}
} else {
echo mysqli_error($link);
}
$query = "SELECT id, name FROM services WHERE id > '".$service_id."'";