Multible myslqi and Meekrodb errors

So I moved my Project from a Windows Server on a Linux Debian 11 and now I’m facing multiple mysqli and MeekroDB errors.
On Windows it all worked fine so far, Login worked with the DB-connection

I had to uncomment the extension=php_mysqli.dll for the Errors to disappear on Windows
On Linux i did all the same but get the following Errors

: mysqli::real_escape_string(): invalid object or resource mysqli in
/var/www/html/projectName/plugins/meekrodb/db.class.php
on line
703

Warning
: mysqli::query(): invalid object or resource mysqli in
/var/www/html/projectName/plugins/meekrodb/db.class.php
on line
792

Warning
: MeekroDB::queryHelper(): Property access is not allowed yet in
/var/www/html/projectName/plugins/meekrodb/db.class.php
on line
796

Warning
: MeekroDB::queryHelper(): Property access is not allowed yet in
/var/www/html/projectName/plugins/meekrodb/db.class.php
on line
797

Warning
: MeekroDB::queryHelper(): Property access is not allowed yet in
/var/www/html/projectName/plugins/meekrodb/db.class.php
on line
815

I double-checked if all packages are installed aswell, and without the DB-connection it works fine aswell just without the Data and User-Login

php json delete after a certain character

I’m printing the data returned as json on my page, but I want to delete everything after certain words.

Sample:

