You don’t have permission to access / on this server. Additionally, a 403 Forbidden

When I open website “You don’t have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.”
moodle setup on apache in cent os 7.9
Permission given chmod -R 777 /var/www/html/moodle/
chwon -R root:root /var/www/html/moodle

Permission given chmod -R 777 /var/www/html/moodle/
chwon -R root:root /var/www/html/moodle

How to integrate recommendation system into my website? [closed]

i have gather the dataset and cleaned them . I have also trained it . Now i wanna integrate it in my website . Any idea how to do it? Im a newbie

I have try many ways but its hard . Someone of my friends suggested to use Flask , can you give me any other options? I have use PHP , javascript , css and html .

Generate an HTML table in PHP with cells that span several rows

I wanted to achieve similar result as shown in below image.

Expected result:
enter image description here

Question: Looking for php html solution to create dynamic table along with Rowspan. I am facing issue to get the parent row and add the rowspan.

Your help is much appreciated.

Here is my php array data:

<?php
// Data dari database
$data = [
    [
        'nama' => 'Asyah',
        'hobi' => ['Bola', 'Voly', 'Renang'],
        'umur' => '10 Tahun',
        'keahlian' => ['Bernyanyi', 'Menari']
    ],
    [
        'nama' => 'Rian',
        'hobi' => ['Bola'],
        'umur' => '10 Tahun',
        'keahlian' => ['Main musik', 'Menari']
    ],
    [
        'nama' => 'Boby',
        'hobi' => ['Basket', 'Voly'],
        'umur' => '10 Tahun',
        'keahlian' => ['Bernyanyi', 'Menari', 'Coding']
    ]
];

?>

This is the script that I have tried:

<?php

// Fungsi untuk menghitung jumlah rowspan
function getRowspan($data) {
    $total = 0;
    foreach ($data as $item) {
        $total += max(count($item['hobi']), count($item['keahlian']));
    }
    return $total;
}
?>

<table border="1">
    <thead>
        <tr>
            <th>Nama</th>
            <th>Hobi</th>
            <th>Umur</th>
            <th>Keahlian</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($data as $item): ?>
            <?php $rowspan = max(count($item['hobi']), count($item['keahlian'])); ?>
            <tr>
                <td rowspan="<?php echo $rowspan; ?>"><?php echo $item['nama']; ?></td>
                <td><?php echo implode('</td></tr><tr><td>', $item['hobi']); ?></td>
                <td rowspan="<?php echo $rowspan; ?>"><?php echo $item['umur']; ?></td>
                <td><?php echo implode('</td></tr><tr><td>', $item['keahlian']); ?></td>
            </tr>
            <?php for ($i = 1; $i < $rowspan; $i++): ?>
                <tr>
                    <td><?php echo isset($item['hobi'][$i]) ? $item['hobi'][$i] : ''; ?></td>
                    <td><?php echo isset($item['keahlian'][$i]) ? $item['keahlian'][$i] : ''; ?></td>
                </tr>
            <?php endfor; ?>
        <?php endforeach; ?>
    </tbody>
</table>

PHP: Perform multiple asynchronous HTTP requests. Can a code like this work?

can a code like this perform curl execution in parallel and in background, while the responses get handled in sequence on foreground?

<?php

$urls      = array(...
);
$n_handles = 4;

$processResult=function ($content){
    echo $content;
};
$handleError=function ($error){
    print_r($error);
};

/**
 * Perform multiple asynchronous HTTP requests.
 *
 * @param int $n_handles Number of concurrent handles.
 * @param array $urls URLs to request.
 * @param callable $processResult Callback for processing successful responses.
 * @param callable $handleError Callback for handling errors.
 * @return void
 */
