Trying to load datatable from SQL Server query with where clause on PHP site using AJAX

I was following along Dani Krossing’s video to help with using AJAX for a SQL Server query (his video is for MySQL) as I have not used AJAX queries before. Hopefully, with some guidance on what I have done so far, it will end up a good lesson for me.

I am trying to build a webpage for our stock takes. The user selects the stock take they are querying from a dropdown menu (as below) and I want to use the StocktakeID as a parameter for the query to return the table of stock with the stocktakeID.

<form method="POST" action="loadstock.inc.php"> 
    <select name="filter_stocktake" id="filter_stocktake" class="form-control" required>
        <option value="">Select a stocktake:</option>               
        <?php         
        while ($row = sqlsrv_fetch_array($result)) {
        echo '<option value="' . $row["StocktakeID"] . '">' . $row["StocktakeName"] . '</option>';
        }
        ?>
    </select>
</form>

The loadstock.inc.php code below

if (isset($_POST['filter_stocktake']))
{
    $id = $_POST["filter_stocktake"];
    $query = "SELECT [Code], [Name], [BoxQty], [RecordedQuantityInStock],
                        [ActualQuantityInStock], [ActualQuantityEntered], [DiscrepancyNarrative],[Barcode], [QtySoldSinceSnapshot], [StocktakeCountShtItemID]
                    FROM [StockTakeStockSheet]
                    WHERE StocktakeID = '$id'";
    $stmt = $conn->sqlsrv_query($conn, $query);
    while ($row = sqlsrv_fetch_array($stmt)) {
        echo '
             <tr>
                 <td>' . $row["Code"] . '</td>
                 <td>' . $row["Name"] . '</td>
                 <td>' . $row["BoxQty"] . '</td>
                 <td>' . $row["RecordedQuantityInStock"] . '</td>
                 <td>' . $row["ActualQuantityInStock"] . '</td>
                 <td>' . $row["ActualQuantityEntered"] . '</td>
                 <td>' . $row["DiscrepancyNarrative"] . '</td>
                 <td>' . $row["Barcode"] . '</td>
                 <td>' . $row["QtySoldSinceSnapshot"] . '</td>
                 <td>' . $row["StocktakeCountShtItemID"] . '</td>
             </tr>
         ';
    }
        
}
else
{
    $id = null;
    echo "No stocktake ID supplied";
}

All I am getting when I submit the stocktake option is the “No stocktake ID supplied” message.

Below is the AJAX lines based on Dani Krossing’s video –

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    var stockID = '';
    $("button").click(function(e) {
        var button = $(e.relatedTarget)     
        var stocktakeID = button.data('stockID')
        $("#stock_data").load('includes/loadstock.inc.php', {
            filter_stocktake: stocktakeID
        });
    });
});
</script>

Am I very far away from getting this right? If you had any guidance or resources that you believe would help me get over the line, I would be really appreciative.

If I have left anything out or you require more details, let me know.

Thank you!

Error in the php code”Uncaught mysqli_sql_exception: Field ‘likes’ doesn’t have a default value in”

I want to implement the functionality of likes and dislikes in my project. But when I start it, it shows me an error:

Uncaught mysqli_sql_exception: Field ‘likes’ doesn’t have a default value in E:OSPaneldomainslocalhostTrynditterindex.php:22 Stack trace: #0 E:OSPaneldomainslocalhostTrynditterindex.php(22): mysqli_query(Object(mysqli), ‘INSERT INTO pos…’) #1 {main} thrown in E:OSPaneldomainslocalhostTrynditterindex.php on line 22

I used: HTML,PHP,MySQL,JS,JQuery.
I took the line: mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Then the error disappears, but the rest of the functionality stops working.

index.php

<?php require_once "header.php"; ?>

