PHP connect to MySQL container created on Railway

PHP newbie here. I created a cloud MySQL provision using Railway (a Heroku alternative) which I’d like to connect to.

Connecting to the database should be fairly simple, as the service provides a connection url.
However, this fails to connect and throws: SQLSTATE[HY000] [2002] No such file or directory.

My attempt at connecting to the db instance:

<?php
try {
  $dsn        = "mysql://root:[email protected]:7265/railway";
  $username   = "root";
  $password   = "password";
  $options    = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  );

  $connection = new PDO($dsn, $username, $password, $options);
  echo "Database created successfully.";
} catch (PDOException $error) {
  echo $error;
  die();
}
?>

What am I missing?

get pure string from json string like ‘ufe0fJ’ with php

here is my json string
{ "opa": "O_ufe0fPufe0f_ufe0fAufe0f" }

when i decode my json string
object(stdClass)#16 (1) { ["opa"]=> string(25) "O_ufe0fPufe0f_ufe0fAufe0f" }

i want to get without this ->ufe0f symbols
result should be “O_P_A”

P.S. it can be any other character like [udbff, udc00, etc.]

How to display data row wise in HTML table [duplicate]

I have 3 tables in MySQL database

  1. rep (id, userid, date)
  2. time (time_id, id, Time)
  3. stud_details (stid, time_id, sid, Student, Subject, Topic, Confidence)

One report has many time details and each time has many student details. I want to display the data row wise in HTML table as shown below.

enter image description here

As show in the screenshot, each time is displayed in column and for each time their respective student details are shown. Every column has different number of students.

I have below code which displays column wise data in HTML table. But the issue is wherever there is empty student data, rows are not displayed. So I need to display the rows for all the cells as shown in the above screenshot.

<?php
 
 $sql2 = 'SELECT rd.Time,rd.id from time as rd,  rep as rep WHERE rep.id=rd.id and 
          DateofReport=:date';      // Query to get all the Time of specific report

 $params = [':date'=>$model->DateofReport];    // Bind date parameter for the query

 $timedetails = Yii::$app->db->createCommand($sql2, $params)->queryAll(); // Get all times
 
 ?>

 <?php
 echo "<table class='table table-bordered'>";

 foreach($timedetails as  $tdetails):
 
  ?>

  <td>
   <table class='table table-bordered'  style="border: 1px solid black">
      <tr  bgcolor='#B8B8B8' style="border: 1px solid black">
         <th style='border: 1px solid black;'>
            <?php echo $tdetails['Time']; // Display Time in columns?>  
        </th>
     </tr>

<?php
// Query to fetch student details for each time
$sql3 = 'SELECT s.StudentName, sd.Subject,sd.Topic,sd.Confidence 
         from time as rd, student as s, stud_details as sd, rep as rep
         where rd.time_id=sd.time_id
         and rep.id=rd.id
         and s.StudentId=sd.StudentId 
         and rd.id=:Id
         and rep.userid=:userid';

$params1 = [':userid' => $model->UserId];    // Bind user id parameter
$params1[':Id']=$tdetails['time_id'];        // Bind time parameter

$StudentDetails=Yii::$app->db->createCommand($sql3, $params1)->queryAll();// Get student data
 
foreach($StudentDetails as $StudentDetails){
?>
  <tr>
       <td style='width:100px; word-wrap: break-word; border: 1px solid black;'>
           <b><?php echo $StudentDetails['StudentName'];?></b>
       </td>
  </tr>
  <tr>
       <td style='width:100px;word-wrap: break-word; border: 1px solid black;'>
               <?php echo  $StudentDetails['Subject'];?>
       </td>
 </tr>
 <tr>
       <td style='width:200px;word-wrap: break-word;border: 1px solid black;'>
              <?php echo  $StudentDetails['Topic'];?>
       </td>
 </tr>
 <tr>
       <td style='width:100px;word-wrap: break-word;border: 1px solid black;'> 
             <?php echo  $StudentDetails['Confidence'];?>
       </td>
 </tr>
 <?php
   }
 ?>
</table>
</td>
<?php
endforeach;
echo '</table>';
?>

How to log-in with encrypted passwords [duplicate]

I made a login and register system, it works, it encrypts the password using bcrypt, but when I go to login it only works with the encrypted password so I have to go to the database and copy it.

This is my login and to help next is Register. I tried to put the password_hash in the login too but when doing that I can’t login.

<label for="password">Password:</label>
<input type="password" id="password" name="password" ><br><br>
<input type="submit" name="login" value="Login">
if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    
    $stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $result = $stmt->get_result();
    
    
    if (mysqli_num_rows($result) == 1) {
      echo "Login successful";
      header("Location: forminicio.php");
    } else {
        echo "Invalid username or password";
    }
}

Register

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

    $data['username'] = ($_POST['username']);
    $data['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
    
    $username = $data['username'];
    $password = $data['password'];
    
    
    $sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
    if (mysqli_query($conn, $sql)) {
        echo "New user created successfully";
    } else {
        echo "Error creating user: " . mysqli_error($conn);
    }
}

