SQLSTATE[HY093]: Invalid parameter number in laravel

controller

    $tracks = DB::table('tracks')->whereNotIn('id',[$album->track_id])->get();

        foreach ($tracks as $key => $track){

            $names = DB::table('singers')->whereIn('id', $track->singers_id)->pluck('singers_name')->toArray();


        }

SQLSTATE[HY093]: Invalid parameter number

select
*
from
tracks
where
id not in (1)

php : what this set_include_path is seting?

Im trying to use php but im a beginner.

I would like to understand which actual paths this function is setting?

set_include_path(get_include_path().PATH_SEPARATOR.dirname(__FILE__).'/php-pear;'.dirname(__FILE__).'/php-pear/DB-1.9.3');

Thank you

Submit multiple forms that are created in PHP while loop with one button

I am attempting to submit multiple values in separate HTML input fields using one button. These values will be entered into a MySQL table called answers with 3 columns: answerID, questionID and answerBody.

However, each input field is generated using a while loop in a separate PHP function, with the form id being set to ‘questions’.

Is it possible to do this?

Here is my code:

survey.php:

<?php

    require_once "config/config.php";
    
    //Start the session to grab session details
    session_start();

    //Process data when form is submitted
    if($_SERVER["REQUEST_METHOD"] == "POST")
    {

        //Check if fields are empty
        if (empty($_POST["answer"]))
        {
            //State error code
            $answerError = 'Please answer this question.';
        }
        else
        {
            //Set answer
            $answer = $_POST["answer"];
        }

        //Check if error variables have any values assigned
        if (empty($answerError))
        {
            //Prepare database insert
            $sql = "INSERT INTO answers (questionID, username, answerBody) VALUES (?,?,?)";

            //Check if the statement has the connect and sql variables
            if ($statement = mysqli_prepare($connect, $sql))
            {
                //Add variables to the statement
                mysqli_stmt_bind_param($statement, "sss", $paramQuestion, $paramUsername, $paramAnswer);

                //Set the parameter to the answer
                $paramQuestion = $_POST["questionID"];
                $paramUsername = $_SESSION["username"];
                $paramAnswer = $answer;
                

                //Execute statement with entered variable
                if (mysqli_stmt_execute($statement))
                {
                    //Redirect user to success page
                    header("location: thankyou.php");
                }
                else
                {
                    echo "Something went wrong. Please try again later.";
                }

                //Close statement
                mysqli_stmt_close($statement);
            }
        }

    }
?>

<!DOCTYPE html>
<lang='en'>
    <html>
    <head>
    <title>Survey</title>
    <link rel="stylesheet" href="CSS/style.css">
    </head>
    <body>

        <div class="wrapper">
        <div class="header"><?php head(); ?>
        <form align="right" name="form1" method="post" action="logout.php">
        <p>Welcome, <?php echo $_SESSION["username"] ?>.</p>
        <label class="logoutLblPos">
        <input name="submit2" type="submit" id="submit2" value="Log Out">
        </label>
        </form>
        </div>
        <div class="wrapperContent">

        <div class="content">
            
            <?php getQuestions($connect); ?>

            <button type="submit" form="questions">Submit</button>

            </form>
            </div>
            </div>
            </div>
        </div>
        <div class="footer"><p><?php if ($_SESSION["username"] == 'admin') { echo footer(); }; ?></p></div>
    </body>
    </html>

in function getQuestions:

function getQuestions($connect)
    {
        $query = "SELECT * FROM questions";
        $result = mysqli_query($connect, $query);

        if ($result)
        {
            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                $body = $row['questionBody'];
                $questionID = $row['questionID'];


                echo '<div class="entry">
                <div class="questionTitle"><h3>' . $body . '</h3>
                <form id="questions" action="survey.php" method="POST">
                <input type="hidden" name="questionID" value="' . $questionID . '" />
                <input type="text" name="answer" size="50" />
            func

            </form>
            </div>
            </div>';

            }
        }
    }

How can I access the constructor of the current subclass from the baseclass? [duplicate]