<html>
<body>
     <?php
     //if (isset($_SESSION["user_login"])) echo 'user_login_Isset';
     $edit_id=$_GET['edit'];
     $text_for_edit = $_GET['text'];
     $Posts_Text = $_POST['post_text'];
     $user_login = $_SESSION["user_login"];
     $likes =$_Get['likes'];
     
     if(isset($_GET['logout'])) //exit session
     {
        unset($_SESSION["user_login"]);
        header("location:index.php");
    }
     
     if(isset($_POST['post_text']) && (!isset($_GET['edit'])) ) //ноий tweet
     {
        $sql = "INSERT INTO posts (posts_text, posts_date, user_login) VALUES('$Posts_Text',now(), '$user_login')";
        $result = mysqli_query($con,$sql);
         if($sql){
            header("location:index.php");
        }
        
    }
    
     if(isset($_POST['post_text']) && (isset($_GET['edit'])) ) //редагування
     {
        $sql = "UPDATE posts SET posts_text='$Posts_Text' WHERE posts_id=$edit_id";
        $result = mysqli_query($con,$sql);
         if($sql){
            header("location:index.php");
        }
    }
    
    if(isset($_GET['del'])) //Видалення
    {
        $Del_ID = $_GET['del'];
        $sql="delete from posts where posts_id='$Del_ID'";
        $post_query = mysqli_query($con,$sql);
        if($sql){
            header("location:index.php");
        }
    }
   
    ?>
    


    <div class="grid-container">

   

    <?php require_once "left-sidebar.php";?>
    <div class="main">
    <p class = "page_title"><?php if (isset($_GET['edit'])) echo 'Editing mode'; else echo 'Trynditter'; ?></p>
        <div class="tweet__box tweet__add" <?php if (!isset($_SESSION["user_login"])) echo 'hidden';?> >

            <div class="tweet_left">
              
            </div>
            <div class="tweet__body">
                <form method="post" enctype="multipart/form-data">
                <textarea name="post_text" id="" cols="100%" rows="3" placeholder='What is happening?'><?php echo $text_for_edit; ?></textarea>
                <?php while ($row = mysqli_fetch_array($posts_text)) { ?>

<div class="post">
    <?php echo $row['text']; ?>

    <div style="padding: 2px; margin-top: 5px;">
    <?php 
        // determine if user has already liked this post
        $query = mysqli_query($con, "SELECT * FROM likes WHERE user_id=1 AND post_id=".$row['id']."");

        if (mysqli_num_rows($query) == 1 ): ?>
            <!-- user already likes post -->
            <span class="unlike fa fa-thumbs-up" data-id="<?php echo $row['id']; ?>"></span> 
            <span class="like hide fa fa-thumbs-o-up" data-id="<?php echo $row['id']; ?>"></span> 
        <?php else: ?>
            <!-- user has not yet liked post -->
            <span class="like fa fa-thumbs-o-up" data-id="<?php echo $row['id']; ?>"></span> 
            <span class="unlike hide fa fa-thumbs-up" data-id="<?php echo $row['id']; ?>"></span> 
        <?php endif ?>

        <span class="likes_count"><?php echo $row['likes']; ?> likes</span>
    </div>
</div>

<?php } ?>

                    <button class="button__tweet" type="submit" name="btn_add_post">Tryndit</button>
                </div>
                </form>
            </div>
        </div>
   <?php require_once "tweet.php" ?>
    </div>
    </div>
    <?php require_once "right-sidebar.php";?>
    <script src="jquery.min.js"></script>
<script>
    $(document).ready(function(){
        // when the user clicks on like
        $('.like').on('click', function(){
            var postid = $(this).data('id');
                $post = $(this);

            $.ajax({
                url: 'index.php',
                type: 'post',
                data: {
                    'liked': 1,
                    'post_id': postid
                },
                success: function(response){
                    $post.parent().find('span.likes_count').text(response + " likes");
                    $post.addClass('hide');
                    $post.siblings().removeClass('hide');
                }
            });
        });

        // when the user clicks on unlike
        $('.unlike').on('click', function(){
            var post_id = $(this).data('id');
            $post = $(this);

            $.ajax({
                url: 'index.php',
                type: 'post',
                data: {
                    'unliked': 1,
                    'post_id': post_id
                },
                success: function(response){
                    $post.parent().find('span.likes_count').text(response + " likes");
                    $post.addClass('hide');
                    $post.siblings().removeClass('hide');
                }
            });
        });
    });
