How to join 3 tables with group_concat

I am using Cubecart for a customer website, and frustratingly they have used comma separated values to associate certain option IDs to products. I now need to create a custom table which gets all this information out into a useful format so that I can assign different product codes for varying combinations of product options.

I have simplified the content to make it easier to understand.

**Products Table**

Product ID   Product Code    Assign Key
1            ABC             23,45
1            HIJ             23
1            KLM             45
2            DEF             10,28
2            GHI             10
2            NOP             28

**Assign Table** 

Product ID  Assign ID     Value ID
1           23            1
1           45            2
2           10            3
2           28            4

**Values Table**

Value ID    Value
1           Red
2           Large
3           Blue
4           Small

I can work out how I would connect the products table directly to the values table, if the assign Keys were actually value IDs, but I can’t work out how to do it with the assign table in the middle. I need to connect products to assign and assign to values.

SELECT 
t1.product_code, 
t1.product_id,
t1.assign_key,
GROUP_CONCAT(t2.value_name)
FROM products t1 
LEFT JOIN values t2 ON FIND_IN_SET(t2.value_id, t1.assign_key)    
GROUP BY t1.assign_key

Expected output would be:

Product ID   Product Code    Values
1            ABC             Red, Large
1            HIJ             Red
1            KLM             Large
2            DEF             Blue, Small
2            GHI             Blue
2            NOP             Small

I tried adding another join in the middle, but cannot work out how to group concat twice.

HELP!

The delete button does not work correctly

I want that when you press delete incident, an alert will appear to make sure that it is deleted or not, the problem is that whenever I press cancel, the incident is deleted. Can somebody help me?

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Si se ha pulsado el boton de eliminar incidencia
if (isset($_POST["eliminarInci"])) {
  // Capturamos el valor de $codTarea del campo oculto del formulario
  $codTarea = $_POST["codigoTarea"];
  // Borramos la tarea seleccionada
  require_once('funciones/conexion.php');
  try {
    $deleteIncidencia = "DELETE FROM tareas WHERE COD_TAREA = ?";
    $preparada = $db->prepare($deleteIncidencia);
    $preparada->execute(array($codTarea));
    // Cuando la consulta se ejecute se elimina
    if ($preparada) {
      print "
        <script>
          var result = window.confirm('¿Seguro que quieres borrar esta incidencia?');
          if(result){
            window.location = 'admin.php';
          }
          else{
            window.location = 'admin.php';
          }
        </script>";
        exit;
    }
  } catch (Exception $e) {
    echo "Error: " . $e->getMessage();
  }
}
}
?>

Automatic update of priority of table rows on new entries

I need to create a table of entries with list of people for webpage, where each row corresponding to one person. Each one needs to be given a priority number let us say 1 to 50 i.e., each person will have a priority number. One entry per row is dedicated for this. If a new person is added to the table row and given a priority number 3, all the other persons with priority from 3 to 50 should automatically change to 4 to 51 as new person’s priority is above all these. Please help me with the code for this.

I have no clue on what to do.

Array sorting by descending numeric value pair in php

I am solving a problem with php. I have bigrams in a table on localhost. I enter a lemma into the page and search for bigrams, or just collocations + logDice association measure. Finally i want to dump it. I wrote:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <form action="kolokace.php" method="post" style="float: left;">
        <input type="text" name="xaverius" placeholder="Svatý Xaverius" style="margin-bottom: 7px;"><br>
        
        <input type="submit" name="logDice" value="logDice" style="padding: 2px 3px; color: green; font-weight: bold;">
</form>