I have a class Child that extends my class Parent. The static function make_new_instance() creates an instance of the class. However, if I call Child::make_new_instance(), I will get a Parent returned. Can I somehow change the method Parent::make_new_instance() to make Child::make_new_instance() return a Child?

I’m not using the constructor for this, since in the actual code, there are multiple make_new_instance that all call the constructor. I don’t want override make_new_instance, since that would lead to a lot of code duplication across all subclassess and variations of make_new_instance.

class Parent {
    public static function make_new_instance() {
        return new Parent();
    }
}
class Child extends Parent {
}

Child::make_new_instance(); // returns Parent, should return Child

If it was not calling the constructor, I’d use static:: for this.

Attempt to read property “id” on null LARAVEL8

I’m new to laravel and I’m learning it from laracast.
Here is my problem, I’m creating a comment form and it’s php code looks like this:

<section class="col-span-8 col-start-5 mt-10 space-y-6">
    <!-- Post form -->
    <form method="POST" action="/post/{{ $post->slug }}/comments" class="border border-gray-200 p-6 rounded-xl">
        @csrf
        <header class="flex items-center">
            <img src="https://i.pravatar.cc/100?id={{ auth()->id() }}" alt="" width="40" height="40" class="rounded-full">
            <h2 class="ml-3 ">Want to participate?</h2>
        </header>
        <div class="mt-6">
            <textarea class="w-full text-sm focus:outline-none focus:ring"
             name="body"  
             cols="30" rows="10"
              placeholder="Quick,think of something to say!" ></textarea>
        </div>
    
        <div>
            <button type="submit" class="bg-blue-500 text-white uppercase font-semi-bold text-xs py-2 px-10 rounded-2xl hover:bg-blue-600">Post</button>
        </div>
                        

this is the corresponding route:

Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store']);

                   

Controller:, and I suspect there could be something wrong here 'user_id'=> request()->user()->id, and I tried numerous ways for this approach like auth()->id, Auth::user()->id

<?php

namespace AppHttpControllers;

use AppModelsPost;


class PostCommentsController extends Controller
{
    public function store(Post $post){

        
        request()->validate([
            'body'=>'required'
        ]);

        $post->comments()->create([
            'user_id'=> request()->user()->id,
            'body' => request('body')
        ]);

        return back();
    }
}

and this the migration table for comment

Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('post_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->text('body');
            $table->timestamps();                       

migration table for post:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->foreignId('category_id');
    $table->string('slug')->unique();
    $table->string('title');
    $table->text('excerpt');
    $table->text('body');
    $table->timestamps();
    $table->timestamp('published_at')->nullable();
});

If I click on post button I get the above error,tried my best to solve this problem but I couldn’t. Can someone help me what’s wrong with my code ?

php use classes in specific environment [duplicate]

I would like to write a website who shows server specific parameters like: temperature, processoruse, …

This code is different on windows and linux.
(I use windows for development and linux for production).

Is tere a design pattern who automaticaly knows which class to use?

I imagined something like this:

class Controller{
    public Main $main = new Main();
    public $temperature = $main->getTemertature;
}

class Main{
    public int getTemperature(){
        //get temperature of current environment
    }
}

class MainProduction{
    public int getTemperature(){
        //linux code
    }
}

class MainDevellopment{
    public int getTemperature(){
        //windows code
    }
}

Using class methods in another file not working in WordPress

I’m trying to include a class in PHP and to use the methods from this class in another file. My code looks like that (small reproducable example). By the way: I’m working on a WordPress environment.

Main file:

include 'class-file.php';

$cars = new Cars();
var_dump($cars->getCars());

File class-file.php:

class Cars {

  public function getCars() {
    return "No Cars";
  }

}

I get the following error:

Fatal error: Uncaught Error: Call to undefined method Cars::load() in /..../wp-content/themes/builder/includes/elements.php

Seems that my class instance is connected with another class from the theme. But why? Can I disconnect the class from any others? If yes, how?

.submit() does not act as pressing the submit button

