Can not add product to cart if sku is numeric

I’m trying to use one of the shopping cart tutorial, everything works just fine, but if product (SKU) is numeric only it does not work. Can anyone help me with this case?
I got this tutorial from source: https://www.allphptricks.com/simple-shopping-cart-using-php-and-mysql/

P.S. If I add any letter to sku for example: k00199288, it works just fine, but if I leave sku in format: 00199288, it does not see sku.

Here is the source code:

<?php
session_start();
include('../admin/config.php');
$status="";
if (isset($_POST['sku']) && $_POST['sku']!=""){
$code = $_POST['sku'];
$result = mysqli_query(
$con,
"SELECT * FROM `products` WHERE `sku`='$sku'"
);
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
$sku = $row['sku'];
$price = $row['price'];
$image = $row['image'];

$cartArray = array(
$sku=>array(
'name'=>$name,
'sku'=>$sku,
'price'=>$price,
'quantity'=>1,
'image'=>$image)
);

if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
$status = "<div class='box'>Product is added to your cart!</div>";
}else{
$array_keys = array_keys($_SESSION["shopping_cart"]);
if(in_array($sku,$array_keys)) {
$status = "<div class='box' style='color:red;'>
Product is already added to your cart!</div>";  
} else {
$_SESSION["shopping_cart"] = array_merge(
$_SESSION["shopping_cart"],
$cartArray
);
$status = "<div class='box'>Product is added to your cart!</div>";
}

}
}
?>


<?php
if(!empty($_SESSION["shopping_cart"])) {
$cart_count = count(array_keys($_SESSION["shopping_cart"]));
?>
<div class="cart_div">
<a href="cart.php"><img src="cart-icon.png" /> Cart<span>
<?php echo $cart_count; ?></span></a>
</div>
<?php
}
?>


<?php
$result = mysqli_query($con,"SELECT * FROM `products`");
while($row = mysqli_fetch_assoc($result)){
echo "<div class='product_wrapper'>
<form method='post' action=''>
<input type='hidden' name='sku' value=".$row['sku']." />
<div class='image'><img src='".$row['image']."' /></div>
<div class='name'>".$row['name']."</div>
<div class='price'>$".$row['price']."</div>
<button type='submit' class='buy'>Buy Now</button>
</form>
</div>";
}
mysqli_close($con);
?>

<div style="clear:both;"></div>

<div class="message_box" style="margin:10px 0px;">
<?php echo $status; ?>
</div>

PHP session cookie deleted on phone restart but not PC restart

I have a PHP application where the PHP session cookie is set to expire after 30 days. This works fine on a PC and it survives a PC restart, but recently my users have started complaining that they have to login again after restarting their phones. Any ideas?

I tried changing the IP address on my PC to see if that was the problem with the phone restarting, but it made no difference.

How to AJAXify WordPress Pages for Dynamic Content Loading?

I’m working on a WordPress site and I want to AJAXify the pages to improve user experience by dynamically loading content without full page reloads.

What I Want to Achieve:

I would like to load different sections of my site, such as blog posts and product pages, using AJAX when users navigate the site. This should minimize page load times and make the navigation smoother.

What I’ve Tried:

  • I’ve installed and activated the necessary jQuery scripts.
  • Added basic AJAX functionality in my theme’s JavaScript file.
  • Created a custom WordPress template to handle AJAX requests.

Issue:

Despite following several tutorials, I’m encountering issues where the content is not being loaded correctly. Sometimes the AJAX request returns the wrong data, and other times the content does not update dynamically on the page.

Code:

Here’s a simplified version of the JavaScript code I’m using:

jQuery(document).ready(function($) {
    $('a.ajax-link').click(function(e) {
        e.preventDefault();
        var href = $(this).attr('href');

        $.ajax({
            url: href,
            type: 'GET',
            success: function(data) {
                $('#content').html($(data).find('#content').html());
                history.pushState(null, null, href);
            },
            error: function() {
                alert('Failed to load content.');
            }
        });
    });
});

Matching Keys and getting value in PHP or jquery

I have two arrays
Array1

{"Colour":"RASPBERRY","Size":"11"}

and a list of products

Array2
[
  {
    "ProductID": 33043,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33043,
    "Key": "Size",
    "Value": "4"
  },
  {
    "ProductID": 33044,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33044,
    "Key": "Size",
    "Value": "5"
  },
  {
    "ProductID": 33045,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33045,
    "Key": "Size",
    "Value": "6"
  },
  {
    "ProductID": 33046,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33046,
    "Key": "Size",
    "Value": "7"
  },
  {
    "ProductID": 33047,
    "Key": "Colour",
    "Value": "RASPBERRY"
  },
  {
    "ProductID": 33047,
    "Key": "Size",
    "Value": "8"
  }
]

