php – Erro de Banco de dados numero 1146

Eu to usando um codigo para chamar uma tabela da database:

public function get_config()
    {
        return $this->db->get('config');
    }

Mas sempre da erro:

Número do erro: 1146

    Tabela 'id17360989_db.hd_config' não existe
    
    SELECT * FROM `hd_config`
    
    Nome do arquivo: models / Inithook.php
    
    Número da linha: 14

javascript – Problema con sesiones en un INDEX PHP

Tengo un login donde ingreso mis credenciales y me redirecciona al dashboard en un index.php que dejare el codigo a continuación. Pero antes, mi problema en particular es que cuando recargo la pagina desde la barra de busqueda, la sesion se cierra y me envia denuevo al login en vez de traerme el dashboard denuevo.

Algo me hace sospechar que la sesion se destruye.

<?php
include_once 'includes/user.php';
include_once 'includes/user_session.php';

$errorLogin = "";

if(isset($_SESSION('user'))){
    $user->setUser($userSession->getCurrentUser());
    include_once 'dashboard.php';

}else if(isset($_POST('username')) && isset($_POST('password'))){
    
    $userForm = $_POST('username');
    $passForm = $_POST('password');
    
    $userSession = new UserSession();
    $user = new User();
    if($user->userExists($userForm, $passForm)){
        // Grant access
        $userSession->setCurrentUser($userForm);
        $user->setUser($userForm);
        include_once 'dashboard.php';
    }else{ 
        // Deny Access
        $errorLogin = "Credenciales inválidas";
        include_once 'login.php';
    }
}else{
    $userSession = new UserSession();
    $user = new User();
    include_once 'login.php';
}
?>

Que puedo estar haciendo mal?

php – Middleware não existe laravel 8

O PROBLEMA

Eu estou fazendo um Middleware para proteger minhas rotas porem eu quando passa pelo Middleware que eu criei retorna que não existe. Ja fiz de tudo mas nao consigo avançar.

O QUE EU JA FIZ

Criei a Middleware, incluir no meu kernel.php

        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
        'jwt' => appHttpMiddlewareJwtMiddleware::class
    );

CHAMO NA ROTA

Route::group(('namespace' => 'Api', 'as' => 'api.'), function () {
    Route::post('/auth/login',  (AuthController::class, 'login'))->name('auth.login');

    Route::group(('middleware' => 'jwt'), function () {

        Route::post('/auth/logout',  (AuthController::class, 'logout'))->name('auth.logout');
        Route::post('/me',  (AuthController::class, 'me'))->name('auth.me');
        Route::get("https://pt.stackoverflow.com/users", (UserController::class, 'index'))->name('auth.index');
        Route::get('/address', (AddressController::class, 'index'))->name('address.index');
        Route::get('/product', (ProductController::class, 'index'))->name('product.index');
    });
});

MENSSAGEM DO ERRO

IlluminateContractsContainerBindingResolutionException: Target class (appHttpMiddlewareJwtMiddleware) does not exist. in file D:devprojetobackvendorlaravelframeworksrcIlluminateContainerContainer.php on line 875

Bulk Backlink Pinger Software (PHP) for $5

Instantly download the amazing PHP Backlink Pinger software! Awesome PHP script to get your SEO website to top!

by: yuyu2000
Created: —
Category: PHP
Viewed: 374


.

php – implementing SOLID principles and oop

im reading clean code, and practicing SOLID principles, can someone help me to improve this code, suggestions are welcome:

<?php 

require_once ('database.class.php');

class EncryptPassword{
    
    public function encrypt(string $password){
        $encrypted_password = sha1($password);
        return $encrypted_password;
    }

}

class insertUser extends EncryptPassword{

    private $id_user_type;
    private $name;
    private $lastname;
    private $email;
    private $password;
    

    public function __construct(int $id_user_type, string $name, string $lastname, string $email, string $password){

        $this->id_user_type = $id_user_type;
        $this->name = $name;
        $this->lastname = $lastname;
        $this->email = $email;
        $this->password = $password;
        
    }

