I want to invert the order of these elements when they are exhibited on my menu:
function buscarSubCateg($categ_id) {
global $con;
$buscar_subcateg = "SELECT * FROM subcateg WHERE categ_id = '$categ_id'";
$run_subcateg = mysqli_query($con, $buscar_subcateg);
$i=0;
while ($row_subcateg = mysqli_fetch_array($run_subcateg)) {
$subcateg_id = $row_subcateg['subcateg_id'];
$subcateg_name = $row_subcateg['subcateg_name'];
echo '<div class="sectionSub"><a class="linkSubCatergoria" href="#">'.$subcateg_name.'</a></div>'.buscarTipos($subcateg_id);
$i++;
}
}
function buscarTipos($subcateg_id) {
global $con;
$buscar_tipo = "SELECT * FROM tipoprod WHERE subcateg_id = '$subcateg_id'";
$run_tipo = mysqli_query($con, $buscar_tipo);
while ($row_tipo = mysqli_fetch_array($run_tipo)) {
$tipo_id = $row_tipo['tipoprod_id'];
$tipo_name = $row_tipo['tipoprod_name'];
echo "<div class='sectionTipo'><a class='linkTipo' href='#'>$tipo_name</a></div>";
}
}
In this echo:
echo '<div class="sectionSub"><a class="linkSubCatergoria" href="#">'.$subcateg_name.'</a></div>'.buscarTipos($subcateg_id);`
I want that the function buscarTipos()'s result be shown after $subcateg_name. The way it is now is doing the opposite, first showing buscarTipos()'s result and after shwoing $subcateg_name.
Thanks.
Replace your current code with the following:
function buscarSubCateg($categ_id) {
global $con;
$buscar_subcateg = "SELECT * FROM subcateg WHERE categ_id = '$categ_id'";
$run_subcateg = mysqli_query($con, $buscar_subcateg);
$i=0;
while ($row_subcateg = mysqli_fetch_array($run_subcateg)) {
$subcateg_id = $row_subcateg['subcateg_id'];
$subcateg_name = $row_subcateg['subcateg_name'];
$tip = buscarTipos($subcateg_id);
echo $tip;
echo '<div class="sectionSub"><a class="linkSubCatergoria" href="#">'.$subcateg_name.'</a></div>';
$i++;
}
}
function buscarTipos($subcateg_id) {
global $con;
$buscar_tipo = "SELECT * FROM tipoprod WHERE subcateg_id = '$subcateg_id'";
$run_tipo = mysqli_query($con, $buscar_tipo);
$str = '';
while ($row_tipo = mysqli_fetch_array($run_tipo)) {
$tipo_id = $row_tipo['tipoprod_id'];
$tipo_name = $row_tipo['tipoprod_name'];
$str = $str."<div class='sectionTipo'><a class='linkTipo' href='#'>$tipo_name</a></div>";
}
return $str;
}
Try changing line #34
echo "<div class='sectionTipo'><a class='linkTipo' href='#'>$tipo_name</a></div>";
into
return "<div class='sectionTipo'><a class='linkTipo' href='#'>$tipo_name</a></div>";
Then the calling function will echo sectionSub before echoing sectionTipo
Or change your SQL to
$sql = 'select a.categ_id, a.subcateg_id, b.tipoprod_id, b.tipoprod_name
from subcateg as a, tipoprod as b where categ_id='$categ_id'
and a.subcateg_id = b.subcateg_id';
and lose the secondary function completely. That gets MySQL to do the join between your two tables and is an order of magnitude easier to work with.
Related
$a_forms = array("a_GG", "a_FF");
$sql = "SELECT name, field FROM categories WHERE enabled = '1' ";
$result = mysqli_query($con,$sql);
$Others = array();
while($row = mysqli_fetch_array($result)) {
$Other_names[] = $row['name'];
$Other_fields[] = $row['db_field'];
}
for ($i=0;$i<count($a_forms);$i++) {
if ($a_forms[$i] == "a_FF") {
$dforms_sql = "SELECT *
FROM a_FF
where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while ($forms_row = mysqli_fetch_array($dforms_result)) {
for ($i=0; $i<count($Other_fields); $i++) {
echo "<tr><td colspan='3'>".$Other_names[$i]."</td></tr>";
}
}
} elseif ($a_forms[$i] == "a_GG") {
$dforms_sql = "SELECT *
FROM a_GG where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while($forms_row = mysqli_fetch_array($dforms_result)) {
echo 'Other cool stuff';
}
}
} //END (first) For Loop
So, for some reason, if that second for loop, $Other_field is there it will only show the IF statement for a_FF. But if the array = a_FF and a_GG and the for loop for $other_field is NOT there it displays them both. So it's obviously that for loop that is breaking something, I have no idea what though. Anyone have any thoughts?
INTRO
I am trying to better understand my knowledge of Php and using classes to better prganise my code so this is just an exercise for a better understanding rather than a real world solution.
BRIEF
I am calling in a function from a class which I have just learnt to do but I want to know the best way to do something simple tasks like use the object in an IF statement.
SCENARIO
So for instance I am setting my classes like so:
class user
{
// Get users ID
function get_user_id()
{
global $conn;
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['id'] . ', '; }
}
}
// Get users name
function get_user_name()
{
global $conn;
$sql = 'SELECT name FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['name'] . ', '; }
}
}
}
$userId = new user;
$userName = new user;
I am then initializing in my classes like so:
<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>
and THEN I am wanting to performa simple task like show a user based on the value of their ID, the above will return 2 sets of results of 4 so id 1, 2, 3, 4 & Dan, Andy, Ryan, Aran
so I am performing a simple IF statement like so:
if($userId > 1){
echo $userName;
} else {
echo 'not working';
}
But it returns 'not working' - I am just wanting to better understand how to use the functions in a way that A works and B best practice.
It doen't look like you've understood OOP just yet.
These code examples should hopefully give you an introduction but as in other comments, read up on OOP. I struggled with it at first but keep at it!
Create your user class
This class represents a single user and the actions associated with a user, think of it as a blue print. It should only perform functions related to a user, it shouldn't keed to 'know' about anything else. For example, database functions sholud be done elsewhere.
class User {
private $id;
private $name;
function __construct($array)
{
$this->id = $array['id'];
$this->name = $array['name'];
}
function getId()
{
return $this->id;
}
function getName()
{
return $this->name;
}
}
Load all users into an array
$sql = 'SELECT * FROM user';
$result = $conn->query($sql);
$users = [];
while ($row = $result->fetch_assoc() ){
$users[] = new User($row);
}
// this array now contains all your users as User objects
var_dump($users);
// echo all user's details
foreach($users as $user) {
echo $user->getId();
echo ' - ';
echo $user->getName();
echo "\r\n";
}
Load a single user
$sql = 'SELECT * FROM user WHERE id = 1';
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
$user = new User($row);
} else {
exit('User ID does not exist');
}
// echo the user's ID and name
echo $user->getId();
echo ' - ';
echo $user->getName();
Resourses
Laracasts - https://laracasts.com/series/object-oriented-bootcamp-in-php
Search PHP OOP explained - https://www.google.co.uk/search?q=php+oop+explained
<?php
class user {
// Get users ID
function get_user_id() {
global $conn;
$data = array();
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['id'] . ', ';
}
}
return $data;
}
// Get users name
function get_user_name() {
global $conn;
$data = array();
$sql = 'SELECT name FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'] . ', ';
}
}
return $data;
}
}
$userId = new user;
$userName = new user;
// all user ids
$all_ids = $userId->get_user_id();
echo '<pre>';
print_r($all_ids);
// all user name
$all_name = $userId->get_user_name();
echo '<pre>';
print_r($all_name);`enter code here`
Check first response from both function after use if condition
You are comparing object with 1 not the value returned by function get_user_id().
So instead of
<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>
Try
<?php $id=$userId->get_user_id(); ?>
<?php $name= $userName->get_user_name(); ?>
and then put in your condition
if($id > 1){
echo $name;
} else {
echo 'not working';
}
I will suggest you to replace echo with return statement.
call your class as an object
$userid = user();
$username = user();
you can also try something like this
class user
{
// Get users ID
function get_user_id($id = "")
{
global $conn;
// check if id is empty or not
if(!empty($id)) {
$sql = 'SELECT id FROM users WHERE id = '.$id;
}else{
$sql = 'SELECT id FROM users';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['id'] . ', '; }
}
}
// Get users name
function get_user_name($name = "")
{
global $conn;
// check if name is empty or not
if(!empty($name)) {
$sql = 'SELECT name FROM user WHERE name = '.$name;
}else{
$sql = 'SELECT name FROM user';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['name'] . ', '; }
}
}
}
$userId = new user();
$userName = new user();
$userId->get_user_id(1);
$userName->get_user_name();
echo $userId;
echo $userName;
please make sure you sanitize the id and name before use
IN both get_user_id, get_user_name methods please
return $row = $result->fetch_assoc();
so, it will value comes in $userId, $userName and you can access it.
right now you return nothing so $user_id has null value so, it always goes in else condition.
Example
function get_user_id()
{
global $conn;
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$value = '';
while ($row = $result->fetch_assoc() ){
$value .= $row['id'] . ', ';
}
return $value;
}
}
i am having category sidebar below code
Working Code:
//Showing categories function
function getCats(){
global $db;
$q_cats = "select * from cats ORDER BY cat_name ASC";
$run_cats = mysqli_query($db, $q_cats);
while($row_cat = mysqli_fetch_array($run_cats)){
$cat_id = $row_cat['cat_id'];
$cat_name = $row_cat['cat_name'];
$q_count = "select * from messages where cat_id='$cat_id'";
$run_count = mysqli_query($db, $q_count);
$cat_sms_count = mysqli_num_rows($run_count);
if($cat_sms_count < 1){
$cat_sms_count = 0;
}
echo "<a href='category.php?category=$cat_id' class='list-group-item'>$cat_name<span class='badge'>$cat_sms_count</span></a>";
}//while row END here
$q_tmsgs = "select * from messages";
$run_tcount = mysqli_query($db, $q_tmsgs);
$tsms_count = mysqli_num_rows($run_tcount);
echo "<a href='allindb.php' class='list-group-item t-list'>Total Messages in DB<span class='badge'>$tsms_count</span></a>";
}//Function getCats END here
this working fine but what i want, i want to add a new badge image next to the category name. i tried a lot but failed to do, what i think is the most relevant code.
Please check this code:
//Showing categories function
function getCats(){
global $db;
$q_cats = "select * from cats ORDER BY cat_name ASC";
$run_cats = mysqli_query($db, $q_cats);
while($row_cat = mysqli_fetch_array($run_cats)){
$cat_id = $row_cat['cat_id'];
$cat_name = $row_cat['cat_name'];
$q_count = "select * from messages where cat_id='$cat_id'";
$run_count = mysqli_query($db, $q_count);
$cat_sms_count = mysqli_num_rows($run_count);
//problem area----------------------------------
$q_new = "select * from messages where cat_id='$cat_id' ORDER BY date DESC LIMIT 20";
$run_new = mysqli_query($db, $q_new);
while($new = mysqli_num_rows($run_new)){
$newbadge = $new['cat_id'];
}
if($cat_id==$newbadge){
$newbadge1 = "<img src='images/mynew.gif'>";
}
//--------------------------------------------
if($cat_sms_count < 1){
$cat_sms_count = 0;
}
echo "<a href='category.php?category=$cat_id' class='list-group-item'>$cat_name $newbadge1<span class='badge'>$cat_sms_count</span></a>";
}//while row END here
$q_tmsgs = "select * from messages";
$run_tcount = mysqli_query($db, $q_tmsgs);
$tsms_count = mysqli_num_rows($run_tcount);
echo "<a href='allindb.php' class='list-group-item t-list'>Total Messages in DB<span class='badge'>$tsms_count</span></a>";
}//Function getCats END here
If i understand you correctly you want to show "new badge" on those topics that doesnt have any messages in them. if so you got $q_count
Just replace the while{} inside with an if{}else{}like so:
if($q_count == 0) {
$newbadge1 = "<img src='images/mynew.gif'>";
} else {
$newbadge1 = '';
}
The problem is that you are doing another query that is returning empty array, and therefore you are getting badges on topics that has got messages. So either remove the while{} and replace with the if-else or you can just do a check like:
if(empty($new)) {
$newbadge1 = "<img src='images/mynew.gif'>";
} else {
$newbadge1 = '';
}
I am wondering my class property $friend_username does not returning its value either it is public.
update
class Feed {
public static $friend_username;
// ONLINE FRIENDS LOGIC
public function online_friends(){
$friendsHTML = '';
$countOnlineFriends = '';
if(GetFriends($GLOBALS['log_username']) != false) {
$all_friends = GetFriends($GLOBALS['log_username']);
$orLogic = '';
foreach($all_friends as $key => $user){
if(IsBlocked($GLOBALS['log_username'],$user,true) == false){
$orLogic .= "username='$user' OR ";
}
}
$orLogic = chop($orLogic, "OR ");
$sql = "SELECT username, avatar, logged_in FROM users WHERE ($orLogic) AND logged_in = 1";
$query = mysqli_query($GLOBALS['db_conx'], $sql);
$friend_loggedIn = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$this->friend_username = $row["username"];
$friend_avatar = $row["avatar"];
$friend_loggedIn[] = $row["logged_in"];
$friend_pic = userImage($this->friend_username,$friend_avatar,'42','42',$link = false,$up = true);
$friendsHTML .= '<li><a href="#" onClick="chatbox(\''.$this->friend_username.'\',\''.getName($this->friend_username,true).'\');return false;">'.$friend_pic.' '.getName($this->friend_username,true).'</li>';
$countFriends = count($friend_loggedIn);
$countOnlineFriends = ($countFriends > 0) ? '<span class="online_friends animated">'.$countFriends.'</span>' : '';
}
}else{
$friendsHTML = 'No friends';
}
return "$countOnlineFriends|$friendsHTML";
}
public function update_chat() {
$id = '';
$messages = '';
$randUser = '';
$user = sanitize($this->friend_username);
$sql = "SELECT * FROM pm_chat WHERE (sender='$GLOBALS[log_username]' AND receiver='$user') OR (sender='$user' AND receiver='$GLOBALS[log_username]') ORDER BY datetime DESC";
$result = mysqli_query($GLOBALS['db_conx'],$sql) or die(mysqli_error($GLOBALS['db_conx']));
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user1 = $row['sender'];
$user2 = $row['receiver'];
$message = parseData($row['message']);
$did_read = $row['did_read'];
$datetime = $row['datetime'];
if ($user1 != $GLOBALS['log_username']) {
$randUser = $user1;
}elseif ($user2 != $GLOBALS['log_username']) {
$randUser = $user2;
}
if ($user1 == $GLOBALS['log_username'] && $user2 != $GLOBALS['log_username']) {
$messages .= '<li class="row" id="pm_row_'.$id.'"><div class="me">'.$message.'</div></li>';
}else{
$messages .= '<li class="row" id="pm_row_'.$id.'">'.userImage($randUser,getAvatar($randUser),28,28,$link = true,$up = true).'<div class="userfrnd">'.$message.'</div></li>';
}
}
return $this->friend_username."$id|$messages|$randUser";
// this is for ^^^^^^^ testing purpose
}
}
here is the other file where I am calling the other class method. And its content-type is text/event-stream
class update_chat extends SSEEvent {
public function update(){
//Here's the place to send data
$feed = new Feed();
return $feed->update_chat();
}
public function check(){
//Here's the place to check when the data needs update
return true;
}
}
Any idea or suggestion why this problem persist ?
thanks in advance.
If you are calling bar() in another file and then creating a new Foo in otherClass, you are not referencing the same instance of Foo. Either make $friend_username static and call it statically
public static $friend_username;
public function update(){
//Here's the place to send data
return Foo::$friend_username;
}
or at least make the function static
public static function bar() {}
public function update(){
//Here's the place to send data
return Foo::bar();
}
or pass in the instance of Foo to the function
public function update(Foo $Foo){
//Here's the place to send data
return $Foo->bar();
}
If you want to call a static method from within the same class, you have to use the self identifier (self::$var)
class Feed {
public static $friend_username = array();
// ONLINE FRIENDS LOGIC
public function online_friends(){
$friendsHTML = '';
$countOnlineFriends = '';
if(GetFriends($GLOBALS['log_username']) != false) {
$all_friends = GetFriends($GLOBALS['log_username']);
$orLogic = '';
foreach($all_friends as $key => $user){
if(IsBlocked($GLOBALS['log_username'],$user,true) == false){
$orLogic .= "username='$user' OR ";
}
}
$orLogic = chop($orLogic, "OR ");
$sql = "SELECT username, avatar, logged_in FROM users WHERE ($orLogic) AND logged_in = 1";
$query = mysqli_query($GLOBALS['db_conx'], $sql);
$friend_loggedIn = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push(self::$friend_username, $row["username"]);
$friend_avatar = $row["avatar"];
$friend_loggedIn[] = $row["logged_in"];
$friend_pic = userImage(self::$friend_username,$friend_avatar,'42','42',$link = false,$up = true);
$friendsHTML .= '<li><a href="#" onClick="chatbox(\''.self::$friend_username.'\',\''.getName(self::$friend_username,true).'\');return false;">'.$friend_pic.' '.getName(self::$friend_username,true).'</li>';
$countFriends = count($friend_loggedIn);
$countOnlineFriends = ($countFriends > 0) ? '<span class="online_friends animated">'.$countFriends.'</span>' : '';
}
}else{
$friendsHTML = 'No friends';
}
return "$countOnlineFriends|$friendsHTML";
}
public function update_chat() {
$id = '';
$messages = '';
$randUser = '';
$user = Feed::$friend_username;
foreach ($user as $key => $value) {
$user[$key] = sanitize($value);
}
//I leave it up to you to figure out how you want to deal with the array of users in this next line
$sql = "SELECT * FROM pm_chat WHERE (sender='$GLOBALS[log_username]' AND receiver='$user') OR (sender='$user' AND receiver='$GLOBALS[log_username]') ORDER BY datetime DESC";
$result = mysqli_query($GLOBALS['db_conx'],$sql) or die(mysqli_error($GLOBALS['db_conx']));
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user1 = $row['sender'];
$user2 = $row['receiver'];
$message = parseData($row['message']);
$did_read = $row['did_read'];
$datetime = $row['datetime'];
if ($user1 != $GLOBALS['log_username']) {
$randUser = $user1;
}elseif ($user2 != $GLOBALS['log_username']) {
$randUser = $user2;
}
if ($user1 == $GLOBALS['log_username'] && $user2 != $GLOBALS['log_username']) {
$messages .= '<li class="row" id="pm_row_'.$id.'"><div class="me">'.$message.'</div></li>';
}else{
$messages .= '<li class="row" id="pm_row_'.$id.'">'.userImage($randUser,getAvatar($randUser),28,28,$link = true,$up = true).'<div class="userfrnd">'.$message.'</div></li>';
}
}
return Feed::$friend_username."$id|$messages|$randUser";
// this is for ^^^^^^^ testing purpose
}
}
Well, since your are using the method mysqli_fetch_array, could it be that more than one element is returned and that the last one is empty?
BTW, I don't understand why you are making a single variable attribution inside a while statement. Supposedly, the last running (if some) will overwrite the variable's value.
Another observation, on the second code. If you are calling the bar() method right off the bat, shoudn't the variable be empty anyway? I understand that $friend_username is only assigned inside the foo() method.
I would like to link to the table with the uploader column that has the uploaders name.
<?php echo $_SESSION['MM_Username'];?>
<?php
$subQ2 = '';
if(isset($_GET['uploader']) && $_GET['uploader']!='')
{
$subQ2 = ' WHERE uploader="'.mysql_real_escape_string(str_replace('_', '', $_GET['uploader'])).'"';
}
function uploader()
{
if(isset($_GET['uploader']) && $_GET['uploader']!='')
{
return $_GET['uploader'];
}
else return "uploader";
}
$query_Form = "SELECT * FROM docus".$subQ2.' ORDER BY ID DESC';
$Form = mysql_query($query_Form, $dbconnection) or die(mysql_error());
$row_Form = mysql_fetch_assoc($Form);
$totalRows_Form = mysql_num_rows($Form);
?>
I'm trying to learn php and sql from video tutorials so this may sound like a dumb question.
Any help is greatly apreciated
Try this code
<?php
function uploader()
{
global $dbconnection;
$return = array('data' => null, 'data_count' => 0);
if(!empty($_GET['uploader']))
{
$data = mysql_real_escape_string(str_replace('_', '', $_GET['uploader']));
$query_Form = 'SELECT * FROM docus WHERE uploader="'.trim($data).'" ORDER BY ID DESC';
$Form = mysql_query($query_Form, $dbconnection) or die(mysql_error());
$return['data'] = mysql_fetch_assoc($Form);
$return['data_count'] = mysql_num_rows($Form);
}
return $return;
}
$total = upload();
// $row_Form - is now $total['data];
// $totalRows_Form - is now $total['data_count];
?>