function multi_request(int $n_handles, array $urls, callable $processResult, callable $handleError)
: void
{
    $multiHandle = curl_multi_init();
    $toProcess   = 0;
    while ($toProcess < $n_handles && !empty($urls)) {
        $handle = curl_init();
        if (!$handle || curl_setopt_array($handle, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_URL            => array_pop($urls)
            ]) !== true) {
            $handleError('Failed to initialize or set options for cURL handle');
            continue;
        }
        if (curl_multi_add_handle($multiHandle, $handle) !== CURLM_OK) {
            $handleError('Failed to add cURL handle to multi handle');
            curl_close($handle);
            continue;
        }
        $toProcess++;
    }
    
    // Process responses asynchronously.
    $processResponses = function () use (
        &$urls, &$toProcess, $multiHandle, $processResult, $handleError
    ) {
        while ($info = curl_multi_info_read($multiHandle)) {
            $handle = $info['handle'];
            if ($info['result'] == CURLM_OK) {
                $content = curl_multi_getcontent($handle);
                $processResult($content);
            } else {
                $handleError(curl_error($handle));
            }
            if (empty($urls)) {
                $toProcess--;
                curl_multi_remove_handle($multiHandle, $handle);
                curl_close($handle);
                continue;
            }
            curl_reset($handle);
            curl_setopt($handle, CURLOPT_URL, array_pop($urls));
        }
    };
    
    while ($toProcess > 0) {
        curl_multi_exec($multiHandle, $running);
        curl_multi_select($multiHandle);
        $processResponses();
    }
    curl_multi_close($multiHandle);
    
}

multi_request($n_handles, $urls, $processResult, $handleError);

i need it to create multiple connection to the same site to download and upload a sequence of file.
My hope is to maximize bandwidth usage, should it work?
is there a better solution to achieve parallelism on php?

Auth::user() returns null, but works in the function that Auth::login() called

Laravel does not save my session after auth()->login()

Hello. I’m using Socialite to create Google login in Laravel application, the redirect and callback functions worked fine. But I am having some trouble in login session, Laravel did not save my session after calling Auth::login(), and Auth::user() returns null, but Auth::user() still works in the function (controller action) where Auth::login() called. Can someone help me?

class LoginController extends Controller
{
    public function callback(Request $request) {
        $googleUser = Socialite::driver('google')->user();
        $userLogin = [
            'id' => $googleUser->getId(),
            'name' => $googleUser->getName(),
            'email' => $googleUser->getEmail(),
            'avatar' => $googleUser->getAvatar(),
        ];
        $email = $userLogin['email'];
        $user = User::updateOrCreate(
            ['email' => $email],
            $userLogin
        );
        auth()->login($user);
        // This still working.
        // dd(auth()->user());
        return redirect()->route('debug');
    }
}

But it wasn’t work in another controller action

class DebugController extends Controller {
    public function __invoke() {
        $user = auth()->user();
        // This returns null
        dd($user);
    }
}

Ensuring Prompt Response Recognition in TelegramBot API Using PHP

When utilizing the TelegramBot API in PHP, I aim to prompt users for their name and age during onboarding. Initially, I ask for their name using the following code:


$bot->command('start', function ($message) use ($bot) {
    $bot->sendMessage($message->getChat()->getId(), "What's your name?", null, false, null);
});

Subsequently, I handle any input received:

$bot->on(function (TelegramBotApiTypesUpdate $update) use ($bot) {
    $message = $update->getMessage();
    $id = $message->getChat()->getId();
    $bot->sendMessage($id, 'Your name: ' . $message->getText());
}, function () {
    return true;
});

The concern arises regarding discerning whether the input corresponds to my prompt, as users can type at any time. How can I reliably identify if the input is in response to my question?

Analyzed the context of incoming messages to determine if they follow a logical sequence from your prompt

Php CURL cookie with 24-hour session

I have a curl script that takes data from my personal account on another site, the problem is that the script works only 24 hours (the session on the site is set to 24 hours), when 24 hours pass my script no longer works and I get a response that the session is out of date. how do I update the session in curl every 24 hours?


