Activate and deactivate concept using PHP PDO

1

I am a newbie and I can take time to learn PDO php from 0, Well this is the concept to activate and deactivate the category. Can someone help me with this? I would like to update the status of the category, the status should be 0 (deactivate) or 1 (activate) to hide (hide) and show (show), how to activate and deactivate the status of the category?

Here is the structure of the table

-------------------------------------------
| category table                          |
-------------------------------------------
| cid | cname | clink | cparent | cstatus |
-------------------------------------------

index.php

public function Category()
    {

        $db = getBD();
        $sql = $db->prepare("SELECT * FROM category WHERE cparent = 0");
        $sql->execute();
        $data = $sql->fetchAll(PDO::FETCH_ASSOC);

        $menu = array();

        foreach ($data as $categ) {

            $sql = $db->prepare("SELECT * FROM category WHERE cparent = '".$categ['cid']."'");
            $sql->execute();
            $sdata = $sql->fetchAll(PDO::FETCH_ASSOC);

            $categ['subcategorias'] = array();

            foreach ($sdata as $subcateg) {
                $categ['subcategorias'][] = $subcateg;
            }
            $menu[] = $categ;

        }
        return $menu;

        //AQUI UPDATE STATUS
        $status = $_GET['cstatus'];
        $sql = $db->prepare("SELECT * FROM category WHERE cid = '".$status."'");
        $sql->execute();
        $data = $sql->fetchAll(PDO::FETCH_ASSOC);

        //AQUI UPDATE STATUS
        $status_var=$row->status;
        if($status_var=='0')
        {
            $status_state=1;
        }
        else
        {
            $status_state=0;
        }
            $sql = $db->prepare("UPDATE category set cstatus='".$status_state."' WHERE cid='".$status."'");

            if($sql)
            {
                header("Location:index.php");
            }
    }

category.php

$object = new myObject();    
$data = '<table>
             <tr>
             <th>Id</th>
             <th>Categoria</th>
             <th>Sub Categoria</th>
             <th>Link</th>
             <th>Estado</th>
             <th>Editar</th>
             <th>Delete</th>
             </tr>';

    $menus = $object->cCategory();

    if($menus)
    {

        foreach ($menus as $menu) {

            $status = $menu['cstatus'];
            if($status == '0'){
                ?>
                <a href="category.php?status=<?php echo $menu['cid']; ?>" onclick="return confirm('Activate');"> Deactivate </a>
                <?php
            } 
            else if($status == '1')
            {
            ?>
                <a href="category.php?status=<?php echo $menu['cid']; ?>" onclick="return confirm('Desactivate');"> Activate </a>

            <?php
            }
            $data .= '<tr>
                    <td>' . $menu['cid'] . '</td>
                    <td>' . $menu['cname'] . '</td>
                    <td>' . $menu['cparent'] . '</td>
                    <td>' . $menu['clink'] . '</td>
                    <td>' . $menu['cstatus'] . '</td>

                    <td>
                        <button onclick="GetUserDetails(' . $menu['cid'] . ')" class="btn btn-warning">Update</button>
                    </td>
                    <td>
                        <button onclick="DeleteUser(' . $menu['cid'] . ')" class="btn btn-danger">Delete</button>
                    </td>
                </tr>';

        }
    } else {
        $data .= '<tr><td colspan="6">No hay resultado</td></tr>';
    }

    $data .= '</table>';

    echo $data;
    
asked by Diego Sagredo 15.03.2017 в 16:53
source

1 answer

2

The truth is that your class is a bit confusing, and even if you only show a method of the class myObject it seems that it groups everything into an amalgam of things.

The first thing you should do is to structure the class better and separate things.

For example:

<?php
class Category 
{
    public function __construct ( ) 
    {
        // Cosas que se hacen al instancia el objeto
    }

    public function index ( )
    {
        // Retornar un Array con todas las categorias
    }

    public function edit ($idCategory)
    {
        // Retornas un Array con los datos de la categoría seleccionada para poder editarlos
    }

    public function update ($idCategory, $dataCategory)
    {
        // Actualizas los datos en la base de datos de la categoría editada
    }

    // Otros métodos 
}
?>

Then outside of class is where you should put together the html / vista

Vista index category

<?php
include 'Category.class.php';

$objCategory = new Category;

$arrayAllCategory = $objCategory->index();

foreach ( $arrayAllCategory as $keyCat => $ValueCat )
{ 
    // Armas la tabla
}

Edit edit category

<?php 
include 'Category.class.php';

$objCategory = new Category;

$arrayCategory = $objCategory->edit($_GET['idCategory']);

// Formulario edición con los datos de $arrayCategory
// este formulario apuntará al archivo que hará el update 

Vista update

<?php
include 'Category.class.php';

$objCategory = new Category;

 if ( $objCategory->update($id, $data) )
 { 
     // se ha actualizado
 }
 else
 { 
     // error, no se ha actualizado 
 }

The update method can be something like this

<?php

public function update ($idCategory, $dataCategory)
{
    // datos para recuperar conexion o establecerla

    // actualizar registro 
    $prepare = $db->prepare("UPDATE category set cstatus= :data WHERE cid= :cid");
    $param  = array( ':data' => $dataCategory, ':cid' => $idCagory);
    if ( $prepare->execute( $param ) )
    { 
        return true; // Se actualizó
    }
    else
    { 
        return false; // No se actualizo
    }

}

Apart from all this, the way in which you prepare the sentences is wrong

$sql = $db->prepare("SELECT * FROM category WHERE cid = '".$status."'");
//                                               Aquí-> ^^^^^^^^^^^^^^
// Debería quedar algo asi por ejemoplo
$sql = $db->prepare("SELECT * FROM category WHERE cid = :status ");

Do not embed values in the preparation of the sentence, this is dangerous and exposes you to SQL injection, the sentence must be prepared with : identifiers or with ? , the parameters are passed afterwards.

PDO documentation prepare

    
answered by 19.04.2017 / 17:39
source