I have a form.
When I exit the text field it should alert “HH” and submit the form – run a PHP script.
if I exit the text field, I get the alert but it is not submitted.
only pressing the submit button calls the PHP script.
what I’m doing wrong?
I found a few questions as my, tried the solution, but it not working.

    <html>
      <head>
       <script src="vendor/jquery/jquery-3.2.1.min.js"></script>
       <script>
          $(document).ready(function(){
          $("#faults_form input").blur(function(){
            alert("HH");
            $("#faults_form").submit();
            return false;
          });
        });

   </script>
    
  </head>



<body>
    <form id="faults_form" name="faults_form" action="/index.php" method="post" enctype="multipart/form-data">
    
    <label for="name">Enter server name:</label>
    
    <input type="text" name="name" value="" >
    <input type="submit" name="submit" value="Submit">
    </form>
 </body>
</html>

Redis Cli Not Working in Laravel 8 after installing it

I just installed Laravel 8 on Windows 10 and ran this command for installing Redis:

composer require predis/predis

Then at the Terminal, I tried redis-cli but not working somehow and says:

‘redis-cli’ is not recognized as an internal or external command,

So what’s going wrong here? How can I solve this issue?

Here is my config/database.php:

'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '1'),
        ],

    ],

Regular Expression in api.php in Laravel

I am beginner in Laravel.
I need validation params in my url. I need form: dd.mm.YY (01.12.1984)


Route::get('age/{ageValue}', [HomeController::class, 'age'])->name('showByDate')->where('ageValue', '[d{1,2}.d{1,2}.d{4}/]+');

but it’s not working.

How can I repair it?

How to display array items with another items in one line in php?

I am getting two arrays as parameters but I want to have one item of array to be display with another item of the array in one line. Can anyone help me, please?

   function getLists($str, array $items,$optional=null, ){
    
            $items1 = array_map(function($x) use ($optional) { return "$x $optional"; }, $items);
            $itemsCount = count($items1);
            $sentence = '';
            if ($itemsCount == 1) {
                $sentence = $items[0] . '.';
            } else {
                if($optional == null)
                {
                    $partial = array_slice($items, 0, $itemsCount-1);
                    $sentence = implode(', ', $partial) . ' and ' . $items[$itemsCount-1]; 
    
                }
                if(is_string($optional))
                {
                    $partial = array_slice($items1, 0, $itemsCount-1);
                    $sentence =   implode(', ', $partial). ' and ' . $items1[$itemsCount-1];
                }
            else
            {
                $partial = array_slice($items1, 0, $itemsCount-1);
                $sentence =   implode(', ', $partial). ' and ' . $items1[$itemsCount-1];
            }              
            }
                        
            return $str.': '.$sentence.'.';
        }

Here are what I am trying to do, the following two are working correctly

getList("What do you want",array("chocolate","icecream","shake"));
getList("Ice Cream has",array("chocolate","vanilla","mango"),"flavour");

But when I replace try to pass [] as parameter then I got an error array to string conversion warning

getList("The color required",array("green","red","blue"),['chilli','onion','berry']);

So when I pass this parameter and my output should be like: I am not getting the correct output that should be like:

The color required: green chilli,red onion and blue berry.

Instead I am getting:

The color required: green Array, red Array and blue Array.

How do I create a dynamic nested HTML table?

I have fetched student records, their marks and grades attained in their courses. Students may have varried number of courses.

How do I present the data in an HTML table like in the example below, showing the perfomance of each student in each of their course and the total number of courses taken?

Table showing students perfomance

dockerized phpmyAdmin : custom php app not loading : the url was not found on the server

I’m using phpmyadmin docker image with apache and php already installed.

I can run phpmyadmin on localhost:8080 correctly and populate a database. So the php module is loaded correctly in apache.

But I have a php app installed in /var/www with different folders and it is not loading when i go to the corresponding adress (Support/index.php). I get an apache error:

phpmyadmin    | 192.168.0.1 - - [09/Jul/2022:09:11:10 +0000] "GET /Support/index.php HTTP/1.1" 404 490 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"

Im new to apache as I usually use nginx. How can i configure it so it serves the php file correctly?

Thank you