    public function insert(){

        try {

            $db = database::getInstance();

            $password = parent::encrypt($this->password);

            $sql = $db->prepare("INSERT INTO users (id_user_type, name, lastname, email, password) VALUES (?, ?, ?, ?, ?)");

            $sql->bindParam(1, $this->id_user_type);
            $sql->bindParam(2, $this->name);
            $sql->bindParam(3, $this->lastname);
            $sql->bindParam(4, $this->email);
            $sql->bindParam(5, $password);

            $result = $sql->execute();

            if($result==true){
                return "inserted";
            } else {
                return "not inserted";
            }

        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}

class updateUser extends EncryptPassword{

    private $id_user;
    private $id_user_type;
    private $name;
    private $lastname;
    private $email;
    private $password;
    

    public function __construct(int $id_user, int $id_user_type, string $name, string $lastname, string $email, string $password=''){

        $this->id_user = $id_user;
        $this->id_user_type = $id_user_type;
        $this->name = $name;
        $this->lastname = $lastname;
        $this->email = $email;
        $this->password = $password;
        
    }

    public function update(){

        try {

            $db = database::getInstance();
            $password = parent::encrypt($this->password);

            if(!empty($password)){

                $sql = "UPDATE users SET id_user_type=?, name=?, lastname=?, email=?, password=? WHERE id=?";
                $stmt= $db->prepare($sql);
                $result = $stmt->execute(($this->id_user_type, $this->name, $this->lastname, $this->email, $password, $this->id_user));
                
            } else {

                $sql = "UPDATE users SET id_user_type=?, name=?, lastname=?, email=? WHERE id=?";
                $stmt= $db->prepare($sql);
                $result = $stmt->execute(($this->id_user_type, $this->name, $this->lastname, $this->email, $this->id_user));
                
            }

            if($result==true){
                return "updated";
            } else {
                return "not updated";
            }

        
        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}


class getUsers{

    public function getAllUsers(){

        try {

            $db = database::getInstance();

            $sql = 'SELECT id, name, lastname, email, active, date FROM users';
            $stm = $db->prepare($sql);
            $stm->execute();
            $result = $stm->fetchAll(PDO::FETCH_ASSOC);

            return $result;
        
        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}

class getUserInfo{

    public function __construct(int $id_user){
        $this->id_user = $id_user;
    }

    public function getUser(){

        try {

            $db = database::getInstance();

            $sql = "SELECT id, name, lastname, email, active, date FROM users where id=:id";
            $stm = $db->prepare($sql);
            $stm->bindParam(':id', $this->id_user, PDO::PARAM_INT);
            $stm->execute();
            $result = $stm->fetch();

            return $result;
        
        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}

class OnOff{

    public function __construct(int $id_user, int $actdeact){
        $this->id_user = $id_user;
        $this->actdeact = $actdeact;
    }

    public function statusUser(){

        try {

            $db = database::getInstance();

            $sql = "UPDATE users SET active=? WHERE id=?";
            $stmt= $db->prepare($sql);
            $result = $stmt->execute(($this->actdeact, $this->id_user));

            return $result;
        
        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}

The database class:

<?php

class database {

    protected static $instance;

    protected function __construct() {}

    public static function getInstance() {

        if(empty(self::$instance)) {

            $db_info = array(
                "db_host" => "localhost",
                "db_port" => "3306",
                "db_user" => "localhost",
                "db_pass" => "xxxxxxxxxx",
                "db_name" => "xxxxxxxxxx",
                "db_charset" => "UTF-8");

            try {

                self::$instance = new PDO("mysql:host=".$db_info('db_host').';port='.$db_info('db_port').';dbname='.$db_info('db_name'), $db_info('db_user'), $db_info('db_pass'));
                self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);  
                self::$instance->query('SET NAMES utf8');
                self::$instance->query('SET CHARACTER SET utf8');

            } catch(PDOException $error) {
                echo $error->getMessage();
            }

        }
        return self::$instance;
    }
}

?>

mysql – PHP ou Node.JS?

mysql – PHP ou Node.JS? – Stack Overflow em Português

php – Add Featured Image to Existing Post

I have already created thousands of product as posts (CSV Import). They have a custom post type. Now, I would like to assign featured image to each existing post programmatically (without manually entering each post and setting the featured images more than 3,000 times).

Additional info:

  • Import plugin have not worked out, so I cannot attach the images using CSV import.
  • I use a custom field called ‘ean’ with each prduct, and it is standing as the unique serial number. It is an interger, for example: “5999626322456”. The same interger is standing for name of the image (i.e. 5999626322456.jpg).

What code do you recommend to use? I tried these two (among many), but they do not work. What do I do wrong?

function set_post_thumbnail( $post, $thumbnail_id ) {
    $post    = get_post( $post );
    $ean_url = rwmb_get_value( 'ean' );
    $kep_url = $ean_url . '.jpg';
    $thumbnail_id = attachment_url_to_postid( $kep_url );
    if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
        if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) {
            return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
        } else {
            return delete_post_meta( $post->ID, '_thumbnail_id' );
        }
    }
    return false;
}

// Add Featured Image to Post

$ean_url          = rwmb_get_value( 'ean' );
$image_url        = '/wp-content/uploads/' . $ean_url . '.jpg'; // Define the image URL here
$image_name       = $ean_url . '.jpg';
$upload_dir       = wp_upload_dir(); // Set upload folder
$image_data       = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir('path'), $image_name ); // Generate unique name
$filename         = basename( $unique_file_name ); // Create image file name

// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir('path') ) ) {
    $file = $upload_dir('path') . "https://wordpress.stackexchange.com/" . $filename;
} else {
    $file = $upload_dir('basedir') . "https://wordpress.stackexchange.com/" . $filename;
}

// Create the image  file on the server
file_put_contents( $file, $image_data );

// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );

// Set attachment data
$attachment = array(
    'post_mime_type' => $wp_filetype('type'),
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => '',
    'post_status'    => 'inherit'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );

// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');

// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );

// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );

// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

php – Loop for recently (updated_post_meta) posts?

I’m trying to create a simple loop for recently updated post meta_key.

Basically, let’s say someone liked a post.

When like was clicked, that updated post meta_key ‘like’ value.

I want to display on the sidebar a loop with newest liked posts.

Is that possible?

Any help would be appreciated.

P.S. I know how to create a function action that does something, when post meta data was updated.

But I don’t need that. I want to show a simple loop with recently liked (meta updated) posts.

php – How to display 8 posts in four columns and 2 rows on a carousel slide?

I am trying to achieve a grid layout as such that posts will be visible on a carousel slider. Each slide will consist of 8 posts. 4 posts per row.

I am using bootstrap as well.

I want html to look like:

<div class="slider_container">
<div class="services-slide">
<div class="row">
<div class="col-md-3">
<div class="box-desc">
<h4>title 1</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 2</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 3</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 4</h4>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="box-desc">
<h4>title 5</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 6</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 7</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 8</h4>
</div>
</div>
</div>
<div class="services-slide">
<div class="row">
<div class="col-md-3">
<div class="box-desc">
<h4>title 9</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 10</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 11</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 12</h4>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="box-desc">
<h4>title 13</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 14</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 15</h4>
</div>
<div class="col-md-3">
<div class="box-desc">
<h4>title 16</h4>
</div>
</div>
</div>
</div>

Here is my code but it is not working though.

<div class="slider_container">
<?php
ob_start();
$args = array( 'post_type' => 'services','posts_per_page' =>-1,'order' => 'ASC');
$the_query = new WP_Query($args);
if ($the_query->have_posts()) : 
$i = 0;
$o = 0;
  ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<div class="services-slide">
 <div class="row">
   <?php if ($i == 4) { $i = 0; ?>
    </div>
    <div class="row">
   <?php } ?>
   <div class="col-md-3">
       <div class="box-desc">
            <h4><?php echo get_the_title(); ?></h4>
        </div>
    </div>
</div>
  <?php $i++; ?>
</div>
<?php endwhile; ?>
<?php
endif;
wp_reset_postdata();
$content = ob_get_contents();
ob_end_clean();
return $content; ?>
</div>

Please help.

php – Perguntas e respostas com ajax

Estou fazendo um form de retorna uma interação caso a resposta esteja errada.
A ideia é que caso a pessoa selecione a resposta certa, o button altere a cor para verde ou vermelho para errado.
Isso em Ajax. Sem atualizar a página.

Alguém teria ideia de como pegar o valor selecionado no radio button e comparar com a resposta correta, dentro desse código ajax? Ou teria uma outra melhor?

<form name="frm'.$row('question_id').'" role="form" id="submitForm'.$row('question_id').'">
<input type="hidden" class="form-control" name="question_id" placeholder="Name" value="'.$row('question_id').'" required="">
<input type="hidden" class="form-control" name="user_id" placeholder="User" value="'.$myid.'" required="">
<div class="form-check">
<input class="form-check-input'.$row('question_id').'" type="radio" name="resposta" id="blankRadio1" value="A" aria-label="..." onClick="mostrar'.$row('question_id').'()"> 
A) '.$row('option1').'
</div>                
<div class="form-check">
<input class="form-check-input'.$row('question_id').'" type="radio" name="resposta" id="blankRadio1" value="B" aria-label="..." onClick="mostrar'.$row('question_id').'()"> 
B) '.$row('option2').'
</div>                
<div class="form-check">
<input class="form-check-input'.$row('question_id').'" type="radio" name="resposta" id="blankRadio1" value="C" aria-label="..." onClick="mostrar'.$row('question_id').'()"> 
C) '.$row('option3').'
</div>                
<div class="form-check">
<input class="form-check-input'.$row('question_id').'" type="radio" name="resposta" id="blankRadio1" value="D" aria-label="..." onClick="mostrar'.$row('question_id').'()"> 
D) '.$row('option4').'
</div><br>                
<button type="submit" class="btn btn-info btn btn-block" id="submitbtn'.$row('question_id').'" name="botao'.$row('question_id').'" disabled>Responder</button>
</form>

<script type="text/javascript">
  $(document).ready(function(){
      $("#submitForm'.$row('question_id').'").on("submit", function(e){
          e.preventDefault();
          $("#submitbtn").text("Please wait..");
          var userForm = $(this).serialize();          
          $.ajax({
              url :"insertData.php",
              type : "POST",
              cache:false,
              data: userForm,
              success:function(response){
                $("#submitbtn'.$row('question_id').'").attr("disabled",true);
                $("#success").show();
                $("#success").html("Data inserted successfully");
                $("#submitbtn'.$row('question_id').'").text("Gabarito: '.$row('answer').'");
                $("#submitForm")(0).reset();                 
              }
          });          
      });      
  });
</script>

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies 5000 Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Buy Cheap Private Proxies; Best Quality USA Private Proxies