<div style="float: left; margin-left: 5rem;">
<!--xaverius-->
<?php
    if (isset($_POST["logDice"])){
        if ($_POST["xaverius"]){
            $lemma = $_POST["xaverius"];
            $conection = mysqli_connect("localhost", "root", "", "asociation");
            mysqli_set_charset($conection, "utf8mb4");
            $sql = "SELECT DISTINCT LOWER (word2) AS word2 FROM xaveriusbigramy WHERE word1='".$lemma."'";
            $result_kolokace = mysqli_query($conection, $sql);  
            if (mysqli_num_rows($result_kolokace) > 0){
                while ($radek_kolokace = mysqli_fetch_assoc($result_kolokace)){
                    
                    $kolokace = $radek_kolokace["word2"]; // pravé kolokace - seznam
                    
                    $mysql1 = "SELECT COUNT(word1) as w1 FROM xaveriusbigramy WHERE word2='".$kolokace."'";
                    mysqli_set_charset($conection, "utf8mb4");
                    $result = mysqli_query($conection, $mysql1);  
                    if (mysqli_num_rows($result) > 0){
                        while ($radek = mysqli_fetch_assoc($result)){
                            $freq_w1 = $radek["w1"]; // frequency of collocations

                        }
                    }

                    $mysql2 = "SELECT COUNT(word2) as w2 FROM xaveriusbigramy WHERE word1='".$lemma."'";
                    mysqli_set_charset($conection, "utf8mb4");
                    $result2 = mysqli_query($conection, $mysql2);  
                    if (mysqli_num_rows($result2) > 0){
                        while ($radek2 = mysqli_fetch_assoc($result2)){
                            $freq_w2 = $radek2["w2"]; // frekvence lemmatu, který zadávám 
                        }

                    $mysql3 = "SELECT COUNT(id) as id FROM xaveriusbigramy WHERE word1='".$lemma."' AND word2='".$kolokace."'";
                    mysqli_set_charset($conection, "utf8mb4");
                    $result3 = mysqli_query($conection, $mysql3);  
                    if (mysqli_num_rows($result3) > 0){
                        while ($radek3 = mysqli_fetch_assoc($result3)){
                            $freq_w3 = $radek3["id"]; // frequency of bigrams 
                        }
                    
                    // COUNTING logDice
                    $logDice = 14+log(2*$freq_w3/$freq_w2+$freq_w1); // logDice value
                    $logDice_round = round($logDice, 2);

                    $pole = array($kolokace=>$logDice_round); 
                     
                    foreach($pole as $key => $val){
                        $pole[$key] = floatval($val);
                        }
                    
                    arsort($pole);

                    echo $kolokace.$logDice_round."<br>";

                        }
                    }
                } 
            }
        }    
    }

?>
</div>


    
</body>
</html>

It does print what I want, but the problem is that the table is not sorted by numeric values. See:

enter image description here

Thank you for any help.

is laravel handle race condition

Today I wrote 2 of the same codes in laravel and simple PHP without a framework to check race conditions. In simple PHP code, race condition happens when I send requests concurrently by the Jmeter tool but in the same scenario, laravel has no race condition problem.

I want to ensure that. Is laravel handling race conditions on its own?

this is simple PHP:

 
<?php

if(empty($_GET['name'])){
    exit('name is required');
}

