How do I redirect the number of rows after a search?

I want to show the number of search results if there are and if not, I want to show a message that there are no results for your search

controller

 public function search(Request $request){
        $search = $request->get('search');
        $Airline['Airlines'] = DB::table('airlines')->where(DB::raw("CONCAT(id,' ',name,' ',country)"),'LIKE','%'.$search.'%')->paginate(4);
        $count = count($Airline);
        if ($count>0) {
         return redirect()->view('admin.airline',$Airline,)->with('success',$count.' records found');

        }
        else{
            return redirect()->view('admin.airline',$Airline)->with('error','No record found');
        }
        
    }

airline.blade.php

             @if(session()->has('success'))
                <div class="alert alert-success">
                    {{ session()->get('success') }}
                </div>
            @endif
            @if(session()->has('error'))
                <div class="alert alert-danger">
                    {{ session()->get('error') }}
                </div>
            @endif

PHP – Optimise read write time

I am reading 200MB of CSV file with 1344953 rows then filtering and writing into other 18 files and all within 25 seconds, but someone in my class has done it under 8 seconds.

Here is my code:

<?php    
$sid = array (
    "188" => "188",
    "203" => "203",
    "206" => "206",
    "209" => "209",
    "213" => "213",
    "215" => "215",
    "228" => "228",
    "270" => "270",
    "271" => "271",
    "375" => "375",
    "395" => "395",
    "452" => "452",
    "447" => "447",
    "459" => "459",
    "463" => "463",
    "481" => "481",
    "500" => "500",
    "501" => "501"
);
$Separator = ',';
array_map('unlink', glob("data_*.csv"));
$fp = fopen("fragment_org.csv", "r");
while (($line = stream_get_line($fp, 0, "n")) !== false) {
    $data = explode(";",$line);
    $siteID = $data[4];
    $ts = $data[0];
    $nox = $data[1];
    $no2 = $data[2];
    $no = $data[3];
    $pm10 = $data[5];
    $nvpm10 = $data[6];
    $vpm10 = $data[7];
    $nvpm25 = $data[8];
    $pm25 = $data[9];
    $vpm25 = $data[10];
    $co = $data[11];
    $o3 = $data[12];
    $so2 = $data[13];
    $loc = $data[17];
    $latlong = $data[18];
    $latlong_ext = explode(",",$latlong);
    $lat = $latlong_ext[0];
    $long = $latlong_ext[1];
    $wrr = array( $siteID, $ts, $nox, $no2, $no, $pm10, $nvpm10, $vpm10, $nvpm25, $pm25, $vpm25, $co, $o3, $so2, $loc, $lat, $long );
    if($siteID == $sid[$siteID]) {
        $fip = fopen('data_'.$siteID.'.csv', 'a');
        if(!$nox == "" || !$co == "") {
            fputs($fip, implode($Separator,$wrr).PHP_EOL);
        }
        fclose($fip);
    }
}
fclose($fp);

Much of the time is taking when writing to multiple files i.e., $fip becasue it is working faster if I am writing everything to a single file.

Can someone kindly guide me on how to optimize it more. Someone said to me this, “Simply read a line and write it out to a specific file. Avoid opening and closing lots of files repeatedly (very time consuming).” , but I am doing that.

Here is what the CSV file that I am reading looks like:
First 5 lines from CSV

Thanks for your time and looking into it.

Insert a text mixed with double and single quotes into the sql database

I have a form and I let users type some additional details for the form. What if the user enters a text mixed with single and double quotes.

