Mysqli not showing results

Im building a website and im trying to avoid mysql injection, so im changing all the queries and connections.
I have the connection os a separated file, called ‘functions.php’:


$mysqli = new mysqli("localhost", "root", "mysql", "padelbeat");
if($mysqli->connect_error) {
  exit('Error connecting to database'); //Should be a message a typical user could understand in production
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli->set_charset("utf8mb4");


function createIdentifier(){
    date_default_timezone_set('Europe/Lisbon');
    date_default_timezone_get();
    $fileName = date("Ymdhis");

    return $fileName;
}

And this is the file that does not work at all:

In the case below, it is not returning any values:

<?php 
            if(!isset( $_SESSION['user']['userID'])){
                print "<script>top.location = '../index.php?id=5';</script>";
                exit();
            } else if($_SESSION['user']['role'] != "customer" ){
                print "<script>top.location = '../index.php?id=5';</script>";
                exit();
            }
            include '../../includes/functions.php';
            $userPoints = $row_card['card_points'];
                    
            $stmt_sel_prods = $mysqli->prepare("SELECT * FROM users WHERE prod_state = ?");
            $stmt_sel_prods->bind_param("s", 1);
            $stmt_sel_prods->execute();
            $result_sel_prods = $stmt_sel_prods->get_result();
            if($result_sel_prods->num_rows != 0){
                while($row_sel_prods = $result_sel_prods->fetch_assoc()) {
                    extract($row_sel_prods);
                    $percentageReachProd = ($userPoints * 1 / $prod_points) * 100;
                    echo "  
                    <div class='product'>
                        <div class='prod_img'><img src='../../assets/products/$prod_img' width='150px'></div>
                        <div class='prod_title'>$prod_name</div>
                        <div class='prod_desc'>$prod_desc</div>
                        <progress id='progressBar' max='100' value='$percentageReachProd' style='margin-bottom:5%; margin-top:-5%'></progress>
                        <div class='prod_seemore'><button class='btn_seemore' onclick='location.href="index.php?page=21&prodID=$prod_id";' >Trocar por $prod_points <img src='../../assets/default/beat.png' width='11px'></button></div>
                    </div>
                    ";

          
                }
            }else{
                echo "  <tr>
                <td colspan='8'>Desculpe, mas não existem registos...</td>
            </tr> ";
            }
          
            
            $stmt_sel_prods->close();

    ?>    

But in similar ones it does work.
I’ve tried to change the query and it does not work.
I’ve also tried to do the connection in the same page, and it also does not work.

Can someone tell me what is wrong with this block of code?

Thank you all

Insert Query Working for Localhost but not Web Server

This code is Working for localhost Xampp server but not working in live Web Server Please give me Right way to execute the in live web server

    public function add_new_task($data){
        // data insert   
        $task_title = $this->test_form_input_data($data['task_title']);
        $task_description = $this->test_form_input_data($data['task_description']);
        $t_start_time = $this->test_form_input_data($data['t_start_time']);
        $t_end_time = $this->test_form_input_data($data['t_end_time']);
        $assign_to = $this->test_form_input_data($data['assign_to']);
        $assign_by = $this->test_form_input_data($data['assign_by']);
        $reviewer = $this->test_form_input_data($data['reviewer']);
        $updated_by = $this->test_form_input_data($data['updated_by']);
        $request_note = $this->test_form_input_data($data['request_note']);

        try{
            $add_task = $this->db->prepare("INSERT INTO task_info (t_title, t_description, t_start_time,    t_end_time, t_user_id, u_comment,as_user_name,rv_name,up_name) VALUES (:x, :y, :z, :a, :b, :uc, :v, :m, :q) ");

            $add_task->bindparam(':x', $task_title);
            $add_task->bindparam(':y', $task_description);
            $add_task->bindparam(':z', $t_start_time);
            $add_task->bindparam(':a', $t_end_time);
            $add_task->bindparam(':b', $assign_to);
            $add_task->bindparam(':uc', $request_note);
            $add_task->bindparam(':v', $assign_by);
            $add_task->bindparam(':m', $reviewer);
            $add_task->bindparam(':q', $updated_by);

            $add_task->execute();

            $_SESSION['Task_msg'] = 'Task Add Successfully';

            header('Location: task-info.php');
        }catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

When I am inserting the data then data is not showing in the webserver database, that is the problem. not showing any kind of data whenever I have filled data in web server and also not showing any kind of errors in the interface.
But when I am inserting the data in localhost xampp server it showing the data that I have inserted in localhost server.

How to join results as an array of objects and filter, sort and paginate them in Laravel?

I have been working a project where activities can be graded in different ways using competences. Among many, I have two tables schemas that I am working on.

Table: Activities

  1. id
  2. name
  3. isNewest //currently always 1

Table : activity_competences //link table between activities, framework_competences and sub_competences

  1. id
  2. activity_id (foreign_key)
  3. framework_competence_id
  4. master_competence_id

Table : framework_competences

  1. id
  2. name

Table : master_competences

  1. id
  2. name

I want to fetch all the activities and its corresponding competences using SQL join.
I also want the user to be able to filter and sort these results so they can only see the activities with the competence they need.

This is what I currently have.


        $paginateOffset = isset($request->paginateOffset) ? $request->paginateOffset : 0;
        $currentSort = isset($request->currentSort) ? $request->currentSort : 'id';
        $currentSortDir = isset($request->currentSortDir) ? $request->currentSortDir : 'desc';


        $activities = Activity::where('isNewest', 1)
        ->leftJoin('activity_competences', 'activities.id', '=', 'activity_competences.activity_id')
        ->leftJoin('framework_competences', 'activity_competences.framework_competence_id', '=', 'framework_competences.id')
        ->leftJoin('master_competences', 'activity_competences.master_competence_id', '=', 'master_competences.id')
        ->where(function($query) use ($request){//filter using keyword that user enters.
            $query->where('activities.name', 'LIKE','%'.$request->keyword.'%')
            ->orwhere('framework_competences.name', 'LIKE','%'.$request->keyword.'%')
            ->orwhere('master_competences.name', 'LIKE','%'.$request->keyword.'%');
        })->orderBy($currentSort, $currentSortDir)->offset($paginateOffset)->limit($paginateAmmount)
        ->get(array('activities.*', 'framework_competences.name as framework_competences', 'master_competences.name as master_competences'));


The response I get is:

[
    {
        "id": 1,
        "name": "activity1",
        "framework_competences": 'name1',
        "master_competences": 'name3',
        "isNewest": 1
    },
    {
        "id": 2,
        "name": "activity2",
        "framework_competences": 'name2',
        "master_competences": 'name4',
        "isNewest": 1
    }
]

but what I would like is:

[
    {
        "id": 1,
        "name": "manjil",
        "framework_competences": [name1, name2],
        "master_competences": [name3, name4]

    }
]

How to edit php.ini file and add extensions to 123-reg site?

I need to install the sqlsrv driver to a php site hosted on 123-reg. when I load up the website it only says: “Failed to get DB handle: could not find driver”

I can see on phpinfo() that the php.ini file is stored in a folder called etc that I can’t seem to find anywhere. The file path is “/etc/php72.ini.d/php.ini”

I also need to copy over the drivers into the extension folder which I can’t seem to find either.

How can I find php.ini or create a new one and use that. And how can I install drivers to 123 reg?

I’m using php 7.2.

Any help would be appreciated!

how to clean url from subfolders in php using .htaccess file [duplicate]

I want to remove Paramters from URL and make clean URL for SEO from example.com/eco/cur/in.php?name=an to
example.com/eco/cur/in/an. I have used so many examples but it wont work for my pages, I have sub folders like in subfolders and in the internet they give example only to root directory index pages I want sub directory example to my project. I have used HTACCESS file to remove .PHP extension but its not working for parameters. thank you

Is this the proper way to not create in each class a new PDO object in PHP OOP?

I want to use in my application PDO connection within multiple classes (objects) but the way how I tried in the past was not correct because everytime I called an object I created a new PDO object (connection) also.

Im right now using a spl_autoload_register for autoloading.

Here Is my DataBase class (I deleted from this example the connection propeties (name, host etc etc.):

DataBase.php

namespace MyApp;

use PDO;

class DataBase {
    
    public function DB_CONN() {
        try {
            $pdo = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->DB_name, $this->DB_username, $this->DB_passw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            // Set the PDO error mode to exception
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $pdo;
        }
        catch (PDOException $e) {
            die("ERROR: Could not connect. " . $e->getMessage());
            return false;
        }
    }
}

So in this example here I need a PDO connection to Customer class and I created a PDO object in the Customer constructor like this:

Customer.php

namespace MyApp;
use MyAppDataBase;
use PDO;

class Customer 
{
  private $PDO;

  public function __construct($cus_id)
  {
    $this->PDO = (new DataBase)->DB_CONN();
  }

  public function getCustomerOrders(int $id): array
  {
    $CustomerOrders = (new Orders())->getOrdersByID($id)
  }

  public function getCustomerNameByID(int $id): ?string
  {
    $stmt = $this->PDO->prepare("SELECT name FROM customers WHERE id=:id");
    $stmt->execute([":id" => $id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result["name"];
  }
}

But its not the best method because because if I need an another class in this example named Orders (which also needs a DataBase connection) then I will create an another PDO object.

Orders.php

namespace MyApp;
use MyAppDataBase;
use PDO;
class Orders
{
  private $PDO;
  public function __construct($cus_id)
  {
    $this->PDO = (new DataBase)->DB_CONN();
  }

  public function getOrdersByID(int $id): array
  {
    $stmt = $this->PDO->prepare("SELECT * FROM orders WHERE id =:id");
    $stmt->execute([":id" => $id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
  }
 }

So my question is that should I only pass the $PDO variable to the given class constructor? It will solve my problem? Like this:

try {
    $pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_username, $db_passw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("ERROR: Could not connect. " . $e->getMessage());
    return false;
}

class Customer
{
    private $PDO;

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

    public function getCustomerOrders(int $id)
    {
        $CustomerOrders = (new Orders($this->PDO))->getOrdersByID($id);
    }

    public function getCustomerNameByID(int $id): ?string
    {
        $stmt = $this->PDO->prepare("SELECT name FROM customers WHERE id=:id");
        $stmt->execute([":id" => $id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result["name"];
    }
}

class Orders
{

    private $PDO;

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

    public function getOrdersByID(): array
    {
        $stmt = $this->PDO->prepare("SELECT * FROM ORDERS WHERE ID =:id");
        $stmt->execute([":id" => $id]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

$Customer = new Customer($pdo);

print_r($Customer->getCustomerNameByID());
print_r($Customer->getCustomerOrders());

Or should I use dependency injection? Thank you!

$_SESSION variable error in second php file

I have reduced the code in both files to try and figure out what is going on.

In my first file loginuser.php, I am running the following lines:

<?php
session_start();

$_SESSION['user_id'] = "test";

// more code follows; nothing else that involved user id or session

To double check that $_SESSION variable is indeed set, I ran the following modified approach:

<?php
session_start();

$_SESSION['user_id'] = "test";

$response['success'] = false;
$response['message'] = $_SESSION['user_id'];

echo json_encode($response);
exit;

When $response[‘success’] is false, the message is printed. So at this point I know that the $_SESSION variable was indeed set and I am getting a body response.

In my second file addrelease.php, I then run the following lines to check if I am seeing the session variable even before I do anything else:

<?php
session_start();

$response['message'] = $_SESSION['user_id'];

// more code would follow but again i will force message to pop and exit
$response['success'] = false;
echo json_encode($response);
exit;

The app will toast “Error, no response” if there is no body provided in the response (I am using retrofit) and this is exactly what happens. Given this, I know that addrelease.php does not even echo the response.

To confirm my suspicion that something is going on with the $_SESSION variable, I replaced $_SESSION[‘user_id’] in addrelease.php with “test2” and now I am getting a body with the message that I forced.

Most posts that I am finding seem to resolve their issue by ensuring the session_start() is the very first thing that is called and doubling checking the session_save_path. I have looked at both of these and can’t find any issues.

Hoping someone can help me, thanks in advance!

P.S. this is all new to me so please excuse if I am making a very basic mistake somewhere.

PHP not moving files from /tmp to target dir

Trying to create a simple file depository on a LAMP stack, but whenever I upload files they won’t move from /tmp to target dir.

I can’t workout where I’m going wrong, I’m using the example code from the PHP docs:


<?php

    $uploaddir='/var/www/example.com/public_html/uploads/';
    $uploadfile=$uploaddir.basename($_FILES['userfile']['name']);

    echo'<pre>';
    if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile))
    {
        echo"File is valid, and was successfully uploaded.n";
    }
    else
    {
        echo "Possible file upload attack!n";
    }

    echo 'Here is some more debugging info:';
    print_r($_FILES);

    print "</pre>";

?>

<!-- The data encoding type, enctype, MUST be specified as below -->

<form enctype="multipart/form-data" action="index.php" method="POST">

    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />

    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />

    <input type="submit" value="Send File" />
</form>

Browser output is:


Possible file upload attack!
Here is some more debugging info:Array
(
    [userfile] => Array
        (
            [name] => Test_File.txt
            [full_path] => Test_File.txt
            [type] => text/plain
            [tmp_name] => /tmp/php1hAD8G
            [error] => 0
            [size] => 19
        )

)

and the apache error log gives the following warning:


PHP Warning:  move_uploaded_file(/var/www/example.com/public_html/uploads/Test_File.txt): Failed to open stream: Permission denied

Which I assume means that the system doesn’t believe it has permission to create the file in teh target dir. when I set up the site I used:


sudo chown -R $USER:$USER /var/www/example.com/public_html/uploads
sudo chmod -R 755 /var/www/

and I can see that the files are owned by whatever account I’m logged into on the SSH as.

I’m pretty new to this, but I assume I’ve done everything right here but I’ve made a mistakes with the permissions?

Resource not found after upgrade to Api-platform 2.7

I want to upgrade my api which currently uses PHP8.1, Symfony 6.1 and Api-Platform 2.6 to Api-Platform 3.0.
So I first upgraded to Api-Platform 2.7 and switched the metadata_backward_compatibility_layer flag to false.

All “getCollection” are in error now while all other endpoints are working normally.

The exception thrown is ApiPlatformExceptionResourceClassNotFoundException with the following message: Resource “AppEntityRatingAttribute” not found.

Here is the entity in question:

<?php

declare(strict_types=1);

namespace AppEntity;

use ApiPlatformMetadataPost;
use ApiPlatformMetadataGetCollection;
use ApiPlatformMetadataPatch;
use ApiPlatformMetadataGet;
use ApiPlatformMetadataApiResource;
use DoctrineORMMapping as ORM;

#[ORMEntity]
#[ORMTable("rating_attribute")]
#[ApiResource(
    operations: [new Get(), new Patch(), new GetCollection(), new Post()],
    paginationEnabled: false
)]
class RatingAttribute extends AbstractReadWriteProperties
{
    #[ORMId]
    #[ORMGeneratedValue]
    #[ORMColumn(type: 'integer', nullable: true)]
    private ?int $id = null;

    #[ORMManyToOne(targetEntity: Rating::class)]
    private Rating $rating;

    #[ORMColumn(type: 'string', length: 240)]
    private string $key;

    #[ORMColumn(type: 'string', length: 240)]
    private string $value;

    #[ORMColumn(type: 'bigint', length: 240)]
    private string $reviewToken;

    /**
     * @return int|null
     */
    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return Rating
     */
    public function getRating(): Rating
    {
        return $this->rating;
    }

    /**
     * @return string
     */
    public function getKey(): string
    {
        return $this->key;
    }

    /**
     * @return string
     */
    public function getValue(): string
    {
        return $this->value;
    }

    /**
     * @return string
     */
    public function getReviewToken(): string
    {
        return $this->reviewToken;
    }

    /**
     * @param Rating $rating
     *
     * @return RatingAttribute
     */
    public function setRating(Rating $rating): RatingAttribute
    {
        $this->rating = $rating;

        return $this;
    }

    /**
     * @param string $key
     *
     * @return RatingAttribute
     */
    public function setKey(string $key): RatingAttribute
    {
        $this->key = $key;

        return $this;
    }

    /**
     * @param string $value
     *
     * @return RatingAttribute
     */
    public function setValue(string $value): RatingAttribute
    {
        $this->value = $value;

        return $this;
    }

    /**
     * @param string $reviewToken
     *
     * @return RatingAttribute
     */
    public function setReviewToken(string $reviewToken): RatingAttribute
    {
        $this->reviewToken = $reviewToken;

        return $this;
    }
}

I don’t understand what can happen, the problem seems to come from the vendor/api-platform/core/src/Core/Metadata/Resource/Factory/ExtractorResourceMetadataFactory.php line 54

If I comment this part in this code :

if (!(class_exists($resourceClass) || interface_exists($resourceClass)) || !$resource = $this->extractor->getResources()[$resourceClass] ?? false) {
    return $this->handleNotFound($parentResourceMetadata, $resourceClass);
}

everything works correctly.

I can connect to localhost using mysqli_connect, but I can’t connect to any other sql server

I am trying to connect to an sql server using mysqli_connect but I keep getting either “php_network_getaddresses: getaddrinfo failed: Name or service not known” or “No connection could be made because the target machine actively refused it” or “Error while reading greeting packet”

However, when I connect to an sql on my local host, it works fine.

Here’s my php:

// details used to connect to sql database
$servername = "localhost";
$username = "root";
$password = "123";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
   die("Connection failed: " . mysqli_connect_error());
}

If I change the login details to that of any other server, it doesn’t work. What am I doing wrong?

I tried changing the details to the server ip and login details of another sever that connects fine with ssms but when I try to connect with php, it doesn’t work and throws up an error. If I can connect with ssms, why wouldn’t I be able to connect with php?

I’ve tried using php hosted on my localhost and php hosted on 123-reg, both with similar results.

How to get download link from a order in Woo-commerce?

I am trying to get download link of a product in Order data. But i am getting error.

Below is my code:

$order = new WC_Order( 206956 );

foreach ( $order->get_items() as $item_id => $item ) {

    echo $product_id = $item->get_product_id(); // product ID

    $downloads = $item->get_item_downloads();
    print_r ( $downloads );

}

I tried this solution also.

$order->get_item_downloads();

Thanks

Validate and caculate product variations shopping cart

I’m trying to validate and calculate the product variations on the shopping cart. On the frontend side the user can select/add product variations. For example extra Cheddar or mayonnaise. The variations have different prices that need to be calculated and shown on the shopping cart.

Frontend user input

When a variation is selected and I validate it at the back end, the correct variation is shown on the shopping cart (see image below).

Shopping cart with variations

Only the price for the different variations are not calculated on the totals.

When I store the price directly on the select value and do not validate it on the controller it’s calculated correctly. But then it’s possible for the user to change the price with the browser console.

Controller:

public function addToCart($id, Request $request)
{
    $product = Product::findOrFail($id);

    // Get user input from front-end
    $option = $this->option;
    $options = $this->options;

    // If option is required
    // Check if option present in model
    $option = Item::where('id', $option)->get()->toArray();

    // If multiple options possible
    // Check if options present in model
    $options = Item::where('id', $options)->get()->toArray();

    if ($product->has_options === "true") {
        if($option === null) {
            $finalOptions = $options;
        } else {
            $finalOptions = array_merge($options, $option);
        }
    } else {
        $option = $this->option;
        $finalOptions = null;
    }

    // If product has options = true calculate product variations price
    if($finalOptions) {
        $total = ($product->discount_price != '' ? $product->discount_price : $product->total_price)
            + array_sum(($finalOptions));
    } else {
        $total = ($product->discount_price != '' ? $product->discount_price : $product->total_price);
    }

    Cart::add(array(
        'id' => $product->id,
        'name' => $product->title,
        'price' => $total,
        'qty' => 1,
        'options' => array(
            $finalOptions
        ),
        'associatedModel' => $product
    ));

    $this->dispatchBrowserEvent('closeModal');
    $this->emit('cart_updated');

    foreach($this->options as &$recipient) {
        $recipient = false;
    }

    $this->option=null;
}

Blade

<select wire:model.defer="option.{{ $extra->id }}" wire:key="option-select-{{ $extra->id }}" class="form-select" required>
    @foreach($items as $item)
        @if($extra->items->pluck('id')->contains($item->id))
            <option wire:key="item--{{ $item->id }}" name="option" value="{{ $item->id }}">
                {{ $item->title }} (+€ {{ number_format((float)Str::words($item->price),2, ',', '') }})
            </option>
        @endif
    @endforeach
</select>

Anything that I’m missing?

Call to undefined function pg_query in php

ON “centOS”

<?php
$db = pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=admin123");
if($db){
    echo "connected!";
    $query = "INSERT INTO book VALUES (3,'bookName','authorName',344)";
    $result = pg_query($query);
    if($result){
            echo "inserted";
    }else{
            echo "error inserting";
    } 
}else{
    echo "error connecting";
?>

Expected output:conneted!
inserted OR error inserting

Actual output:**connected!

Fatal error: Uncaught Error: Call to undefined function pg_query() in /opt/lampp/htdocs/newplsql/connect.php:24 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/newplsql/connect.php on line 24**

Laravel datatables data range filter not working

Hi, I have a problem with filtering by date range. When I try to use table.draw() the search doesn’t work at all, but when I define a column like table.columns(8).search( this.value ).draw(); then it searches but doesn’t do a range.




I tried something like this 

`var minDate, maxDate;
 
// Custom filtering function which will search data in column four between two values
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min = minDate.val();
        var max = maxDate.val();
        var date = new Date( data[4] );
 
        if (
            ( min === null && max === null ) ||
            ( min === null && date <= max ) ||
            ( min <= date   && max === null ) ||
            ( min <= date   && date <= max )
        ) {
            return true;
        }
        return false;
    }
);
 
$(document).ready(function() {
    // Create date inputs
    minDate = new DateTime($('#min'), {
        format: 'YYYY-MM-DD'
    });
    maxDate = new DateTime($('#max'), {
        format: 'YYYY-MM-DD'
    });
 
    // DataTables initialisation
    var table = $('#example').DataTable();
 
    // Refilter the table
    $('#min, #max').on('change', function () {
         table.draw();
    });
});
`


but when i change the value nothing happens.