user device detection with javascript [closed]

my html:

<li data-memberId="{$row['member_id']}"></li>

I want to show user device Icon behind of usernames. for this I write below javascript code but I don’t know how to implement that.

my javascript:

if (window.matchMedia("(max-width: 768px)").matches)
{
  document.write("fa-mobile");  
}  
else  
{  
  document.write("fa-desktop");  
}

just I want to display user device (mobile or desktop or tablet)

I am facing problem in using PHP-ML Persistency feature. The model is not working as expected

I am building a model to analyze sentences whether positive or negative. After the model is successfully trained, I am trying to save the model using PHP-ML Persistency. The model is being saved successfully as well.

But the problem is when I restore the model from file and try to predict, the predict method is throwing error as follows :

Type: PhpmlExceptionInvalidArgumentExceptionMessage: Missing feature. All samples must have equal number of features.

My example code is as follows :

require_once __DIR__ . '/vendor/autoload.php';

use PhpmlClassificationNaiveBayes;
use PhpmlFeatureExtractionTokenCountVectorizer;
use PhpmlTokenizationWhitespaceTokenizer;
use PhpmlModelManager;

$modelPath = '/var/www/ai/models/sentiment_analyzer';

if( ! file_exists($modelPath) ) {

    // Training data
    sentences = [
       'I love this product!',
       'This is terrible, do not buy it.',
       'The customer service was amazing.',
       'I am very disappointed with this purchase.',
       'The quality of this item is excellent.',
       'I would recommend this to anyone.',
       'This product is a waste of money.',
       'The shipping was fast and efficient.',
       'I regret buying this product.',
       'This is the best product I have ever used.'
    ;
    
    labels = [
       'positive',
       'negative',
       'positive',
       'negative',
       'positive',
       'positive',
       'negative',
       'positive',
       'negative',
       'positive'
    ;

    // Vectorize the sentences
    vectorizer = new TokenCountVectorizer(new WhitespaceTokenizer());
    vectorizer->fit($sentences);
    vectorizer->transform($sentences);

    // Train the Naive Bayes classifier
    classifier = new NaiveBayes();
    classifier->train($sentences, $labels);


    modelManager = new ModelManager();
    modelManager->saveToFile($classifier, $filepath);
}
else
{
    $classifier = modelManager->restoreFromFile($filepath);
}


// Predict the sentiment of a new sentence
$newSentence = 'This product is not worth the money.';
$newSentenceVector = $vectorizer->transform([$newSentence])[0];
$predictedLabel = $classifier->predict($newSentenceVector);

echo 'Prediction : ' . $predictedLabel;

Please do note, if I am not saving the model, the prediction is working fine without any errors.

How to loop for searching id by row using php excel

I want to create an import from excel to database. But in one of the inputs are using <select> which has the value of an id. like this:

<select id="merchant" name="merchant">
                        <?php 
                            foreach($merchant as $opt_merchant){
                        ?>
                            <option value="<?= $opt_merchant['merchant_id'] ?>"><?= $opt_merchant['merchant_name'] ?></option>
                        <?php
                            }
                        ?>
</select>

How do I get the ID when the user only input the merchant_name in the excel?

my senior told me to get all the merchants first, then when it loops, just search for the object by name, then get the id. But I don’t know how to get each row of merchant_name and then search for their id.

the controller for the import:

public function import_retail_proses(){
    $this->load->library(array('excel','session'));
    if (isset($_FILES["fileExcel"]["name"])) {
        $path = $_FILES["fileExcel"]["tmp_name"];
        $object = PHPExcel_IOFactory::load($path);
        foreach($object->getWorksheetIterator() as $worksheet)
        {
            $highestRow     = $worksheet->getHighestRow();
            $highestColumn  = $worksheet->getHighestColumn();   
            $values         = [];
            for($row=2; $row<=$highestRow; $row++)
            {
                $pos_pelanggan_code = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
                $pos_merchant       = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
                $pos_name           = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
                $pos_sales_name     = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
                $pos_address        = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
                $pos_email          = $worksheet->getCellByColumnAndRow(5, $row)->getValue();
                $pos_phone          = $worksheet->getCellByColumnAndRow(6, $row)->getValue();
                $pos_website            = $worksheet->getCellByColumnAndRow(7, $row)->getValue();
                $pos_npwp   = $worksheet->getCellByColumnAndRow(8, $row)->getValue();
                $pos_post_code = $worksheet->getCellByColumnAndRow(9, $row)->getValue();
                $pos_fax    = $worksheet->getCellByColumnAndRow(10, $row)->getValue();
                $pos_vip    = $worksheet->getCellByColumnAndRow(11, $row)->getValue();
                $values[]       = array(
                'kode_pelanggan' => $pos_pelanggan_code,
                'nama' => $pos_name,
                'vip' => 0,
                'tgl_daftar' => date('Y-m-d H:i:s'),
                'alamat' => $pos_address,
                'email' => $pos_email,
                'no_hp' => $pos_phone,
                'website' => $pos_website,
                'no_npwp' => $pos_npwp,
                'kode_pos' => $pos_post_code,
                'no_fax' => $pos_fax,
                'limit' => 0,
                'top' => 0,
                'merchant' => $pos_merchant,
                'jenis_pelanggan' => 0
                );
            }
        }
        $insert     = $this->db->insert_batch('pelanggan',$values);
        if( $insert ) {
            $this->session->set_flashdata('success','Import item');
            redirect($_SERVER['HTTP_REFERER']);
        }else{
            print_r('error ');die;
        }
    } else {
        echo "Tidak ada file yang masuk";die;
    }
}

How to make a super fast load for one of Laravel routes?

I have one route in Laravel (9) which is for photo resizing. In that route max speed is needed, so I want to avoid loading not used controller, models, vendors in that route. Is this possible? How? Maybe there are better decisions?

/public/index.php has this code:

<?php

use IlluminateContractsHttpKernel;
use IlluminateHttpRequest;

define('LARAVEL_START', microtime(true));


if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
    require $maintenance;
}

require __DIR__.'/../vendor/autoload.php';


$app = require_once __DIR__.'/../bootstrap/app.php';

$kernel = $app->make(Kernel::class);

$response = $kernel->handle(
    $request = Request::capture()
)->send();

$kernel->terminate($request, $response);

Maybe I can load Image Magick vendor and skip the rest? I’m not using Database in that route or anything else which needs dependences

How to create an exception route inside of a middleware laravel

I have made a working middleware that forces the user to complete onboarding before progressing any further in the web site. See code below –

public function handle(Request $request, Closure $next)
{
    $user = $request->user();

    // if the user has completed onboarding - let them go where they need to go!
    if ($user->isOnboarded())
        return $next($request);

    $redirectDictionary = [
        0 => 'employment.index',
        1 => 'qualificationsAndCertifications.index',
        2 => 'extraDocs.index',
        3 => 'additionalInformation.index',
    ];


    $intendedRoute = Arr::get($redirectDictionary, $user->onboarded);

    // If the user is where they are meant to be - let them proceed!
    if ($intendedRoute == $request->route()->getName())
        return $next($request);

    return redirect()->route($intendedRoute);
}

I want to add a new route called resume onboarding. Which will appear if the user logs back in and hasn’t completed the onboarding process. I have implemented this by checking that the user’s onboarded value is <4 on login. However, this implementation is being overwritten by this middleware as it redirects the user off of that page automatically. And therefore I was wondering if there was a way of adding an exception to this middleware to allow the user to access this resume onboarding page ?

Doctrine possible values for driver in DATABASE_URL

In Doctrine configuration reference (driver) I see pdo_mysql as a possible value, but not mysql, which is the one defined by default in Symfony (in DATABASE_URL).

I have checked that it’s using PDO even though mysql is defined as driver in DATABASE_URL, but I can’t find any reference. Is it an alias of pdo_mysql?

On the other hand, in the same reference page I see an example with pdo-mysql, not pdo_mysql. Is there any sort of transformation of driver within DATABASE_URL?

What are then all possible values for driver in DATABASE_URL?

Access denied for user ‘pmauser’ when connecting to MySQL server in PHP code

I am trying to connect to a MySQL database from my PHP code using the mysqli_connect() function. However, I am getting the following error message in the browser :

Fatal error: Uncaught mysqli_sql_exception: Access denied for user
‘pmauser’@’localhost’ (using password: YES) in
C:xampphtdocsecommincludesdbh.inc.php:8 Stack trace: #0
C:xampphtdocsecommincludesdbh.inc.php(8):
mysqli_connect(‘localhost’, ‘pmauser’,
Object(SensitiveParameterValue), ‘phpproject01’) #1
C:xampphtdocsecommincludessignup.inc.php(11):
require_once(‘C:xampphtdocs…’) #2 {main} thrown in
C:xampphtdocsecommincludesdbh.inc.php on line 8

I have verified that the username and password are correct, and that the user ‘pmauser’ has all privileges and access to the ‘phpproject01’ database. I am running the MySQL server on port 3306, and I have checked my firewall settings to ensure that the port is open.

Here is the code I am using to connect to the database:

$serverName = "localhost";
$dBUsername = "pmauser";
$dBPassword = "sensitive";
$dBName = "phpproject01";

$conn = mysqli_connect($serverName,$dBUsername,$dBPassword,$dBName);

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

im running this on xampp

What could be causing this error, and how can I resolve it? Any help would be greatly appreciated.

Can’t log out an PHP application [closed]

I have an CRUD simple system made in PHPRunner. Recently I migrated PHP to last version. After that the system doesn’t log out anymore. When I test it in localhost (PHP 7.x) works perfectly, but in server (PHP 8.x) not.
I suspect it has relation with php sessions, but have no idea where start to check out.