ex:- I’d like to join. So we”are party”this”time’addtional’details`willbe”

I found out that, because of this text, nothing goes into the database. It means literally this thing crashes my whole program.

How do I enter it into the database using PHP or MySQL query?

I’ve tried these methods

  • Backslashes (‘)

  • JSON encode

  • str_repalce

  • htmlspecialchars with ENT_QUOTES

But nothing works for me!

Retrieve data from the name of a directory in my database

I use php and laravel. I have a column named MsgBody. In this column, there is an array as follows. I want to get the value of “conversationDesc” from this array. What should I do in the Controller and blade part for this?

"MsgBody": [
    {
      "MsgType": "TIMCustomElem",
      "MsgContent": {
        "Desc": "",
        "Data": "{"conversationDesc":"abc","deviceType":"Android","otherUserMsg":false,"sender":{"birthday":"","city":"","coin":9018,"diamonds":990992,"emotional_state":"gizlilik","family_chieftain":0,"family_id":0,"fans_count":0,"focus_count":1,"follow_id":0,"gameCurrency":990992,"gh_status":0,"head_image":"http://fw25live.oss-cn-beijing.aliyuncs.com/public/attachment/202101/29/16/6013cc8481bbc.png","is_admin":0,"is_agree":1,"is_authentication":0,"is_edit_sex":0,"is_guardian":0,"is_noble_mysterious":0,"is_open_shop":0,"is_remind":1,"is_vip":0,"item":{"Yaş":"tahmin edersiniz","Medeni durum":"gizlilik","Meslek":"host","LopMeID":"106050"},"job":"host","levelImageResId":2131232827,"login_type":0,"luck_num":"","luck_num_url":"https://test99.lopme.net/wap/index.php?ctl=luck&act=index","members_url":"https://test99.lopme.net/wap/index.php?ctl=vip_pay&act=purchase","n_svideo_count":0,"nick_name":"ibrahimozden","nick_nameFormat":"ibrahimozden:","noble_avatar":"","noble_barrage":0,"noble_car":0,"noble_car_name":"","noble_car_url":"","noble_experience":0,"noble_icon":"","noble_is_avatar":0,"noble_medal":0,"noble_name":"","noble_silence":0,"noble_special_effects":0,"noble_stealth":0,"noble_vip_type":0,"open_podcast_goods":0,"pay_car":"https://test99.lopme.net/wap/index.php?ctl=car&act=index","podcast_goods":0,"podcast_order":0,"podcast_pai":0,"proUser":true,"province":"","seconds":0,"selected":false,"sex":1,"sexResId":2131231724,"shop_goods":0,"shopping_cart":0,"showId":"106050","show_podcast_goods":0,"show_podcast_order":0,"show_podcast_pai":0,"show_shopping_cart":0,"show_svideo":1,"show_user_order":0,"show_user_pai":0,"signature":"","society_chieftain":0,"society_id":0,"society_name":"","sort_num":-1,"star_box":"","stealth":0,"ticket":1806,"token":"","use_diamonds":9018,"useable_ticket":1806,"user_id":"106050","user_level":25,"user_order":0,"user_pai":0,"v_explain":"","v_icon":"","v_type":"0","video_count":0,"viewer_guard_type":0,"vip_expire_time":"Açılmadı"},"text":"abc","type":20}",
        "Ext": "",
        "Sound": ""
      }
    }
  ]

              

The submit(update) button return an empty value, causing the update function not working

Currently doing the address part in e-commerce website application. The address needs to be edited. I have included the SQL query and PHP code well, but still can’t run. There is no error message prompt. Below is my part of the code:

As there are multiple addresses, each address has an edit and delete button. The edit button will do the editing work based on the address-id passed inside.

<?php
                    while($row = mysqli_fetch_array($address_result_query)) {
                        $address_id=$row['address_id'];
                        $_SESSION['address_id'] = $address_id;
                        echo "<td>
                              <a class='editbutton' href='editaddress.php?
                              address_id=".$address_id."'>Edit</a>
                              </td>";
?>

On the edit page, it will show the address data currently, and allow the user to modify it inside the text box. Below is the code to get the user data.

    <form  name="update_" method="post" action="editaddress.php" >
            <?php
            $address_id = $_SESSION['address_id'];
            $result2 = mysqli_query($mysqli, "SELECT * FROM user_address WHERE address_id='$address_id'");
            $row2=mysqli_fetch_assoc($result2);
            if(isset($row2['address'])!=null){
                $address = $row2['address'];
                $state = $row2['state'];
                $city = $row2['city'];
                $postcode = $row2['postcode'];
                $address_name = $row2['address_name'];
                $address_phone = $row2['address_phone'];
            }
            ?>

Code to show the data:

<div class="container_header">
                    <p>Edit Address</p>
                    <br>
                </div> 
                <label>Recipient Name:</label>
                <br>
                <input type="text" size="50" class="address_name"name="address_name" value="<?php echo $address_name;?>">           
                <br><br>

                <label>Recipient Phone:</label>
                <br>
                <input type="text" size="50" class="address_phone"name="address_phone" value="<?php echo $address_phone;?>">
                <br><br>

                <label>Recipient address:</label>
                <br>
                <input type="text" size="50" class="address"name="address" value="<?php echo $address;?>">
                <br><br>

                <input type="text" size="50" class="state"name="state" value="<?php echo $state;?>">
                <br><br>

                <input type="text" size="50" class="city"name="city" value="<?php echo $city;?>">
                <br><br>

                <input type="text" size="50" class="postcode"name="postcode" value="<?php echo $postcode;?>">           
                <br><br>

                <input type="button" onclick="location.href='index.php';" name="add_address" value="Cancel" class="cancel">
                <input type="submit" name="update_address" value="Update">
            
    </form>

When user click on the update address, below PHP will run, but it’s not. The code are inside the edit page, same location with above

if(isset($_POST['update_address']))
{   
    if(isset($_POST['address'])){
        $address = $_POST['address'];
    }else echo"address not get";
    $address_id = $_POST['address_id'];
    $state = $_POST['state'];
    $city = $_POST['city'];
    $postcode = $_POST['postcode'];
    $address_name = $_POST['address_name'];
    $address_phone = $_POST['address_phone'];

    $myquery = "UPDATE user_address SET 
                address='$address',
                state='$state',
                city='$city',
                postcode='$postcode',
                address_name='$address_name',
                address_phone='$address_phone'
                WHERE address_id='$address_id'";    
    $result = mysqli_query($mysqli,$myquery)or die(mysqli_error($mysqli));
    
    header("Location: ../profile/index.php");
}    
?>

AJAX upload multiple images using arrays

I want to make a multiple image upload function where the user can upload images and can remove specific images from the uploaded ones. So my plan was, when the user selects the images, a demo preview of the images will appear, with a remove button.

When the user selects the images, on the input change, a loop gets the files from the input and pushes them into an array. So if the user decides to upload more images, the loop will add the new ones to the array. And if the user clicks the remove button, it removes the selected item from the array.

After the user selected the images, on button click an AJAX function posts the values to a PHP file which processes it and uploads it into a datebase. So basically everything would work fine if I was POST the default input.files with the AJAX but I want to POST the array with the files in it but I get an error: undefined index.

test.html:

let array = [];
$('body').on('click', '#upload', function(e){
        e.preventDefault();
        
        var el = document.getElementById("file").files;

        for (let i = 0; i < el.length; i++) {
            array.push(el[i]);
        } console.log(array);

        $.ajax({
            url: 't.php',
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            success: function (data) {
                $('#preview').html(data);
            },
            data: array,
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
});
<html lang="en">
<head>
<title>How to upload and display multiple images in php ajax</title>
 <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
 
</head>
<body>
<style type="text/css">
#preview img{
   margin: 5px;
}
</style>
<form enctype="multipart/form-data" method="post">
    <input name="file[]" id="file" type="file" multiple />
    <input type="button" id="upload" value="Upload File" />
</form>

<div id="preview"></div>

</body>
</html>

t.php:

<?php
error_reporting(E_ALL | E_STRICT);

var_dump($_POST['data']);

for($i=0; $i<count($_POST['data']['name']); $i++){
    $target_path = $_SERVER['DOCUMENT_ROOT'].'/assets/images/uploads/';
    $ext = explode('.', basename( $_POST['data']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 
    
    if(move_uploaded_file($_POST['data']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}
?>

Display last modified date of a mysql table in php

I try to display the last modified date of one of my tables in mysql database in a php page by using this bit of code:

$qwerty = mysqli_query($connect, "SELECT update_time FROM information_schema.tables WHERE table_name = zFixtures");

It displays nothing… I look for the simplest possible solution, thank you.

Update Parameter value in laravel

Actually I have a URL like this

abc.com?country=india&state=haryana&city=karnal

I have a select option in my code like this

<select onchange="location=this.value;">
   <option value="">karnal</option>
   <option value="">panipat</option>
   <option value="">ambala</option>
   <option value="">kurukshetra</option>
</select>

Now I want to change state city parameter in URL? How can I do that?

HTML not posting file to PHP

Here is my code:

<html>
<body>

<div>
    <form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
      <input type="file" id="myFile" name="filename">
      <input type="submit" name="Submit">
    </form>
</div>


<?php
if(isset($_POST['Submit']))
{
    $file = $_POST["myFile"];
    echo("hello");
}


?>

</body>
</html>

when I run it and input a file it says: Undefined array key “myFile”

what am I doing wrong?

Upgrading from Laravel 5.5 to Laravel 9

I am upgrading an Laravel version for an old project. But I have encountered an issues with updating the AuthServiceProvider. It looks like the “validator()” method on line “Password::broker()->validator(function ($credentials) {” has been removed. Could someone give me a suggestion on how to fix it in the upgrade? I could do it differently, but I wanted to know if there was a new way to use the “validator()” method.


namespace AppProviders;

use AppHttpFormsSitesLogin;
use AppHttpFormsResetPassword;
use AppHttpFormsForgotPassword;
use IlluminateSupportFacadesPassword;
use StoneFormsHandlersLaravelFormBuilder;
use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider;


class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'AppModel' => 'AppPoliciesModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        $this->app['forms']->register(
            'forgot-password',
            new LaravelFormBuilder(view(), ForgotPassword::class)
        );

        $this->app['forms']->register(
            'reset-password',
            new LaravelFormBuilder(view(), ResetPassword::class)
        );

        $this->app['forms']->register(
            'site-login',
            new LaravelFormBuilder(view(), Login::class)
        );

        Password::broker()->validator(function ($credentials) {
            return $credentials['password'] === $credentials['password_confirmation'];
        });
    }
}

Laravel validation – how return back with errors from Request on fail?

On validation fail, I have 2 situations

  • one when I display a new error page (this is how it was done before in the app)
  • I have a form and I redirect back with input (my problem)

The app is catching the ValidationException in the exceptions Handler – so there is no back with errors for me if a request fails.
Now, I need to return back to the input with errors – from the request class, before it throws the standard ValidationException.

How do I do that from the request class pls?

The code is very basic

I have some rules…

I imagine I need a hook like – validationFailed().. in the request class?

Edit: – not API – regular monolithic PHP

<?php

namespace AppHttpRequests;

use IlluminateFoundationHttpFormRequest;
use Auth;

class LocationCodeRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $user = Auth::user();

        return [
            'new_location_code' => 'required|string|max:255|exists:bars,code|not_in:' . $user->locationCode,
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'new_location_code.not_in' => 'xxx',
            'new_location_code.exists' => 'yyy',
        ];
    }

    //I need something like this
    public function validationFailed()
    {
        return redirect()->back()->withErrors($this->validator)->withInput();;
    }
}

PHP not parsing ID correctly? [closed]

so i have a function on my website where a user can favourite a post, but when i click the button it returns error “Post ID not provided” (see below) how can i fix this?

php function:

public function toggleLike($post_id){
    $is_like = $this->isLike($post_id);
    if($is_like) {
        $query = "DELETE FROM user_like WHERE like_id = :like_id";
        $stmt = $this->Conn->prepare($query);
        $stmt->execute([
            "like_id" => $is_like['like_id']
        ]);
        return false; 
    }else{
        $query = "INSERT INTO user_like (profile_id, post_id) VALUES 
    (:profile_id, :post_id)";
        $stmt = $this->Conn->prepare($query);
        return $stmt->execute(array(
            "profile_id" => $_SESSION['user_data']['profile_id'],
            "post_id" => $post_id
        ));
        return true;
    }
}

and my toggle like Ajax is as follows:

<?php
session_start();
require_once(__DIR__.'/../includes/autoloader.php');
require_once(__DIR__.'/../includes/database.php');
if($_SESSION['user_data']){
    $post_id = (int) $_POST['post_id'];
    if($post_id) {
        $userlike = new userLike($Conn);
        $toggle = $userlike->toggleLike($_POST['post_id']);
        if($toggle) {
            echo json_encode(array(
                "success" => true,
                "reason" => "Post was added to users likes."
            ));
        }else{
            echo json_encode(array(
                "success" => true,
                "reason" => "Post was removed from users likes."
            ));
        }
    }else{
        echo json_encode(array(
            "success" => false,
            "reason" => "Post ID not provided."
        ));
    }
}else{
    echo json_encode(array(
        "success" => false,
        "reason" => "User not logged in."
    ));
}

I am expecting it to insert a like into the database
The toggle function is a javascript file and is as follows:

$(function() {
  $('body').on('click', '#addFav', function(e) {
    var post_id = $(this).data('postid');
    $.ajax({
        method: "POST",
        url: "./ajax/togglelike.php",
        dataType: 'json',
        data: {
          post_id: post_id
        }
      })
      .done(function(rtnData) {
        console.log(rtnData);
        $('#addFav').text('Removed From Favorites').attr('id', 'removeFav');
      });
  });
  $('body').on('click', '#removeFav', function(e) {
    var post_id = $(this).data('postid');
    $.ajax({
        method: "POST",
        url: "./ajax/togglelike.php",
        dataType: 'json',
        data: {
          post_id: post_id
        }
      })
      .done(function(rtnData) {
        console.log(rtnData);
        $('#removeFav').text('Add to Favorites').attr('id', 'addFav');
      });
  });
});

what is 0xFF and 0x33 means?

For example when I read pixel color from an image, why I should use

$r = round(round($rgb['red'] / 0x33) * 0x33);
$g = round(round($rgb['green'] / 0x33) * 0x33);
$b = round(round($rgb['blue'] / 0x33) * 0x33);

I’m trying to feagure it out the right hexa color of rgb when breaking a part pixel by pixel and image.