I have both those arrays, I need to fetch ProductID from Array2 Using the data from Array 1, the list can be thousands long, want to avoid heavy work

Below is my attempt:

 // Step 1: Group entries in array2 by ProductID
        var productDict = {};

        $.each(array2, function(index, entry) {
            var productID = entry.ProductID;
            var key = entry.Key;
            var value = entry.Value;

            if (!productDict[productID]) {
                productDict[productID] = {};
            }
            productDict[productID][key] = value;
        });

        // Step 2: Check each ProductID group against the criteria in array1
        var matchingProductIDs = [];

        $.each(productDict, function(productID, attributes) {
            var match = true;
            $.each(array1, function(key, value) {
                if (attributes[key] !== value) {
                    match = false;
                    return false; // Break out of the loop
                }
            });
            if (match) {
                matchingProductIDs.push(productID);
            }
        });

        // Output the result
        console.log("Matching Product IDs:", matchingProductIDs);
    

the above code works, but it seems heavy and would like a better solution, if anyone can help.

PHP encrypted Code uploaded in cpanel and changed users passwords to login in cpanel

Yesterday i received email, that my cpanel password changed, and contact my Provider and they send me new pass, but today same thing happened. Then i realized something went wrong. so i decided to reset pass and monitor whats going on, after few minutes i see there were 5 new php files added some day ago and the one with encrypted Php code executed on specific time, and i noticed at that time password was changed.

I tired to read other codes written in php, and checked many times how it might possible to upload code in public domain folder, there is no option to upload any files on public domain, so how it could be possible.
PHP Code here

This is how it started “.base64_decode(“JXNsMmh3bjBrLQolZzh………………6000 plus then ended k7ID8+”)); ?> like this.

which query is executed when ‘var_dump(pg_fetch_all(pg_query_params($db,’select $1=$2′,[FALSE,0])))’ is executed ;

While having reiterated some questions until now, I still fail to understand what exactly does ‘pg_query_params’ when called from PHP !!!

Having previously connected $db to a postgres database the command

var_dump(pg_fetch_all(pg_query_params($db,'select $1=$2',[FALSE,0])));

returns false as shown bellow:

array(1) {
  [0]=>
  array(1) {
    ["?column?"]=>
    string(1) "f"
  }
}

while the direct execution in pgadmin of

select false=0;

returns

ERROR:  operator does not exist: boolean = integer
LINE 1: select false=0 ;

so the question is where it is documented that the above results in false instead of in true ?

Similar questions for mysql_query_params and the corresponding dbo call.

How to fix “Link redirection” error in PHP [closed]

I added a button to the theme, I wanted it to redirect with these buttons, but it didn’t work.

My website address: https://temacim.com

.htaccess

Options +FollowSymlinks
RewriteEngine On
 