$ch = curl_init();
$post_field = 'ajax=SearchArticulo&cntrSgn=DeExMEkRabGEO396gOLDMqUZiXe2BibRjqgUXwZlQmMgrw4jJmdAwbUD11%2BddBhn&srcInicio=false&isSimple=false&codMarca=0&field=nombre&value=&oferta=false&pvpSubido=False&detallada=false&codPedido=';
$post_field .= '&cat1=5&cat2=65&cat3=363&token=';
curl_setopt($ch, CURLOPT_URL, 'https://E8029:[email protected]/WebForms/Clientes/GenerarPedidosVentas_new.aspx');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field);
curl_setopt($ch, CURLOPT_USERAGENT, 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36');
curl_setopt ($ch, CURLOPT_REFERER, 'https://E8029:[email protected]/WebForms/Clientes/GenerarPedidosVentas_new.aspx');
curl_setopt($ch, CURLOPT_COOKIEJAR, $_SERVER['DOCUMENT_ROOT'].'/modules/heallyimport/cookie_actibios.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, $_SERVER['DOCUMENT_ROOT'].'/modules/heallyimport/cookie_actibios.txt');
curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Connection: Keep-Alive'
));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
$dom = new DOMDocument();
$dom->loadHTML($result);
$tables = $dom->getElementsByTagName('table');
$table_array = array();
foreach ($tables as $table) {
    $rows = $table->getElementsByTagName('tr');
    foreach ($rows as $row) {
        $cols = $row->getElementsByTagName('td');
        $row_array = array();
        foreach ($cols as $col) {

            $row_array[] = $col->nodeValue;
        }
        $table_array[] = $row_array;
    }
}