</script>
    </body>
    </html>

db.php

<?php
 error_reporting(E_ERROR | E_PARSE);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con  = mysqli_connect("localhost","root","","twitter");
$select_db=mysqli_select_db($con,'twitter');
if(!con){
   die("Not Connected");
   
}
?>

header.php

<?php

ob_start();
session_start();
require_once('db.php');
?>

<!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>Trynditter</title>
    <link rel="shortcut icon" href="imagesTrynditter.jpg" type="image/jpg">
    <link href="cssstyle.css" rel="stylesheet" type="text/css">
    <link href="csstweet-box.css" rel="stylesheet" type="text/css">

    <link href="cssright-sidebar.css" rel="stylesheet" type="text/css">
    <link href="cssleft-sidebar.css" rel="stylesheet" type="text/css">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
 
</body>
</html>

MySQL

Структура таблиці `likes`
--

CREATE TABLE `likes` (
  `id` int NOT NULL,
  `user_id` int NOT NULL,
  `post_id` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;

-- --------------------------------------------------------

--
-- Структура таблиці `posts`
--

    CREATE TABLE `posts` (
      `posts_id` int NOT NULL,
      `posts_text` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci NOT NULL,
      `posts_date` date NOT NULL,
      `user_login` varchar(20) NOT NULL,
      `likes` int NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
    
    --
    -- Дамп даних таблиці `posts`
    --
    
    INSERT INTO `posts` (`posts_id`, `posts_text`, `posts_date`, `user_login`, `likes`) VALUES
    (148, 'bfbbbbbt', '2022-10-05', 'petro', 0);
    
    -- --------------------------------------------------------
    
    --
    -- Структура таблиці `users`
    --
    
    CREATE TABLE `users` (
      `id` int NOT NULL,
      `login` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci NOT NULL,
      `password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci NOT NULL,
      `name` varchar(255) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
    
    --
    -- Дамп даних таблиці `users`
    --
    
    INSERT INTO `users` (`id`, `login`, `password`, `name`) VALUES
    (33, 'Roma', '123', ''),
    (34, 'Petro', '333', ''),
    (35, 'roma', '123', '');
    
    --
    -- Індекси збережених таблиць
    --
    
    --
    -- Індекси таблиці `likes`
    --
    ALTER TABLE `likes`
      ADD PRIMARY KEY (`id`);
    
    --
    -- Індекси таблиці `posts`
    --
    ALTER TABLE `posts`
      ADD PRIMARY KEY (`posts_id`);
    
    --
    -- Індекси таблиці `users`
    --
    ALTER TABLE `users`
      ADD PRIMARY KEY (`id`);
    
    --
    -- AUTO_INCREMENT для збережених таблиць
    --
    
    --
    -- AUTO_INCREMENT для таблиці `likes`
    --
    ALTER TABLE `likes`
      MODIFY `id` int NOT NULL AUTO_INCREMENT;
    
    --
    -- AUTO_INCREMENT для таблиці `posts`
    --
    ALTER TABLE `posts`
      MODIFY `posts_id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=152;
    
    --
    -- AUTO_INCREMENT для таблиці `users`
    --
    ALTER TABLE `users`
      MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36;
    COMMIT;

JSON TO PHP ARRAY READ DATA [duplicate]

i’m very new to php,json and array.

i decode the json to array with $obj=json_decode($data,true);

the json is:

{
   "events":[
      {
         "id":"3433333",
         "appointment":{
            "id":"12907641",
            "start_date":"2022-10-28T11:20:00+02:00",
            "end_date":"2022-10-28T11:40:00+02:00",
            "duration":20,
            "status":"confirmed",
            "notes":null,
            "agenda_id":"11",
            "agenda_label":"AAAAA",
            "visit_motive_id":"111",
            "visit_motive_label":"BBBBBBB",
            "patient":{
               "id":"32621033",
               "last_name":"Pluto",
               "first_name":"Giovanni",
               "maiden_name":null,
               "gender":null,
               "birthdate":"1988-02-01",
               "phone_number":"+xxxxxxxxxxxxxx",
               "secondary_phone_number":"+xxxxxxxxxxxxx",
               "email":"[email protected]",
               "address":null,
               "zipcode":null,
               "city":null
            }
         }
      }
   ]
}

i need to read the events id and all the appointment data and the patient data.

i tryed with:

$fl = $obj['events']['id'];

and with

$fr = $obj['events']['appointment']['id'];

but it is wrong.

Any help will be very appreciated

Thank you

How do i store the users email and password from my website into an SQL database [closed]

I want to store the users email and password from my website in an SQL database. This is the html:

  <form class="signup" name="signupForm" onsubmit="return validatesignupForm()" method="POST">

    <label for="firstname"> First Name: </label>
    <input type="text" name="fname" id="firstname" placeholder="Enter your First Name" />

    <label>Last Name</label>
    <input type="text" name="lname" id="lastname" placeholder="Enter your Last Name" />

    <label>Email</label>
    <input type="text" name="email" id="useremailsignup" placeholder="[email protected]" />

    <label>Password</label>
    <input type="password" name="password" id="pwordsignup" placeholder="Enter your Password" />

    <label>Confirm Password</label>
    <input type="password" name="password2" id="pwordsignup2" placeholder="Confirm your Password" />

    <input type="submit" value="Sign up">


  </form>

PHP in Windows: add an environment variable for User or Machine

I am trying to update the Path environment variable in Windows with a PHP script, but if I use putenv() it doesn’t change. I can get the paths list in the Path variable but I am not able to update it.
Another problem is that if I use getenv('Path') to get the paths list, I have a unique string with all paths merged from the Path variable of User and of the Machine.

I’m wondering if there is a better way to do that, maybe acting directly in the registry key to update User Path variable.

Why can’t I populate appended select in php?

clientAdd.php


                    $office = "SELECT * FROM tblOffice";
                    $office_qry = mysqli_query($conn, $office);

                    ?>

                       <div class="input-field"> 
                        <label> Office </label>
                    <select id="office-dd" name="office-dd">
                    <option disabled selected value>Select Office</option>
                        <?php while ($row = mysqli_fetch_assoc($office_qry)) : ?>
                            <option value="<?php echo $row['officeId']; ?>"> <?php echo $row['officeName']; ?> </option>
                            <?php endwhile; ?>
                    </select>
                        </div> 


<div class="clientAddPosi" id="clientAddPosi">
          <label for="formGroupExampleInput"> Position Title </label>
                <div class="form-group">
                    <input type="text" class="form-control" id="filterPosi" placeholder="Filter Positions" name="filterPosi" style=" transition: ease 0.4s;">
                      <select class="form-control" id="posi-dropdown" name="posi-dropdown" style="transition: ease 0.4s !important;" multiple="multiple">
                    </select>
                <hr>
                </div>
        </div>


 $('#office-dd').on('change', function() {
        var officeId = this.value;
        // console.log(country_id);
        $.ajax({
            url: '../Module - Client/fetch-position.php',
            type: "POST",
            data: {
                officeData: officeId
            },
            success: function(result) {
                $('#posi-dropdown').html(result);
                $('#posiDDEarn').html(result);
                $('#poSI').html(result);
            }
        });
    });

The #posi-dropdown, #posiDDEarn are all working fine since they are hardcoded in the other file (clientEarningsInsert.php) but when adding the select which is #poSI, it’s not working

clientEarningsInsert.php

        <div class="form-group" style="transition: ease 0.4s !important; margin-bottom: 23px;">
            <select class="form-control" name="posiDDEarn" id="posiDDEarn" onchange="getId(this.value)">
            <option value=""></option>
             </select>
        </div>  

 <button type="button" class="btn btn-primary btn-lg btn-block" style="width: 100% !important; margin-top: 6% !important" onclick="clientAddWage()" id="AddPosition"> Add Earning </button>
 

 function clientAddWage() {
      $("#clientAddWage").append(   
        `<div id="newWage"> <label for="formGroupExampleInput"> Position Title </label>
        <div class="form-group" style="transition: ease 0.4s !important; margin-bottom: 23px;">
           <select class="form-control" name="poSI" id="poSI" onchange="getId(this.value)">
            <option value=""></option>
             </select> 
 );
      wageIndex++;
    }

Output

enter image description here

I’m really sorry if the code is not clean/written well, I’m still a beginner and looking for ways to improve. Any help regarding this would be of great help to me. Thank you!

how to use return with url function in Laravel

I want to redirect the same page when error occurs.
so i want to use return with url .
is that possible ?

 <?php
                    if(DB::connection()->getDatabaseName()==null){
                        session()->put('error', 'your .env file has error');
                        ?><a href="{{url('installer')}}">home</a>
                        <?php
                        return url('installer');
                    }?>

I am facing this error at the time of artisan migration

I am facing this error at the time of configuration my laravel 6.2 project with PHP 7.2.5 to MSSQL SERVER and I have added in .env file

DB_CONNECTION=sqlsrv

DB_HOST=”DESKTOP-AMCDA5K”

DB_PORT=1433

DB_DATABASE=”AuditReferences”

DB_USERNAME=”sa”

DB_PASSWORD=”admin123″

DB_ENCRYPT=true

DB_TRUST_SERVER_CERTIFICATE=false

for view server connection page is here
server login page

and I have added all dll files in php.ini file setting and pdo_sqlsrv, sqlsrv are shown in phpinfo page

$ php artisan migrate

 IlluminateDatabaseQueryException  : could not find driver (SQL: select * from sysobjects where type in ('U', 'V') and name = migrations)
 at C:wamp64wwwLaravellaravelProjvendorlaravelframeworksrcIlluminateDatabaseConnection.php:669
665|         // If an exception occurs when attempting to run a query, we'll format the error
666|         // message to include the bindings with SQL, which will make this exception a
667|         // lot more helpful to the developer instead of just the database's errors.
668|         catch (Exception $e) {
> 669|             throw new QueryException(
670|                 $query, $this->prepareBindings($bindings), $e
671|             );
672|         }
673|

Exception trace:

1   PDOException::("could not find driver") C:wamp64wwwLaravellaravelProjvendorlaravelframeworksrcIlluminateDatabaseConnectorsConnector.php:70

2   PDO::__construct("dblib:host=DESKTOP-AMCDA5K:1433;dbname=AuditReferences;charset=utf8", "sa", "admin123", []) C:wamp64wwwLaravellaravelProjvendorlaravelframeworksrcIlluminateDatabaseConnectorsConnector.php:70

json_decode all the array values of an php array

I have an array similar to:

[ "id" => "90bbc6f8"
  "user_id" => "7a88a06f"
  "country" => "Greece"
  "region" => null
  "users" => "[]"
  "emails" => "[]"
]

but having hundreds of values, I need to decode the arrays like “users” and “mails”, is there a way to apply json_decode to the values without going through foreach loop? paying attention to the performance

Trying to access rowid of phpgrid in another page but not getting it in PHP

    I want to retrieve rowid of a phpgrid on the page the same i included it using SESSION e.g
    
         $id=$_SESSION['id'];
    
            However when it use var_dump($id); I get respond String(8) without the actual value. 
           Below 
            is my code.
      



 1. lasttest.php
    
        <?php
         require_once('../phpGrid_Lite2/conf.php');       
        ?>
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
         <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
         <head>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Select Multiple Rows</title>
         <script type="text/javascript">
    
        </script>
        </head>
         <body> 
    
         <?php
    
          $dg = new C_DataGrid("SELECT * FROM uploaded", "id", "treated"); 
    
    
    
         $onSelectRow1 = <<<ONSELECTROW
          function(status, rowid)
          {
          //alert('event 1');
          console.log(rowid);
          console.log(status);
       
        /* example to redirect a new URL when select a row */
        cabinet = $('#uploaded').jqGrid('getCell',rowid,'cabinet');
        cabinet_name = $('#uploaded').jqGrid('getCell',rowid,'cabinet_name');
        //alert(rowid);
         //window.location = encodeURI("http://example.com/" + "?" + "cabinet=" +cabinet + 
         "&cabinet_name="+cabinet_name);
         }
         ONSELECTROW;
         $dg->add_event("jqGridSelectRow", $onSelectRow1);
         $dg -> display();
          ?>
          </body>
          </html>
    
    
            2. retrieverowid.php
                <?php
        require_once('checklogin.php');
        $date=@date('l jS of F Y h:i:s A');
        require_once('connect1.php');
        $do = new db;
        $do->doconnect();
        //Get Return Page
        $username=$_SESSION['username'];
        //$cate=$_SESSION['cate'];  
        $mytype = $_SESSION['mytype'];
        $Link =$_SESSION['link']; 
            $count = count($Link);
            $loggedUBranch= $_SESSION['cate'];

        $uploaddir = "uploadsbenefit/"; 



            $command = "";
            if (isset($_POST['Submit'])) {
            $myfilename = $_FILES['file']['name'];
            $FileToAddSize =$_FILES['file']['size'];
            
            $ispdf = @end(explode(".",$myfilename));
            //$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
            $ispdf = strtolower($ispdf);
            
             if($ispdf !='pdf'){
             echo "Sorry, You can only merge PDF files, press browser back button to continue";
             exit;
             }
             
             //Get original filename from the database
            $id = $_SESSION['id'];
            var_dump($id);
            
            $Orig = $do->gett("select * from uploaded where id ='$id'");
            $OriginalFileNameOnServer = "uploadsbenefit/".$Orig['file_name'];
?>
</table></td>
                <td valign="top" width="73%"bgcolor="#FFFFFF">
                
                                <div align="center"><span id=""></span>
                                  
                                        <div id = 'retrievetable' class="style17" >
                                                <?php include 'lasttest2.php'?>
                                            
                                  </div>

                                    <table style="width: 700px; height: 14px;" align="center" width="706">
                                        <tbody>
                                        <tr>
                                        <td>
                                        <div id = "myresult" align="left">
                                        </div>
                                        <div>
                            
                                        </div>
                                        
                                        
                                        <div class="uploader">          
            
                                                <form id ="actionform" method="post" action="" enctype="multipart/form-data">
                                                <p> <input name="file" id="file[]" type="file" /></p>  
                                                <p>Allowed Files: .pdf </p>
                                                 <input type="submit" name="Submit" value="Merge Files" />
                                                 <input type="button" name="Delete" id = "deletebtn" value="Delete Selected" />
                                                </form>
                                                                            
                                         </div>`enter code here`

I want a sitiuation whereby when I click on the Merge files Button i should be able to retrieve the clicked rowid using Sesssion which i will thereafter use it to select the actual selected row from the database. I have tried several options but it is not working for me. anytime i try using var_dump($id) i get string(8) without the actual rowid number.

Thank you in advance

php only displaying first result from sql query

I’m very new to PHP and I’m trying to get some code that someone else has written to work. As the title says it is only showing the first result when it should be displaying many and I have no idea how to sort it (even though I imagine it’s quite simple!). The code is below:

$result = mysqli_query($connection, ("SELECT id FROM details where publicposition like '%$trimvar%'  or familyorgname like '%$trimvar%' or commercialorgind like '%$trimvar%' ORDER BY id "));
if (!$result)
{
    die('Could not run query');
    }


echo "<h1>Your staff conflict search on <font color='#ff0000'>'$trimvar'<font color='#000'> returned <font color='#ff0000'>$rows<font color='#000'> results</h1>";



$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
{ 

    echo "<table style='width: 20%; border='0';'>"; 
    echo "<tr>";
    echo "<th> Record ID : " . $row['id'] . "</th><br/>";
    echo "</tr>";

}
echo "</table>";

Any help on this would be hugely appreciated!

Symfony how autowire a class specifique?

How can we have AutoWire active on calls in the 2nd child of the controller.

Here are different examples to explain my problem.

First exemple :

@Route("/user")

class UserControler extends AbstractController {

@Route("/", name="user_index", methods={"GET"})

public function index(UserRepository $userRepository) : Response {

if(!$userRepository instanceof UserRepository){
    throw new Exception('is not instance of UserRepository');}
}

  return new JsonResponse(['succes' => "test"]);
}

it’s ok, i don’t have problem here, the autowire has instantiate UserRepository


In this example, the Test1 class will be instantiated in the user controller, it takes a UserRepository in the contructor the auto wire will provide it

class Test1  {

    public function __construct (UserRepository $userRepository)  {

        if(!$userRepository instanceof UserRepository) {
            throw new Exception('is not instance of UserRepository');
        }
    }
} 
-
class UserControler extends AbstractController {

@Route("/", name="user_index", methods={"GET"})

public function index(Test1 $test1 ) : Response {
 


  return new JsonResponse(['succes' => "test"]);
}

None error trow, i have a instance of UserRepository, i can used it.


Now i want UserControler instanciate class Test1 and call method try().

The method try() instantiate the classe Test2 who need UserRepository in construtor.

class Test1  {

    public function try()  {
         new Test2();
         
    }
} 

class Test2  {

    public function __construct (UserRepository $userRepository)  {

        if(!$userRepository instanceof UserRepository) {
            throw new Exception('is not instance of UserRepository');
        }
    }
} 
-
class UserControler extends AbstractController {

@Route("/", name="user_index", methods={"GET"})

public function index(Test1 $test1 ) : Response {
 
  return new JsonResponse(['succes' => "test"]);
}

Autowire not working here, is possible ?


PHP testing emptying out collection

I’m currently trying to write PHP tests using pest for a search feature within a chat component. The component works fine when being used in my test environment though i’m unable to get a certain test to pass. The objective is to be able to return multiple messages that meet a specific search term.

Here is the test itself in ChatSearchTest.php:

/** @test */
    public function the_component_can_return_multiple_search_results()
    {
        $messages_fixed_content = ChatMessage::factory(2)
        ->for($this->members[0], 'from')
        ->for($this->members[1], 'to')
        ->create([ 
            'content' => 'test123'
        ]);

        $messages_random_content = ChatMessage::factory(1)
        ->for($this->members[0], 'from')
        ->for($this->members[1], 'to')
        ->create();

        $messages = $messages_fixed_content->merge($messages_random_content);
         
        $chat_search = 'test123';
        
        $component = Livewire::test(ChatSearch::class, ['partnership' => $this->partnership])
            ->set('chat_search', $chat_search)
            ->call('getSearchResults', $chat_search);
            ->assertCount('messages', 2);
    }   

And the relevant code it’s testing in ChatSearch.php:

public function updatedChatSearch()
    {
        $this->getSearchResults();
    }

    public function getSearchResults()
    {
        $search_results = $this->getMessagesQuery()->get();
        $this->messages = $search_results;
        
        $this->have_results = true; 
    }

    protected function getMessagesQuery()
    {
        $query = $this->partnership
            ->chatMessages()
            ->with('from')
            ->with('shareable');
        if ($this->chat_search) {
            $query->search('content', $this->chat_search);
        }
        $query->latest();
        
        return $query;
    }

    public function goToMessage($message_id)
    {
        $this->emitUp('goToSearchResult', $message_id);
    }

The issue is that $this->messages returns an empty collection during the test, whereas on the actual testing environment, it works. If I dump out at the end of getSearchResults() it correctly shows $this->have_results as true though $this->messages returns an empty collection, as does $search_results.