try {
    $conn = new PDO("mysql:host=localhost;dbname=databasename", 'user', 'pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (?,?,?)");


    $numRowsStmt = $conn->prepare("Select * from users where name = ?");
    $numRowsStmt->execute([$_GET['name']]);

    $numRows = $numRowsStmt->rowCount();


    if($numRows <= 0){





        $name = $_GET['name'];
        $email = rand(100,50000) . '@gmail.com';
        $pass = 'password';

        $stmt->execute([$name,$email,$pass]);

        exit('user created');
    }

    exit('user exists');

} catch(PDOException $e) {

    echo $e->getMessage();
}

this is laravel:

Route::get('/100/{name}', function (Request $request, $name) {


    $r = Validator::make(compact('name'), ['name' => 'unique:users,name']);

    if ($r->fails()) {
        exit('its exist');
    };


    User::create(['name' => $request->name, 'email' => rand(100, 80000) . '[email protected]', 'password' => IlluminateSupportFacadesHash::make(rand(100,50000)),]);

});

I know these codes are not clean I use this only to test what I want the other things are unnecessary. thanks.

Inserting multiple rows into MySQL when creating a new product in PHP for multi-location sales

I’m working on a stock management system USING PHP,Mysql,Jquery everything works fine but i cant get figured out how to create multiple MYSQL rows with php when creating a new product.

I do have 3 tables since i have a product at different sales locations here are my tables

// product table
SELECT pro_id, pro_name, pro_buy, pro_sell, pro_status FROM pro_set

// product locations
SELECT loc_id, loc_name, loc_status FROM pro_loc

// product quantity table
SELECT id, pro_id, loc_id, pro_qty FROM pro_qty

Now i am trying to get it work that if i do create a new product, it will create 5 rows in table pro_qty with my location id’s inside the pro_qty.loc_id since i have 5 locations.

yii2 sql migration overwrite newly changed records

I’m trying to create a migration that changes the records I need in a table

$sql = '';

$sql .= "UPDATE card_series SET Code = 903 WHERE ID = 1600;";

$cardsSeries1600 = CardList::find()
            ->where(['seriesId' => 1600])
            ->orderBy('ID')
            ->all();
        $cardNum = 2;

        foreach ($cardsSeries1600 as $card) {
                $number = str_pad($cardNum, 8, "0", STR_PAD_LEFT);
                $cardId = (1903).$number; 
                $sql .= "UPDATE card_list SET ID = ".$cardId.", Code = '903', Number = '".$number."' WHERE ID = ".$card->ID.";";

                $cardNum++;
        }
        $this->execute($sql);

But in the end, my migration works in such a way that at first all my necessary records change, but then immediately they change to even newer ones, here is an example

UPDATE card_series SET Code = 903 WHERE ID = 1600;UPDATE card_list SET ID = 190300000002, Code = ‘903’, Number = ‘00000002’ WHERE ID = 1111000005;UPDATE card_list SET ID = 190300000003, Code = ‘903’, Number = ‘00000003’ WHERE ID = 1111000011;UPDATE card_list SET ID = 190300000004, Code = ‘903’, Number = ‘00000004’ WHERE ID = 190300000002;UPDATE card_list SET ID = 190300000005, Code = ‘903’, Number = ‘00000005’ WHERE ID = 190300000003;

How can this be fixed?

Getting fetch_assoc() error after implementing script

i bought a website one year ago. And now i created a real-time chat script with php it works well on test website. But when i try to upload on my main website i am gettin “Error: Call to a member function fetch_assoc()” error. Whats causes the error i couldnt find it or is there a way to fix it?

Chat has login and register inputs and its connected to my main database that created one year ago.
Database connecting successfully, so the problem is something else.
Here is my index.php code

<?php
require 'php/database.php';
session_start();

if(isset($_SESSION['user']) && $_SESSION['user'] == true) {
    $query = "INSERT INTO online_status (user_id, status) VALUES (".$_SESSION['userdata']['id'].", 1)";
    mysqli_query($db, $query);
}

if(empty($_GET['toUser'])) {
    header("Location: ?toUser=NULL");
    exit;
}

if(isset($_GET['toUser'])) {
    $toUserId = $_GET['toUser'];
    $select = "SELECT * FROM users WHERE id = $toUserId";
    $query = $db->query($select);

    if($query && $query->num_rows > 0) {
        $row = $query->fetch_assoc();
        // Rest of your code handling the query result
    } elseif($toUserId == "NULL") {
        // Handle case when toUser is explicitly set to NULL
    } else {
        header("Location: ?toUser=NULL");
        exit;
    }
}

if(isset($_POST['search_input'])) {
    $user = strip_tags($_POST['search_user']);
    $select = "SELECT * FROM users WHERE full_name = '$user'";
    $query = $db->query($select);

    if($query && $query->num_rows > 0) {
        $row = $query->fetch_assoc();
        // Rest of your code handling the query result
        header("Location: ?toUser=".$row['id']);
        exit;
    }
}
?>

Error log is

PHP Warning:  mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in /home/xxxx/public_html/chatsystem/index.php on line 280
PHP Notice:  Trying to access array offset on value of type null in /home/xxxx/public_html/chatsystem/index.php on line 281

And here is the another error on db folder

PHP Warning:  mysqli_fetch_all() expects parameter 1 to be mysqli_result, bool given in /home/xxxx/public_html/chatsystem/php/function.php on line 70
PHP Warning:  count(): Parameter must be an array or an object that implements Countable in /home/xxxx/public_html/chatsystem/php/function.php on line 71

Also checked PHP modules and it seems correct to me. Changed mysqli to mysqlnd but problem still exists.

Stripe: Network error [errno 92]: HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)

