can run a query within a user defined function in php?

Asked

Viewed 547 times

0

I have code like this:

function apagar(){

    $conexao = mysqli_connect('localhost','usuario','senha');
    $db = mysqli_select_db("banco");    

    $delete = mysqli_query("TRUNCATE table sap_reportes.zempe019");
    return $delete;

    //return 'teste';
}

//script do relatório.

apagar($delete);

//fim do relatório.

the problem is that Truncate does not work, I am running this script in cmd, this server script to generate reports so far everything well it is generating the normal report and sending by e-mail the problem is that at the end of the report I would like to delete the table I’ve tried everything else I don’t know why truncate doesn’t work after running all the script at the beginning of the script it even works more I would need this truncate to run at the end of the report so I did this php function and called it at the end of the report.

  • Yes it is possible, what error happens?

  • The first argument of mysqli_query() is the connection apparently why it doesn’t work.

  • Try it like this $delete = mysqli_query($conexao, "TRUNCATE table sap_reportes.zempe019") or die(mysqli_error($conexao));

  • Did a mistake appear?

  • A delete without Where works?

  • Have any error being returned you need to discover it or try to run this query directly in the bank see via phpmyadmin or Workbench

  • 1

    Yes, any type of encapsulation is possible.

  • can solve like $delete = mysql_query("truncate table name_da_table");

  • 1

    and called $delete(); at the end of the report it worked

  • mysql_query() is a function removed in new versions of php and mysqli_query() is the current function.

Show 5 more comments

1 answer

-1

To make a encapsulation, I prefer to use PDO:

 class Database {

        private static $servidor = 'localhost'; // Servidor, no caso poderia ser também localhost
        private static $usuario = 'root'; // usuário do banco de dados
        private static $senha = 'senha'; // senha do banco de dados
        private static $banco = 'banco'; // nome do banco de dados
        private static $instance = null;

        public static function getConnection() {
            if (!self::$instance instanceof PDO) {
                try {
                    self::$instance = new PDO('mysql:host=' .
                    self::$servidor . ';dbname=' . 
                    self::$banco, 
                    self::$usuario, 
                    self::$senha);
                } catch (PDOException $exc) {
                    echo "Erro ao conectar :: {$exc->getMessage()}";
                }
            }
            return self::$instance;
        }

        public function fetchAll($query) {
            $con = self::getConnection();

            $stmt = $con->prepare($query);

            $this->execute($stmt);

            if ($stmt->rowCount()) {
                return $stmt->fetchAll(PDO::FETCH_OBJ);
            } else {
                return false;
            }
        }

        public function execute(PDOStatement $stmt, array $data = null) {
            try {
                if (isset($data)) {
                    $stmt->execute($data);
                } else {
                    $stmt->execute();
                }
            } catch (PDOException $exc) {
                echo $exc->getTraceAsString();
            }
        }

        public function action($sql, array $data) {
            $con = self::getConnection();
            $stmt = $con->prepare($sql);
            $this->execute($stmt, $data);
            if ($stmt->rowCount()) {
                return true;
            } else {
                return false;
            }
        }
    }

$conexao = new Database();

//listando...
$collection = $conexao->fetchAll("SELECT * FROM tabela");

foreach ($collection as $data) {
      echo $data['campo'] . '<br>';
}

//deletando...
 $deletou = $conexao->action('DELETE FROM tabela WHERE id=:id',array('id' => (int) $id));
 if ($deletou) {
   echo "apagou!";
 }

//inserindo
$insert = $conexao->action("INSERT INTO tabela (campo1, campo2) values (:campo1,:campo2)",array('campo1'=>'valor1','campo2'=>'valor2'));
 if ($insert) {
   echo "gravou!";
 }
//atualizando
$update = $conexao->action("UPDATE tabela SET campo1=:campo1, campo2=:campo2 where id=:id",array('campo1'=>'valor1','campo2'=>'valor2','id' => (int) $id));
 if ($update) {
   echo "atualizou!";
 }
  • In my opinion, it is not very clear at what point this all solves the problem reported in the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.