$products = [];
foreach ($table_array as &$item) {

    curl_setopt($ch, CURLOPT_URL, 'https://E8029:[email protected]/WebForms/Clientes/Indicacion.aspx?cp='.$item[0]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "ajax=GetIndicacion&codArticulo=".$item[0]);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $_SERVER['DOCUMENT_ROOT'].'/modules/heallyimport/cookie_actibios.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, $_SERVER['DOCUMENT_ROOT'].'/modules/heallyimport/cookie_actibios.txt');
    curl_setopt ($ch, CURLOPT_REFERER, 'https://E8029:[email protected]/WebForms/Clientes/GenerarPedidosVentas_new.aspx');
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_COOKIESESSION, false);
    $page_content = preg_replace('/<(pre)(?:(?!</1).)*?</1>/s','',curl_exec($ch));
    $desc = explode(':',$page_content);

    $description = str_replace(",'marca'","",$desc[3]);
    $description = str_replace("'", "", $description);
    $name = str_replace("xc2xa0",' ',$item[1]);
    $name = trim($name);

    $products[] = [
        'ref' => $item[0],
        'name' => $name,
        'cat1' => 'COSMÉTICA E HIGIENE',
        'cat2' => 'Salud bucodental',
        'cat3' => 'Hilo dental e interdentales',
        'image' => 'https://E8029:[email protected]/WebForms/Controls/imgArticulo.aspx?ca='.$item[0],
        'stock' => $item[5],
        'desc' => $description,
        'brand' => $item[2],
        'price1' => floatval($item[6]),
        'price2' => floatval($item[7])
    ];
    unset($item[8]);
    unset($item[9]);
    unset($item[10]);
}
echo json_encode($products); ```

TCPDF images automatically render next page when it has enough space

frist row genarate corectlly .
enter image description here

But when it comes 2nd row each image list in next page .
enter image description here

   $x=10;
   $y=$grandNextY+2;
   $width=46;
   $height=46;
   if($order_files){
    foreach ($order_files as $image) {
        //https://smarterappliances.co.uk/uploads/orders/82013/6631ffc3c212f.jpeg
        $imagePath = base_url('uploads/orders/image.jpg');
        $pdf->listImage($imagePath, $x, $y, $width, $height);
        $x +=48;
        if( $x > 180 ){
        $y += 48;
        $x=10;
        } 
    }
   }

   public function listImage($imagePath, $x, $y, $width, $height){
    
        $this->Image($imagePath, $x, $y, $width, $height);
   }

I need 2nd row make same as 1st row.

PHP won’t post image data

Okay so I’m working on a program that takes canvas data, takes a screenshot, adds in in a text box, and posts it to htdocs/creations/random number.xml. It posts some subbmited data; but not the model tag.

The model tag gets the JSC3D (I know no one here has ever heard of that; that has nothing to do with the problem) data from the text box I talked about and adds it should add it as <model>image data</model>. But instead it outputs the model tag as </model>. No opening tag or data; just </model>.

Here’s my PHP code:

<?php
$errors = array();

if(isset($_POST['save'])){

    $canvas = $_POST['img_text'];

    $username = $_SESSION['username'];

    $model_id = rand(1, 10000);

    $model_name = $_POST['name'];

    $model_description = $_POST['description'];

    if(file_exists('../creations/' . $model_id . '.xml')){
        $errors[] = 'Random model ID already exists. Please try saving again';
        }

    if($model_name == '') {
        $errors[] = 'Model name is blank';
    }

    if($model_description == ''){
        $errors[] = 'Description is blank';
        }

        if(count($errors) == 0){
            $xml = new SimpleXMLElement ('<creation></creation>');

            $xml->addChild('model', $canvas);

            $xml->addChild('id', $model_id);

            $xml->addChild('name', $model_name);

            $xml->addChild('description', $model_description);

            $xml->asXml('../creations/' . $model_id . '.xml');

            header('Location: index.php');
        }
            
}
?>
<!DOCTYPE HTML">
<HTML>
 <HEAD>
  <TITLE> JSC3D - test </TITLE>
  <!--[if lt IE 9]><script type="text/javascript" src="js/flashcanvas.js"></script><![endif]-->
  <link rel="stylesheet" type="text/css" href="style.css">
 </HEAD>

 <BODY onload="init()">

     <div class="action_buttons">
        <b>Actions:</b>
        <input type="button" value="File" onClick="alert('Error loading save menu')" />
        <input type="button" value="Help" onClick="alert('Error loading help menu')" />
        <input type="button" value="Rotate down" onClick="viewer.rotate(-10,0,0);viewer.update();" />
        <input type="button" value="Rotate up" onClick="viewer.rotate(10,0,0);viewer.update();" />
        <input type="button" value="Rotate left" onClick="viewer.rotate(0,-10,0);viewer.update();" />
        <input type="button" value="Rotate right" onClick="viewer.rotate(10,0,0);viewer.update();" />
        <input type="button" value="Zoom in" onClick="viewer.zoom(0,10,0);viewer.update();" />
        <input type="button" value="Zoom out" onClick="viewer.zoom(0,-10,0);viewer.update();" />
        <input type="button" value="Reset viewer" onClick="viewer.resetScene();viewer.update();" />
     </div>

    <div class="mode_buttons">
        <b>Mode:</b>
        <input type="radio" name="operate" value="rotate" onclick="viewer.setMouseUsage(&#39;rotate&#39;);" checked="true">Rotate
        <input type="radio" name="operate" value="zoom" onclick="viewer.setMouseUsage(&#39;zoom&#39;);">Zoom
        <input type="radio" name="operate" value="pan" onclick="viewer.setMouseUsage(&#39;pan&#39;);">Pan
    </div>
    
    <div class="blocks">
        <b>Scene:</b>
        <select id="model_list">
        <option>base.stl</option>
        <option>jsc_logo.obj</option>
        <option>blocks.obj</option>
        <option>minifig.obj</option>
        </select>
        <input type="button" id="load" value="Load model" onClick="loadModel();" />
        <select id="render_mode_list">
        <option>render as flat</option>
        <option>render as smooth</option>
        <option>render as wireframe</option>
        <option>render as points</option>
        <option>render with environment</option>
        </select>
        <input type="button" id="change" value="Change render mode" onClick="setRenderMode();" />
     </div>

     <form method="post" action="">
            <?php
            if(count($errors) > 0) {
                echo '<ul>';
                foreach($errors as $e){
                    echo '<li>' . $e . '</li>';
                }
                echo '<ul>';
            }
            ?>

            <br/>

            <div class="save">

                <b>Save:</b>
                <input type="text" value="Name" name="name" />
                <input type="text" value="Description" name="description" />
                <br />
                <input type="submit" value="Save model" name="save" />

                <div class="screenshot"><input type="button" id="screenshot" value="Take screenshot" onClick="takeScreenshot();" /></div>
                <br /><center><div id="sc"></div></center>

            </div>
        </form>

    <div id="canvas-head" style="width:640px; margin:auto; position:relative; font-size: 9pt; color: #777777;">
        <canvas id="cv" style="border: 1px solid;" width="640px" height="480px" ></canvas>
    <div>
        
     <canvas id="tex" style="border:1px solid;" width="1" height="1"></canvas>
    </div>
    
    */ ie or not /*
    <!--[if !IE]><!-->
     <script type="text/javascript" src="jsc3d.js"></script>
     <script type="text/javascript" src="jquery.js"></script>
    <!--<![endif]-->
    <!--[if IE]>
     <script type="text/javascript" src="ie.js"></script>
     <script type="text/javascript">
      JSC3D.Texture.cv = document.getElementById('tex');
     </script>
    <![endif]-->
    <script>
    */ JS3CD stuffz /*

   
   function takeScreenshot() {
        var canvas = document.getElementById("cv");
        var imgData    = canvas.toDataURL("image/png");
        document.getElementById("sc").innerHTML += '<img src="'+imgData+'" id="image">';
        $(image).width(240);

        document.getElementById("sc").innerHTML += '<input type="text" value="'+imgData+'" id="img_text">';
        $(image).width(240);
        
    }

  </script>
 </BODY>
</HTML>

Laravel 7x fix race conditions – table cache_locks is empty

I’m trying to fix race conditions by applying Atomic Locks, like stated in the docs: https://laravel.com/docs/7.x/cache

My environment file is configured to use the database driver and I have both cache and cache_locks table migrated.

I can see some contents being written in the cache table but the cache_locks is always empty.

This is my code logic to fix race conditions:

$lock = Cache::lock("{$myUniqueId}_lock", 5);

try 
{
    $lock->block(5);

    // Perform some database operation
    DB::statement("UPDATE my_table SET some_column = {$some_data}");
} 
catch (LockTimeoutException $e) 
{
    throw new Exception('Error with atomic locks');
} 
finally 
{
    $lock->release();
}

While performing a stress test on postman with 20 virtual users:

  1. I get the MySQL error Integrity constraint violation: 1062 Duplicate entry '....' for key '....', meaning the locks are not being performed correctly
  2. The table cache_locks is always empty, it doesn’t hold any value, I keep refreshing but I don’t see anything being written there
  3. The LockTimeoutException is never thrown

What am I missing?

My code is somehow changing the date and in need to stop it

I’m having a problem with dates. I have this code

        echo "<br>2a. Recall action date: ".$recallActionDate."<br>";
        $recallActionDate = date("Y-m-d H:i:s", strtotime($recallActionDate));
        echo "<br>2b. Recall action date: ".$recallActionDate."<br>";

this is a printout of the result:

2a. Recall action date: 26/06/2019

2b. Recall action date: 1970-01-01 00:00:00

I can’t figure out how the date is getting changed – any ideas please?

Laravel queue worker stopped due to long-running job

I am facing an issue in my laravel (v-8) application. There are 10+ jobs to generate Excel files and send them to different email addresses. Everything works fine, but only one job is taking too long to execute. Then, php artisan queue:work stopped for this.

How can I fix it? Please help me.

I have set the php.ini file with max_execution_time=600 and assigned memory_limit=4G, but this problem persists.

Auto Description for wordpress post like genius [closed]

how can add auto description to all post that are empty on my platform, it’s music platform
user use to upload music without description so i need how to add a short description like “Lyrics isn’t available for the current track” and others link for review >> text

haven’t try any code but need support

Having problems with my PHP while storing the data into database [closed]

I am doing a customer service Ticket submission to resolve the customer question, and when was doing the create new ticket from user, i done the data entry by it was not storing into the database the error keep saying that “Error: Unable to insert data into the database.” can anyone can help me to fix my code

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'db_connect.php';

class FormState
{
    protected $pdo;

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

    public function handleRequest($formData)
    {
        // Default behavior for handling form submission
        return false;
    }

    protected function insertData($formData)
    {
        try {
            $sql = "INSERT INTO ticket (userName, email, phoneNumber, address, city, state, postcode, issueType, issueSubject, issueDetails, productType, serialNumber, systemPassword, extraItem, ticketStatus) 
                VALUES (:userName, :email, :phoneNumber, :address, :city, :state, :postcode, :issueType, :issueSubject, :issueDetails, :productType, :serialNumber, :systemPassword, :extraItem, :ticketStatus)";

            $stmt = $this->pdo->prepare($sql);

            $stmt->bindParam(':userName', $formData['userName']);
            $stmt->bindParam(':email', $formData['email']);
            $stmt->bindParam(':phoneNumber', $formData['phoneNumber']);
            $stmt->bindParam(':address', $formData['address']);
            $stmt->bindParam(':city', $formData['city']);
            $stmt->bindParam(':state', $formData['state']);
            $stmt->bindParam(':postcode', $formData['postcode']);
            $stmt->bindParam(':issueType', $formData['issueType']);
            $stmt->bindParam(':issueSubject', $formData['issueSubject']);
            $stmt->bindParam(':issueDetails', $formData['issueDetails']);
            $stmt->bindParam(':productType', $formData['productType']);
            $stmt->bindParam(':serialNumber', $formData['serialNumber']);
            $stmt->bindParam(':systemPassword', $formData['systemPassword']);
            $stmt->bindParam(':extraItem', $formData['extraItem']);
            $stmt->bindValue(':ticketStatus', "pending/open");

            if ($stmt->execute()) {
                return true; // Success, return true
            } else {
                // Output the error message if execution fails
                echo "Error executing SQL statement: " . $stmt->errorInfo();
                return false; // Return false to indicate failure
            }
        } catch (PDOException $e) {
            // Log or echo the error message for debugging purposes
            echo "Error: " . $e->getMessage(); // Output the specific error message
            return false; // Return false to indicate failure
        }
    }
}

// Check $_POST data
var_dump($_POST);

// new_ticket.php
$state = new FormState($pdo);

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($state->handleRequest($_POST)) {
        // Data inserted successfully, show alert
        echo '<script>alert("Data saved successfully."); setTimeout(function(){ window.location.href = "tiketList.php"; }, 3000);</script>';
    } else {
        // Error occurred while inserting data
        echo '<script>alert("Error: Unable to insert data into the database.");</script>';
    }
}

?>


<style>
    #regForm {
        background-color: #ffffff;
        margin: 100px auto;
        font-family: Raleway;
        padding: 40px;
        width: 70%;
        min-width: 300px;
    }

    h1 {
        text-align: center;  
    }

    input {
        padding: 10px;
        width: 100%;
        font-size: 17px;
        font-family: Raleway;
        border: 1px solid #aaaaaa;
        margin: 10px 0px 10px 0px;
    }
    
    select{
        padding: 10px;
        font-size: 17px;
        border: 1px solid #aaaaaa;
        margin: 10px 0px 10px 0px;
    }
    #backupData{
        display: inline-block;
        width: auto;
        margin-left: 7%;
        margin-bottom: 10px;
    }

    /* Mark input boxes that gets an error on validation: */
    input.invalid {
        background-color: #ffdddd;
    }

    /* Hide all steps by default: */
    .tab {
        display: none;
    }

    button {
        background-color: #04AA6D;
        color: #ffffff;
        border: none;
        padding: 10px 20px;
        font-size: 17px;
        font-family: Raleway;
        cursor: pointer;
        margin: 10px 0px 0px 0px;
    }

    button:hover {
        opacity: 0.8;
    }

    #prevBtn {
        background-color: #bbbbbb;
    }

    /* Make circles that indicate the steps of the form: */
    .step {
        height: 15px;
        width: 15px;
        margin: 0 2px;
        background-color: #bbbbbb;
        border: none;  
        border-radius: 50%;
        display: inline-block;
        opacity: 0.5;
    }

    .step.active {
        opacity: 1;
    }

    /* Mark the steps that are finished and valid: */
    .step.finish {
        background-color: #04AA6D;
    }
</style>


<form id="regForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <div class="tab">
        <h2>Contact Information</h2>
        <div>
            <label for="userName">User Name *</label>
            <input type="text" id="userName" name="userName" placeholder="User Name" required>
        </div>
        <div>
            <label for="email">Email Address: *</label>
            <input type="email" id="email" name="email" placeholder="Email Address" required>
        </div>
        <div>
            <label for="phoneNumber">Phone Number *</label>
            <input type="tel" id="phoneNumber" name="phoneNumber" placeholder="Phone Number" pattern="[0-9]{10,11}" required>
        </div>
        <div>
            <label for="address">Address: </label>
            <input type="text" id="address" name="address" pattern="[^ @]*@[^ @]*" placeholder="Address" optional>
        </div>
        <div>
            <label for="city">City: </label>
            <input type="text" id="city" name="city" placeholder="City" optional>
        </div>
        <div>
            <label for="state">State/Province: </label>
            <input type="text" id="state" name="state" placeholder="State/Province" optional>
        </div>
        <div>
            <label for="postcode">Postcode</label>
            <input type="text" id="postcode" name="postcode" placeholder="Postcode" pattern="d{5}" title="Please enter a correct postcode." optional>
        </div>
    </div>
    <div class="tab">
        <h2>Issue details</h2>
        <div>
            <label for="issueType">Issue Type *</label>
            <br/>
            <select id="issueType" name="issueType" required>
                <option value=""></option>
                <?php
                // Use $pdo instead of $conn
                $issueTypeQuery = $pdo->query("SELECT * FROM issue_type ORDER BY name ASC");
                while($row = $issueTypeQuery->fetch(PDO::FETCH_ASSOC)):
                ?>
                    <option value="<?php echo $row['id'] ?>"><?php echo ucwords($row['name']) ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <div>
            <label for="issueSubject">Issue Subject *</label>
            <input type="issueSubject" id="issueSubject" name="issueSubject" placeholder="Need help with... " required>
        </div>
        <div>
            <label for="issueDetails">Issue Details *</label>
            <input type="issueDetails" id="issueDetails" name="issueDetails" placeholder="Detailed explanation of the issue">
        </div>
        <div>
            <label for="productType">Product Type *</label>
            <br/>
            <select id="productType" name="productType" required>
                <option value=" "> </option>
                <option value="Desktop">Desktop</option>
                <option value="Laptop">Laptop</option>
                <option value="Monitor">Monitor</option>
                <option value="Other">Other</option>
            </select>
        </div>
        <div>
            <label for="serialNumber">Product Serial Number *</label>
            <input type="text" id="serialNumber" name="serialNumber" required>
        </div>
        <div>
            <label for="systemPassword">Operating System Password</label>
            <input type="text" id="systemPassword" name="systemPassword" optional>
        </div>
        <div>
            <label for="extraItem">Other accessories sent in together (backpack, box etc)</label>
            <input type="text" id="extraItem" name="extraItem"  optional>
        </div>
    </div>
    <div style="overflow:auto;">
        <div style="float:right;">
            <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
            <button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
        </div>
    </div>
    
    <div style="text-align:center;margin-top:40px;">
        <span class="step"></span>
        <span class="step"></span>
    </div>
</form>

<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
    // This function will display the specified tab of the form...
    var x = document.getElementsByClassName("tab");
    x[n].style.display = "block";
    //... and fix the Previous/Next buttons:
    if (n === 0) {
        document.getElementById("prevBtn").style.display = "none";
    } else {
        document.getElementById("prevBtn").style.display = "inline";
    }
    if (n === (x.length - 1)) {
        document.getElementById("nextBtn").innerHTML = "Submit";
    } else {
        document.getElementById("nextBtn").innerHTML = "Next";
    }
    //... and run a function that will display the correct step indicator:
    fixStepIndicator(n);
}

function nextPrev(n) {
    // This function will figure out which tab to display
    var x = document.getElementsByClassName("tab");
    // Exit the function if any field in the current tab is invalid:
    if (n === 1 && !validateForm()) return false;
    // Hide the current tab:
    x[currentTab].style.display = "none";
    // Increase or decrease the current tab by 1:
    currentTab = currentTab + n;
    // if you have reached the end of the form...
    if (currentTab >= x.length) {
        // ... the form gets submitted:
        document.getElementById("regForm").submit();
        return false;
    }
    // Otherwise, display the correct tab:
    showTab(currentTab);
}

function validateForm() {
    // This function deals with validation of the form fields
    var x, y, i, valid = true;
    x = document.getElementsByClassName("tab");
    y = x[currentTab].getElementsByTagName("input");
    // A loop that checks every input field in the current tab:
    for (i = 0; i < y.length; i++) {
        // If a field is empty...
        if (y[i].value === "" && !y[i].hasAttribute("optional")) {
            // add an "invalid" class to the field:
            y[i].className += " invalid";
            // and set the current valid status to false
            valid = false;
        }
        // Additional validation for phone number
        if (y[i].id === "phoneNumber" && !(/^d{10,11}$/.test(y[i].value))) {
            y[i].className += " invalid";
            valid = false;
        }
        // Validation for email
        if (y[i].id === "email" && y[i].value !== "") {
            var emailPattern = /^[^s@]+@[^s@]+.[^s@]+$/;
            if (!emailPattern.test(y[i].value)) {
                y[i].className += " invalid";
                valid = false;
            }
        }
        // Validation for postcode
        if (y[i].id === "postcode" && y[i].value !== "") {
            if (!(/^d{5}$/.test(y[i].value))) {
                y[i].className += " invalid";
                valid = false;
            }
        }
    }
    // If the valid status is true, mark the step as finished and valid:
    if (valid) {
        document.getElementsByClassName("step")[currentTab].className += " finish";
    }
    return valid; // return the valid status
}

function fixStepIndicator(n) {
    // This function removes the "active" class of all steps...
    var i, x = document.getElementsByClassName("step");
    for (i = 0; i < x.length; i++) {
        x[i].className = x[i].className.replace(" active", "");
    }
    //... and adds the "active" class on the current step:
    x[n].className += " active";
}   
</script>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// db_connect.php
    $host = 'localhost';
    $dbname = 'customerservice_db';
    $username = 'test';
    $password = '1234';

    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
CREATE TABLE `tickets` (
  `id` int(30) NOT NULL,
  `userName` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `phoneNumber` int(20) NOT NULL,
  `address` varchar(255) DEFAULT NULL,
  `city` varchar(255) DEFAULT NULL,
  `state` varchar(255) DEFAULT NULL,
  `postcode` int(20) DEFAULT NULL,
  `issueType` varchar(255) NOT NULL,
  `issueSubject` varchar(255) NOT NULL,
  `issueDetails` varchar(255) NOT NULL,
  `productType` varchar(255) NOT NULL,
  `serialNumber` varchar(255) NOT NULL,
  `systemPassword` varchar(255) DEFAULT NULL,
  `backupData` tinyint(1) NOT NULL,
  `extraItem` varchar(255) NOT NULL,
  `ticketStatus` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

the situation is like this, the user had completed input all the data but when the user click submit, it will have error saying that “Error: Unable to insert data into the database.”, i know i had assign this error handling, but i wtill dont know where the problem is, please someone help me

How can I use foreignId in Laravel with camelCase?

I have a table User, which has an id. In another table (AdminUser), I want to reference it, but with camelCase convention.

However, Laravel doesn’t convert that and/or recognize the user table, so it returns always null when asking for the user from the other table.

I am experimenting with something, so the table layout User and AdminUser might be weird, but that is not the point of the question.

Here is the AdminUser table:

Schema::create('AdminUser', function (Blueprint $table) {
    $table->id();
    $table->foreign('userId');
    $table->integer('pin');
    $table->string('passcode');
    $table->timestamp('updatedAt');
    $table->timestamp('createdAt');
});

Here is the User table:

Schema::create('User', function (Blueprint $table) {
    $table->id();
    $table->string('username');
    $table->string('password');
    $table->enum('role', ['ADMIN', 'USER'])->default('USER');
    $table->string('loginToken')->nullable();
    $table->rememberToken()->nullable();
    $table->renameColumn('remember_token', 'rememberToken');
    $table->timestamp('createdAt');
    $table->timestamp('updatedAt');
});

If I reference it with user_id in the AdminUser table, it is working properly, but I would like to find out how to use camelCase foreign keys.