RewriteRule ^/.*$ index.php [NC]
RewriteRule ^gizlilik-politikasi.* gizlilik-politikasi.php [NC]
RewriteRule ^cerez-politikasi.* cerez-politikasi.php [NC]
RewriteRule ^kullanici-sozlesmesi.* kullanici-sozlesmesi.php [NC]
RewriteRule ^iletisim.* iletisim.php [NC]
RewriteRule ^premium.* premium.php [NC]
RewriteRule ^Tema/([0-9a-zA-z_-]+) kullanici.php?ad=$1 [QSA,L]
RewriteBase /
RewriteCond %{REQUEST_URI} ^(.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !.(css|gif|ico|jpg|js|png|swf|txt)$
RewriteRule ^kategori/([0-9a-zA-z_-]+) kategori.php?slug=$1 [QSA,L]
RewriteRule ^demo/([0-9a-zA-z_-]+)
RewriteRule ^indir/([0-9a-zA-z_-]+)

# php -- BEGIN cPanel-generated handler, do not edit
# “ea-php81” paketini varsayılan “PHP” programlama dili olarak ayarlayın.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php81 .php .php8 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

Code used in search.php and other php pages

<html>
<head>
<title>Kodeks Editör</title>
<link type='text/css' rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css' />
<style type="text/css">
@import url('https://fonts.googleapis.com/css?family=Fira+Sans+Condensed');
body {
  font-family: 'Fira Sans Condensed', sans-serif;
  -webkit-font-smoothing: antialiased;
  margin: 30vh auto 0 auto;
}
#bebuton{margin:20px auto;text-align:center}
#bebuton br{display:none}
.buton-be,.buton-be2{position:relative;display:inline-block;height:50px;width:200px;line-height:50px;padding:0;border-radius:50px;background:#fefefe;border:2px solid #0792c1;margin:10px;transition:.5s}
.buton-be2{border:2px solid #f37a0f}
.buton-be:hover{background:#0792c1}
.buton-be2:hover{background:#f37a0f}
.buton-be:hover span.circle,.buton-be2:hover span.circle2{left:100%;margin-left:-45px;background:#fefefe;color:#0792c1}
.buton-be2:hover span.circle2{color:#f37a0f}
.buton-be:hover span.keyw,.buton-be2:hover span.keyw2{left:40px;opacity:0}
.buton-be:hover span.keyw-hover,.buton-be2:hover span.keyw-hover2{opacity:1;left:40px}
.buton-be span.circle,.buton-be2 span.circle2{display:block;background:#0792c1;color:#fff;position:absolute;float:left;margin:5px;line-height:42px;height:40px;width:40px;top:0;left:0;transition:.5s;border-radius:50%}
.buton-be2 span.circle2{background:#f37a0f}
.buton-be span.keyw,.buton-be span.keyw-hover,.buton-be2 span.keyw2,.buton-be2 span.keyw-hover2{position:absolute;left:90px;text-align:center;margin:0 auto;font-size:15px;font-weight:bold;color:#0792c1;transition:.5s}
.buton-be2 span.keyw2,.buton-be2 span.keyw-hover2{color: #f37a0f;left:80px}
.buton-be span.keyw-hover,.buton-be2 span.keyw-hover2{left:80px;opacity:0}
.buton-be span.keyw-hover,.buton-be2 span.keyw-hover2{color:#fff}
</style>
</head>
<body>
<div id="bebuton">
<a href="*" class="buton-be" target="_blank">
  <span class="circle"><i class="fa fa-rocket"></i></span>
  <span class="keyw">Demo için</span>
  <span class="keyw-hover">Buraya Tıkla</span>
</a>
<a href="*" class="buton-be2" target="_blank">
  <span class="circle2"><i class="fa fa-download"></i></span>
  <span class="keyw2">İndirmek için</span>
  <span class="keyw-hover2">Buraya Tıkla</span>
</a>
</div>
</body>
</html>

The code that appears when I press the ADD THEME button on the table or home page, admin panel, etc.

<div class="mb-6">
  <label for="link" class="mb-1 block font-display text-sm text-jacarta-700 dark:text-white">Demo Linki <span class="text-red">*</span></label>
  <input type="text" class="contact-form-input w-full rounded-lg border-jacarta-100 py-3 hover:ring-2 hover:ring-accent/10 focus:ring-accent dark:border-jacarta-600 dark:bg-jacarta-700 dark:text-white dark:placeholder:text-jacarta-300" name="demo" required="">
</div>
<div class="mb-6">
  <label for="link" class="mb-1 block font-display text-sm text-jacarta-700 dark:text-white">İndirme Linki <span class="text-red">*</span></label>
  <input type="text" class="contact-form-input w-full rounded-lg border-jacarta-100 py-3 hover:ring-2 hover:ring-accent/10 focus:ring-accent dark:border-jacarta-600 dark:bg-jacarta-700 dark:text-white dark:placeholder:text-jacarta-300" name="indir" required="">
</div>
<div class="mb-4">
  <label for="message" class="mb-1 block font-display text-sm text-jacarta-700 dark:text-white">Tema Hakkında Detaylar (Admin Bilgileri, Kullanım Alanı vs)<span class="text-red">*</span></label>
  <textarea  class="contact-form-input w-full rounded-lg border-jacarta-100 py-3 hover:ring-2 hover:ring-accent/10 focus:ring-accent dark:border-jacarta-600 dark:bg-jacarta-700 dark:text-white dark:placeholder:text-jacarta-300" required="" name="ozgecmis" rows="5" placeholder="Maksimum 300 Karakter Giriniz"></textarea>
</div>
<div class="mt-4 flex items-center space-x-2">

In summary, what I want to do:

When I press the ADD THEME button on the main screen and admin panel, I want it to go to the buttons in the article when I add the links to the places where DEMO LINK and DOWNLOAD LINK are written in the opened forum.

Users are accessing each other’s account in Codeigniter when I implement WAF

The application is built with CodeIgniter 3. With in a Big corp. there are several users accounts on same public IP. Now upon implementing the WAF (Web Application Firewall), weird behavior happened.

When the users logged into their own accounts but accessed another user’s profile directly. Few users were on their mobile devices using different data networks.

I have no clue why this has started after waf added. Is there any settings with sessions? why the sessions are jumping up. Below mentioned are the sessions settings in config file.
Session are stored in DB.

$config['sess_driver'] = 'database';

$config['sess_cookie_name'] = 'ciapp_session';

$config['sess_expiration'] = 32400; //7200;

$config['sess_save_path'] = 'ci_sessions';

$config['sess_match_ip'] = FALSE;

$config['sess_time_to_update'] =60; // 300;

$config['sess_regenerate_destroy'] =  TRUE;


$config['sess_match_useragent'] = TRUE;

$config['cookie_prefix']    = '';

$config['cookie_domain']    = '';

$config['cookie_path']      = '/';

$config['cookie_secure']    = FALSE; //setting this to TRUE leading me to 429 error on user login/logout

$config['cookie_httponly']  = TRUE;

need to extract all headings which has # symbols from PDF file

I need to extract the headings of my PDF file which start with # symbols through PHP. I don’t know how to do it. Here is my PDF file link:

https://afxwebdesign.com/order.pdf

I have tried this script:

<?php
// Load the PDF file
$pdfFile = 'order.pdf';

// Use a PDF parsing library like TCPDF or FPDI to extract text
// Code snippet using TCPDF

require_once('tcpdf.php');
require_once('vendor/setasign/fpdi/src/autoload.php');

use setasignFpdiTcpdfFpdi;
$pdf = new Fpdi();
$pageCount = $pdf->setSourceFile($pdfFile);

for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
    $templateId = $pdf->importPage($pageNo);
    $text = $pdf->getPageContent($pageNo);

    preg_match_all('/^#[^#].*$/m', $text, $headings);

    foreach ($headings[0] as $heading) {
        echo $heading . "n";
    }
}

$pdf->close();
?>

But it’s not working – it throws this error:

Fatal error: Uncaught Error: Call to undefined method
setasignFpdiTcpdfFpdi::getPageContent() in
C:xampphtdocspdfextractindex.php:17 Stack trace: #0 {main} thrown
in C:xampphtdocspdfextractindex.php on line 17

Create a Deamon worker for NGINX/PHP/MariaDb on Windows

I am creating a batch script to run php-cgi, mariadb and nginx in the background when Windows launches.

Here is my script:

@echo off

set mariadb_home=C:wamp64binmariadbmariadb10.6.5bin
set php_home=C:php8.1.10
set nginx_home=C:nginx-1.27.0nginx-1.27.0

if not exist "%mariadb_home%" (
    echo The specified MARIADB directory does not exist: %mariadb_home%
    exit /b 1
)

if not exist "%php_home%" (
    echo The specified PHP directory does not exist: %php_home%
    exit /b 1
)

if not exist "%nginx_home%" (
    echo The specified NGINX directory does not exist: %nginx_home%
    exit /b 1
)

rem run php-cgi in background on port 9000
cd /d %php_home%
start /b "" "php-cgi" -b 127.0.0.1:9000

rem run mariadb in background
cd /d %mariadb_home%
start /b "" "mysqld"

rem run nginx in background
cd /d %nginx_home%
start "" "nginx"

if errorlevel 1 (
    echo Failed to start services
    exit /b 1
)

exit /b 0

Currently only two services out of three are in the background (php-cgi and nginx), but for mariadb I have a window with: “2024-06-04 13:47:19 0 [Note] mysqld (server 10.6.5- MariaDB) starting as process 15096…”.

How can I make MariaDb running in background ? The flag b seems not working as well.

Uncaught PDOException: SQLSTATE[HY093] Invalid parameter number [duplicate]

The error occurs when I try to update the ‘name’ and ‘description’ in the database.

Full error:

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in ...db.php:126 Stack trace: #0 ...db.php(126): PDOStatement->execute() #1 C:OSPaneldomainsteachappcontrollerstopics.php(76): update() #2 ...edit.php(3): include('...') #3 {main} thrown in ...db.php on line 126"

File: db.php

function update($table, $id, $params){
    global $pdo;
    $i = 0;
    $str = '';
    foreach ($params as $key => $value) {
        if ($i === 0){
            $str = $str . $key . "= '" .$value . "'";
        }else {
            $str = $str .", " . $key . " = '" . $value . "'";
        }
        $i++;
    }

    $sql = "UPDATE $table SET $str WHERE id =". $id;
    // tt($sql);
    // exit();

    $query = $pdo->prepare($sql);
    $query->execute($params);
    dbCheckError($query);
    return $pdo->lastInsertId();
}

File: topics.php

if ($name === '' || $description === ''){
        $errMsg = 'Не все поля заполнены!';
    }elseif(mb_strlen($name, 'UTF8') < 2){
        $errMsg = "Придумайте длиннее категорию";
    }else{
            $topic = [
    
                'name' => $name,
                'description' => $description
                
            ];
            $id = $_POST['id'];
            $topic_id = update('topics', $id, $topic);
            header('location: ' . BASE_URL . 'admin/topics/index.php');
        }
}

File: edit.php

<?php session_start();
      include('../../path.php');
      include("../../app/controllers/topics.php");
?>

Unfortunately, I didn’t find any similar examples.

CodeIgniter file not working on localhost – dashboard redirection

I am experiencing an issue where when I run a CodeIgniter file on localhost, I am redirected to the dashboard. I have followed the steps provided in the CodeIgniter documentation, but the issue still persists. Is there a solution to this problem?

{
    "description": "The CodeIgniter framework",
    "name": "codeigniter/framework",
    "type": "project",
    "homepage": "https://codeigniter.com",
    "license": "MIT",
    "support": {
        "forum": "http://forum.codeigniter.com/",
        "wiki": "https://github.com/bcit-ci/CodeIgniter/wiki",
        "irc": "irc://irc.freenode.net/codeigniter",
        "source": "https://github.com/bcit-ci/CodeIgniter"
    },
    "require": {
        "php": ">=5.2.4"
    },
    "suggest": {
        "paragonie/random_compat": "Provides better randomness in PHP 5.x"
    },
    "require-dev": {
        "mikey179/vfsStream": "1.1.*"
    }
}

Naming Convention for Repositories method in Laravel

function naming convention for models if using left joins and multiple data in the where clause.

class InventoryRepository implements InventoryRepositoryInterface
{
public function getDetailByEventIdAndEventDate(int $eventId, string $date)
{
$query = Inventory::select(
‘inventory.*’,
‘seat_bifurcation.id as seat_bifurcation_id’,
‘seat_bifurcation.price as eventprice’,
‘seat_bifurcation.quantity’,
‘seat_bifurcation.booked_quantity’,
DB::raw(‘(seat_bifurcation.quantity – IFNULL(seat_bifurcation.booked_quantity, 0)) as available_quantity’),
DB::raw(‘IF(NOW() > CONCAT(inventory.event_date, ” “, inventory.start_time), ” TIME IS OVER “, ” EVENT available “) as time_status’),
DB::raw(‘IF(NOW() > CONCAT(inventory.event_date, ” “, inventory.end_time), ” TIME IS OVER “, ” EVENT available “) as end_time_status’),
‘event.enable_booking_during_bookingtime’
)
->leftJoin(‘seat_bifurcation’, ‘inventory.id’, ‘=’, ‘seat_bifurcation.inventory_id’)
->leftJoin(‘event’, ‘event.event_id’, ‘=’, ‘inventory.event_id’)
->where(‘inventory.event_id’, $eventId)
->where(‘inventory.event_date’, ‘>=’, $startDate)
->groupBy(
‘inventory.start_date’,
‘inventory.end_date’,
‘inventory.start_time’,
‘inventory.end_time’
)
->orderBy(‘inventory.id’, ‘ASC’)
->get();

    return $query;
}

}

public function getDetailByEventIdOrDate(int $eventId, string $date)
{}

Refactoring DB::raw() to DB::raw()->getValue(DB::connection()->getQueryGrammar()) in Laravel 10

i migrate from Laravel 8 to Laravel 10 so i used in whole project DB::raw(). in laravel 10, DB::raw() does not work must use DB::raw()->getValue(DB::connection()->getQueryGrammar())
how can i refactor this in all of my project about 35 files and 135 usage in my project

i used this package but have an error : https://github.com/remarkablemark/rector-laravel-database-expressions

PHP Fatal error: Uncaught RuntimeException: Unable to create the Doctrine Proxy directory on SuiteCRM clean installation

i had a problem with a dockerized SuiteCRM 8.6 fresh installation that return everytime i try to rebuild the cache from user interface:

PHP Fatal error: Uncaught RuntimeException: Unable to create the Doctrine Proxy directory “/bitnami/suitecrm/cache/prod/doctrine/orm/Proxies”.

After too many days of testing i realized that the problem seems to be related to a incompatibility between SuiteCRM (Symphony) and Docker’s bind mount.

I have tested in different ways:

  1. Permissions and file ownership are double-checked. Keep in mind that cache rebuilding from UI is started by apache user (www-data), and file ownership and group is www-data:www-data.

  2. The problem is present everytime i work with docker’s bind mount, but strangely works perfectly if i try with bitnami official release without bind mount. If i set bind mount in this installation, the problem occurs again.

I have asked for help on Official Support Forum here and GitHub with no luck.

Anyone have an idea about how solve this problem?

Thanks in advance.