[
  {
    "Id": "15195456",
    "PHONE": "1XXXXXXXXXX",
    "NAME": "JESSICA",
    "SURNAME": "CLAY",
    "MOTHER": "AHMET",
    "FATHER": "AYSE",

  },

Code:

echo json_encode(["success" => "true", "data" => json_decode($result, true)]);

What I want to do is delete everything after mother, how can I do this?

UPDATE sql after pulling user data [duplicate]

I am trying to pull users for a php mailer script.

$sql = "SELECT email FROM emails WHERE status = 'new' LIMIT 1

I am able to pull up the users i want using the sql above, but i want to update the “status” column to done when it has sent the email, i have tried the below but its not pulling any records.

$sql = "SELECT email FROM emails WHERE status = 'new' LIMIT 1 UPDATE 'emails' SET 'status'=done WHERE new";

How to get the rank of a row in a MySQL table using PHP and how to store it into a separate variable?

I have been writing the script of a cron job in PHP that is supposed to connect to a text file, get the participantID that is written to it using Java separately, and return details about that participant in a separate text file. The details about that participant are supposed to be their Points, Quantity and Rank out of other participants(which is got using the points that the respective participants have got).

This is the code that I have written so far:

<?php

//connect to mysql database procedurally
$conn = mysqli_connect("localhost","root","","anka");

if(!$conn){
    echo "Connection error" . mysqli_connect_error("localhost","root","","anka");
}

$participantid = 0;
$participantid = fopen('performancerequests.txt',"r") or die("Request not taken.");
$content = fread($participantid, filesize("performancerequests.txt"));
file_put_contents("performancerequests.txt","");


//should return rank, points, products left(quantity) 
$sql1 = "SELECT points from participants where id='$content'";
$sql2 = "SELECT quantity from products where participant_id='$content'";
$sql3 = "SELECT points, ROW_NUMBER() OVER( ORDER BY points ) RowNumber from participants where id='$content'";

$result1 = mysqli_query($conn, $sql1);
$result2 = mysqli_query($conn, $sql2);
$result3 = mysqli_query($conn, $sql3);

while ($row1 = $result1->fetch_assoc()) {
    $points = $row1['points'];
}

while ($row2 = $result2->fetch_assoc()) {
    $quantity = $row2['quantity'];
}

while ($row3 = $result3->fetch_assoc()) {
    $rank = $row3['rank'];
}


$handle = fopen("performance.txt", "w") or die("File does not exist.");
if(fwrite($handle,$content." "."Points: ".$points." "."Quantity: ".$quantity." "."Rank: ".$rank) == false ){
    echo "Error Writing.";
}

?>

The code for the tables in question are also as follows:

CREATE TABLE participants (
    id bigint(20),
    name varchar(255),
    password varchar(255),
    product varchar(255),
    DOB date,
    points int(11),    
    PRIMARY KEY(id)
);

CREATE TABLE products (
    id bigint(20),
    name varchar(255),
    quantity varchar(255),
    rate varchar(255),
    description varchar(255),
    FOREIGN KEY(participant_id) REFERENCES participants(id),    
    PRIMARY KEY(id)
);

But when I test and run it, it returns the warning that there’s an undefined array key, for the variable $rank. And in the text file, the rank bit is also left blank.

Is there a way I could solve this?

How to build a DRY Laravel resource API?

I’m trying to build a resource API with Laravel.
It appears that the approach taken by most is to:

  • Create a route for each resource
  • Create a controller for each resource
  • CRUD logic for each resource either in the controller or deferred to a service for each resource

This seems fine if you’ve only got a couple of resources otherwise you are repeating most of code.

Is there a reason why you wouldn’t create a single catchall route, with a single controller, with a CRUD service that could perform logic whatever the resource?

I appreciate this could be considered an opinionated question, so I am looking for the reasons why either approach would or wouldn’t be taken, or, methods to DRY up the first approach.

Many thanks to any responders.

How to reuse a MySQLi connection

I’ve ran into an issue with user already has more than ‘max_user_connections’ active connections

This happens because I use functions for the website functionality, each function contains a

$mysqli = connect();

Though at the same time, each function closes the mysqli at the end of function

mysqli_close($mysqli);

I do not want to include $mysqli as a parameter of the function, as the function is dynamic and would be tiresome to include it with each function call.

the connect() function just contains:

$mysqli = new mysqli(...);
return $mysqli;

I believe the error is thrown because the function sometimes calls itself for different executions, based on user input and pre-requisites… even though the mysqli is closed at the end of the function

I’d like to know if there is a way of re-using a $mysqli connection sort of like in a global way…

I’m not sure whether I’ve explained myself fully so if you need some more information please leave a comment.

Ajax update of iframe at specific time of the day

I have a section on a site where, at certain times of the day, it loads a different php page that contains the code to pick at random from a list of mixcloud shows (using Mixcloud’s embed iframe) It’s an online radio station so the idea being that between 5-8am for example, the 80s music php page is loaded and an iframe is picked at random to appear on the site, this way users don’t just get the same 80s show every morning and there’s a bit of ‘randomness’ to it (it’s still not a true online station but as close as using a custom solution) then at 8-11, it loads 90s music etc. I don’t think the Mixcloud details are too important to the question but I wanted to paint a complete picture.

The code for actually loading the php scripts on the front end is:

<?php
    if (date('H') >= 5 && date('H') < 8) {
        echo '<iframe width="100%" frameborder="0" src="80s-iframe-page-path-here"></iframe>';
    }
    if (date('H') >= 8 && date('H') < 11) {
        echo '<iframe width="100%" frameborder="0" src="90s-iframe-page-path-here"></iframe>';
    }
?>

An example of the script itself where the iframes are loading randomly is:

<script>
    var videos = [
        '?hide_cover=1&light=1&autoplay=1&feed=%2Fshow=path-here%2F',
        '?hide_cover=1&light=1&autoplay=1&feed=%2Fanother-show=path-here%2F',
    ];

    var index=Math.floor(Math.random() * videos.length);
    var html='<iframe width="100%" height="100" src="https://www.mixcloud.com/widget/iframe/' + videos[index] + '" frameborder="0" allow="autoplay"></iframe>';
    document.write(html);
</script>

In itself, this works great so visit the site between 5-8am and you will get a random 80s show. visit between 8-11 and you’ll get 90s etc. The issue I need to address though is as these are static shows and not a live stream, if you arrive at the site at 5am or 5.30am you’re going to get a 3 hour show but if you start it at 5.30am, it is going to play til 8.30am (cutting into the 90s show) so everyone will be out of sync plus anyone listening to it will just be met with silence once that 80s show has finished. I want to pull people back in to the schedule the best I can.

My initial thought was at 8am, show an ajax div saying ‘the 90s show is now playing, click here to refresh’ which reloads the page and 90s will play but firstly I’m not sure how to display that div automatically without page refresh but even with this, it requires reloading the page so isn’t the most polished solution.

So my decision is to instead just reload the iframe at 8am so if you’re listening to 80s still at 8am, that will just stop and 90s will start. It means an abrupt end but I’m fine with that if it means this happens automatically.

So steering back to the question, based on my code a user would need to refresh the page at 8am to get the 90s show so how can I make that automatic so at 8am, the iframe itself reloads, recognises it’s time for a show change and loads the relevant php file? I guess this is ajax but I have little experience of that.

Vue TableLite 1 column with multiple rows

Table repeats the userid and username so i want to only show the userid and name once and then show the rest of the data like in the link on imgur. Manipulating the data is no concern i just need the layout to display “good looking”

Don’t ask me why but i was told to only use TableLite

Check the full code on codepen

https://codepen.io/m0nst3rgr1m/pen/ZEoyKjy

`userleavedaysusageTable: {
isLoading: false,
isReSearch: false,
columns: [
{
label: “User ID”,
field: “user_id”,
width: “5%”,
isKey: true,
},
{
label: “User Name”,
field: “user_id”,
width: “15%”,
display: function (row) {
return row.user.name;
},
},

                {
                    label: "Leave Type",
                    field: "lt_cd",
                },
                {
                    label: "Avail fin days ",
                    field: "uldu_avail_fin_days",
                    columnStyles: { "text-align": "right" },
                },
                {
                    label: "Avail carryover days ",
                    field: "uldu_avail_co_days",
                    columnStyles: { "text-align": "right" },
                },
                {
                    label: "Avail total days ",
                    field: "uldu_avail_total_days",
                    columnStyles: { "text-align": "right" },
                },
                {
                    label: "Pending days ",
                    field: "uldu_pending_days",
                    columnStyles: { "text-align": "right" },
                },
                {
                    label: "Declined days ",
                    field: "uldu_declined_days",
                    columnStyles: { "text-align": "right" },
                },
                {
                    label: "Cancelled days ",
                    field: "uldu_cancelled_days",
                    columnStyles: { "text-align": "right" },
                },`

https://imgur.com/a/o5CT997

Thank you all in advance

How to block all urls and only allow 1 / 2 url as public?

Hi I have an application with sso all the clients and server is on same IP (using sub-domains). A central application auth is made in ci which accepts the login from the other node application. I want to allow only those applications which are on my sub-domains to access auth and block all other IP’s who tries to access the auth. There is an admin section made on auth basically made to deal with user creation and updation. The url is suppose auth/admin. I only want this url to be accessible publically and few others related to it. Any suggestions will be helpful.

Thank you in advance.

Dynamic sql insert for exporting excel into sqlserver using php?

I have been exporting excel file to database using php. Which is working properly but now I want dynamic insert sql query where I Do

not want to specify column name and column numbers please help me on
the same I have done enough research and I am unable to come up with a
solution for the same I am sharing my code too please help me

<?php
session_start();
$serverName = "192.168.22.68"; //serverNameinstanceName
$connectionInfo = array( "Database"=>"INTEROPDB", "UID"=>"uatkrasqluser", "PWD"=>"CV!u@t2018");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if($conn) {
  
  

}else{
 echo "Connection could not be established.<br />";
    die( print_r( sqlsrv_errors(), true));
}


require 'vendor/autoload.php';

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;

if(isset($_POST['save_excel_data']))
{
    $fileName = $_FILES['import_file']['name'];
    $file_ext = pathinfo($fileName, PATHINFO_EXTENSION);

    $allowed_ext = ['xls','csv','xlsx'];

    if(in_array($file_ext, $allowed_ext))
    {
        $inputFileNamePath = $_FILES['import_file']['tmp_name'];
        $spreadsheet = PhpOfficePhpSpreadsheetIOFactory::load($inputFileNamePath);
        $data = $spreadsheet->getActiveSheet()->toArray();

        $count = "0";
        foreach($data as $row)
        {
            if($count > 0)
            {
                $fullname = $row['0'];
                $email = $row['1'];
                $phone = $row['2'];
                $course = $row['3'];

                $studentQuery = "INSERT INTO PRIYATIWARI (fullname,email,phone,course) VALUES

(‘$fullname’,’$email’,’$phone’,’$course’)”;
$result = sqlsrv_query($conn, $studentQuery);
$msg = true;
}
else
{
$count = “1”;
}
}

        if(isset($msg))
        {
            $_SESSION['message'] = "Successfully Imported";
            header('Location: index.php');
            exit(0);
        }
        else
        {
            $_SESSION['message'] = "Not Imported";
            header('Location: index.php');
            exit(0);
        }
    }
    else
    {
        $_SESSION['message'] = "Invalid File";
        header('Location: index.php');
        exit(0);
    }
}
?>

IN place of insert tablename(column name), values() I want something dynamic where I do not need to specify column name

php in javascript. the server responded with a status of 404 (Not Found) [duplicate]

I just started to learn js, I ran into a problem. I have a feedback form on my landing page. I need the emails to come to gmail. For this I wrote one js script which links to a php file using fetch. however I get an error in the console. and of course it doesn’t send the request

html

 <form action="#" autocomplete="on" method="POST" class="form-action" id="form" enctype="multipart/form-data">
                    <h3 class="h3-form">Let's jump onto message</h3>
                    <input class="form-input _req" type="text" name="Name" placeholder="Name">
                    <input class="form-input _req _email" type="text" name="Email" placeholder="Email">
                    <textarea class="form-input _req" cols="30" rows="1" style="resize: none;" name="Message" placeholder="Your idea"></textarea>
                    <div class="attaching">
                        <div class="form-file-preview" id="formPreview"></div>
                        <label class="attach-label">
                            <input id="formFile" type="file" accept=".pdf,.doc,.docx,.jpeg,.xls,.xlsx,.jpg,.csv,.ods,.tsv" multiple data-max-size="10485760" name="file" class="hiddenInput" data-hj-allow="true">
                            <span class="icon-paperclip">
                                <img src="/img/attach.svg" alt="">
                            </span>
                            <div class="attach">Attach Files
                            </div>
                        </label>
                    </div>
                    <button class="send" type="submit">Send</button>
                </form>

JS

const form = document.getElementById('form');
const sendmessage = document.getElementById('sendmessage');
form.addEventListener('submit', formSend);

async function formSend(e) {
    e.preventDefault();
    let error = formValidate(form);
    let formData = new FormData(form);
    formData.append('file', formFile.files[0]);
    if (error === 0) {
        sendmessage.classList.add('_sending');
        let response = await fetch('sendmail.php', {   \here is a problem
            method: 'POST',
            body: formData
        });
        if (response.ok) {
            let result = await response.json();
            alert(result.message);
            formPreview.innerHTML = '';
            form.reset();
            sendmessage.classList.remove('_sending');
        } else {
            alert("Fail");
            sendmessage.classList.remove('_sending');
        }
    }
}

function formValidate(form) {
    let error = 0;
    let formReq = document.querySelectorAll('._req');
    for (let index = 0; index < formReq.length; index++) {
        const input = formReq[index];
        formRemoveError(input);
        if (input.classList.contains('_email')) {
            if (emailTest(input)) {
                formAddError(input);
                error++;
            }
        } else {
            if (input.value === '') {
                formAddError(input);
                error++;
            }
        }
    }
    return error;

}

sendmail.php

<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require 'PHPMailer/src/Exeption.php';
require 'PHPMailer/src/PHPMailer.php';

$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';

$mail->setLanguage('en', 'phpmailer/language/');
$mail->IsHTML(true);

$mail->setFrom('[email protected]');
$mail->addAdress('[email protected]');
$mail->Subject = 'New Message';

$body = '<h1>Message on Site</h1>';
if(trim(!empty($_POST['Name']))){
  $body.='<p><strong>Name:</strong> '.$_POST['Name'].'</p>';
}
if(trim(!empty($_POST['Email']))){
  $body.='<p><strong>Email:</strong> '.$_POST['Email'].'</p>';
}
if(trim(!empty($_POST['Message']))){
  $body.='<p><strong>Message:</strong> '.$_POST['Message'].'</p>';
}

if(!empty($_FILES['file']['tmp_name'])){
$filePath = __DIR__ . "/files/" . $_FILES['file']['name'];
if (copy($_FILES['file']['tmp_name'], $filePAth)) {
  $fileAttach = $filePath;
  $body.='<p><strong>File attached</strong>';
  $mail->addAttachment($fileAttach); 
}
}
$mail->Body = $body;

if(!$mail->sent()) {
  $message = 'Error';
}else {
  $message = "Successfully";
}

$response = ['message' => $message];

header('Content-type: application/json');
echo json_encode($response);
?>

Console error:

POST 192.168.88.21:3000/sendmail.php 404 (Not Found).
_refers to script.js:51

enter image description here

enter image description here

How do I run this file so there are no errors?

my code was running well before i host my web now i see this kind of error after web being hosted. please help me [closed]

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /category.php on line 14

Fatal error: Uncaught Error: Call to a member function error() on null in category/category.php:20 Stack trace: #0 {main} thrown in category/category.php on line 20

<?php
session_start();
mysqli_report(E_ALL);
if(!isset($_SESSION['loggedin'])){
    header('location : ../../connection/session.php');
    exit();
}
 if(isset($_POST["submit"])){
   if(empty($_POST['name'])){
      echo "some fields are empty";
   }else{
        $names = $_POST['name'];

      $result= mysqli_query($link,"insert into category(name) values('$name')");
        
      if($result){
          echo "added successfully";
      header('location:create.php');
   }else{
       echo "error".$link->error();
   }
   }
   }

PHP says “SOAP-ERROR: Parsing WSDL: Couldn’t load from… failed to load external entity” when trying connect to docker container

I’am using Docker container to create a SOAP server inside it. My external PHP script trying to get response from SOAP server, but receive an error

SOAP-ERROR: Parsing WSDL: Couldn't load from... failed to load external entity.

If I’am getting http://domain.loc:8080/api/soap?wsdl from browser, I receive a correct WSDL.

PHP script is

try {

    $client = new SoapClient('http://domain.loc:8080/api/soap?wsdl', [

        'uri'                   => 'http://schemas.xmlsoap.org/soap/envelope/',
        'style'                 => SOAP_RPC,
        'use'                   => SOAP_LITERAL,
        'soap_version'          => SOAP_1_1,
        'cache_wsdl'            => WSDL_CACHE_NONE,
        'connection_timeout'    => 60,
        'trace'                 => true,
        'encoding'              => 'UTF-8',
        'exceptions'            => false,
        'verifypeer'            => false,
        'verifyhost'            => false,
    ]);

    $params = new SoapVar('<options>...</options>', XSD_ANYXML);
    $result = $client->getSOAPMethod($params);

    var_dump($client->__getLastRequest());
    var_dump($result);

} catch (SoapFault $exception) {

    echo $exception->getMessage(); 
}

How someone explain to me where is a trouble?

jQuery & Ajax – POST 406 error on form submit

I see the POST 406 error in developer console when I try to press the submit button on a contact form:

HTML:

<form id='contact-form' method="POST">
    <input name="name" type="text" class="text cleartext" placeholder="Your Name" />
    <input name="email" type="text" class="text cleartext" placeholder="Your EMail Address" />
    <textarea name="message" placeholder="Your Message"></textarea>
    <input type="submit" class="submit" value="Send" name="" />
</form>

Error:

jquery.1.9.1.min.js:5
POST https://example.co.uk/php-mail/mail.php 406

send @ jquery.1.9.1.min.js:5
ajax @ jquery.1.9.1.min.js:5
(anonymous) @ theme.mail.js:14
dispatch @ jquery.1.9.1.min.js:3
v.handle @ jquery.1.9.1.min.js:3

What could be causing this error?