Laravel serves as my backend, and I use vue as my frontend. The following issue is thrown when my vue app sends a payment request to Stripe using Laravel:

Unexpected error communicating with Stripe. If this problem persists, let us know at [email protected]. (Network error [errno 92]: HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1))

I read through the many responses here, but I was unable to find the right remedy to this problem.

One thing is that my web application was running on EC2 before I switched to ECS Farget; while it was running smoothly on the EC2 server previously, when a payment is made using the ECS above, an error is generated.

I reached out to AWS and Stripe Support, but I haven’t yet received the right answer.

Intergrating background images on PHPRad

Good Day Everyone, I have a PHPrad project I am working on, I am fairly new to PHPRad so I am struggling a bit with my html canvas tag.

Problem

I am using custom view option to add ny script tag and it does not seem to work. I am also using a custom HTML Page. I want to add an html 5 canvas tag and set its background to an image I uploaded online, When I do so, nothing shows up and despite trying to prevent the drawing and erasing button from automatically submitting the form when clicked, the buttons do submit the form

Here is the Code.
HTML

`<div class="canvases">
                <!-- Corolla Canvas -->
                <div class="corolla-canvas">
                  <input type="hidden" name="corolla_data" value="" />
                  <div class="buttons-container">
                    <button id="corollax-draw" class="form-button">
                      Free Drawing
                    </button>
                    <button id="corollax-remove" disabled="disabled">Remove</button>
                  </div>
                  <canvas
                    id="corolla-canvas"
                    width="650px"
                    height="330px"
                    name="corolla_data"
                  ></canvas>
                </div>
                  </canvas>
                </div>
`

javascript

<script>

alert('testing if the script is well connected')


const canvas = document.getElementById("corolla-canvas");
const ctx = canvas.getContext("2d");

const img = new Image();
img.src = "https://i.ibb.co/QF5k508/Removal-69.png";
img.onload = function () {
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};

let isDrawing = false;
let isErasing = false;

const drawButton = document.getElementById("corollax-draw");
const removeButton = document.getElementById("corollax-remove");

drawButton.addEventListener("click", function () {
  removeButton.disabled = false;
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  canvas.addEventListener("mousedown", startDrawing);
  canvas.addEventListener("mousemove", draw);
  canvas.addEventListener("mouseup", endDrawing);
});

removeButton.addEventListener("click", function () {
  drawButton.disabled = false;
  ctx.globalCompositeOperation = "destination-out";
  canvas.addEventListener("mousedown", startErasing);
  canvas.addEventListener("mousemove", erase);
  canvas.addEventListener("mouseup", endErasing);
});

function startDrawing(e) {
  isDrawing = true;
  ctx.beginPath();
  ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
}

function draw(e) {
  if (isDrawing) {
    ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
    ctx.stroke();
  }
}

function endDrawing(e) {
  isDrawing = false;
}

function startErasing(e) {
  isErasing = true;
  ctx.beginPath();
  ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
}

function erase(e) {
  if (isErasing) {
    ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
    ctx.stroke();
  }
}

function endErasing(e) {
  isErasing = false;
  ctx.globalCompositeOperation = "source-over";
}

drawButton.addEventListener("click", function (event) {
  event.preventDefault();
  removeButton.disabled = false;
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  canvas.addEventListener("mousedown", startDrawing);
  canvas.addEventListener("mousemove", draw);
  canvas.addEventListener("mouseup", endDrawing);
});

removeButton.addEventListener("click", function (event) {
  event.preventDefault();
  drawButton.disabled = false;
  ctx.globalCompositeOperation = "destination-out";
  canvas.addEventListener("mousedown", startErasing);
  canvas.addEventListener("mousemove", erase);
  canvas.addEventListener("mouseup", endErasing);
});


</script>

Here are my image of how it all looks when I preview it.. I want the image to show and the draw and remove buttons to function acordingly instead of submitting the form:

The GET method is not supported for this route. Supported methods: POST. Error only occurs on mobile but works fine on PC?

I am getting this particular error that only exists on mobile..
The idea of this function is that the user can convert one risk to another type of risk. The get method will get the ID of the first type of risk, then the target register.
Then the post will convert this risk into another type of risk.
This works fine on PC. However, on mobile I get this error and I just can’t make sense of it.

Below is my routes.
enter image description here

And this is the error I am getting.
enter image description here

Can anyone help me understand why this error only occurs on mobile yet works perfectly on PC?
I’d expect it to work fine on both.

Invalid json response laravel api’s

I have written the api`s for mobile applications in the laravel framework. I deployed my code on the domain for a few days API’s worked fine but after a few days I received javascript tags in the response due to which my application crashed or not performed correctly, I have been facing this issue for many days but I did not found any proper solution to resolve this issue. Recommend any best solution that solves my problem permanently.

enter image description here

I have attached the postman json response screen shot

Image source not readable Laravel

I want to upload image from base64 image in two version, one 250px another 650px with watermark and it give me back an error: Image source not readable

    $path = public_path().'/seller/uploads/'. $seller->id .'/'. $adsid;  
    $watermark = public_path().'/watermark.png';
    $Image = explode(";base64,", $img);
    $ImageName = $date;
    $ImageDecode = base64_decode($Image[1]);
    $thumb_name = $ImageName.'-thumb.jpg';
    $resize_name = $ImageName.'-resized.jpg';

Image::make($ImageDecode)->encode('jpg', 80)->orientate()->resize(250, null, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$thumb_name);

Image::make($ImageDecode)->encode('jpg', 80)->orientate()->resize(650, null, function ($constraint) {
$constraint->aspectRatio();
})->insert($watermark, 'bottom-right', 10, 10)->save($path.'/'.$resize_name);

Error:

exception: “InterventionImageExceptionNotReadableException”
file:
“E:vendorinterventionimagesrcInterventionImageAbstractDecoder.php”
line: 351 message: “Image source not readable”

What I have missed?

xampp 
PHP Version 8.1.12
Laravel Framework 8.83.23

How to create a WooCommerce single product custom field I can enter unique HTML into and have it display on product page(s) via Astra Theme hook?

I’m looking to create a custom field I can enter unique HTML into for each unique WooCommerce product as required, and have the HTML render and display in an Astra theme hook on the single product page(s).

Here is the code I’ve managed to put together so far, but it isn’t working, what am I doing wrong?

/**
* Add custom text field to product page
* Only for display on the front-end, not carried over to cart, checkout, or order meta
*/

// Add custom field to product in backend
add_action( ‘woocommerce_product_options_general_product_data’, ‘cfwc_create_vc_custom_field’ );
function cfwc_create_vc_custom_field() {
woocommerce_wp_textarea_input( array(
‘id’ => ‘view_collection_text_field’,
‘label’ => __( ‘View Collection’, ‘cfwc’ ),
‘class’ => ‘cfwc-vc-custom-field’,
‘desc_tip’ => true,
‘description’ => __( ‘Enter your data.’, ‘ctwc’ ),
) );
}

// Save custom field value
add_action( ‘woocommerce_process_product_meta’, ‘cfwc_save_vc_custom_field’ );
function cfwc_save_vc_custom_field( $post_id ) {
$post = wc_get_product( $post_id );
$view_collection_field_value = isset( $_POST[‘view_collection_text_field’] ) ? $_POST[‘view_collection_text_field’] : ”;
$product->update_meta_data( ‘view_collection_text_field’, wp_kses_post( $view_collection_field_value ) );
$product->save();
}

// Display custom field on single product pages
add_action( ‘astra_woo_single_title_after’, function() {
$view_collection_field_value = get_post_meta( get_the_ID(), ‘view_collection_text_field’, true );
if ( $view_collection_field_value ) {
echo ” . wp_kses_post( $view_collection_field_value ) . ”;
}
} );