HTML comment tags prevent PHP execution [duplicate]

I have PHP code at the top of my document and I want to surround it with HTML comment tags so that it is commented out in the source code in my dev environment.

<!--
<?php
session_start();
lib->checkSession();
?>
-->

<html>
my website
</html>

Normally, HTML comment tags shouldn’t prevent the php from executing but somehow it does. Is that configurable?

Warning: Attempt to read property “username” on null in C:UsershpDesktopxampphtdocs19Aprilmain.php on line 33

I am trying to fetch data from the database and getting the error as:

Warning: Attempt to read property “username” on null in C:UsershpDesktopxampphtdocs19Aprilmain.php on line 33

Please suggest/guide me through the solution

My main.php file

<!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>Document</title>
</head>
<body>
    <h3>Search Meetings</h3>
    <form action="" method="POST">
        <!-- <label>Enter Your Name:</label><br /> -->
        <input type="text" name="username" placeholder="Your Name" required/>
        <br /><br />
        <button type="submit" name="submit">Search</button>
    </form>  
</body>
</html>

<?php

if(isset($_POST['username']) && $_POST['username']!=""){
    $username = $_POST['username'];
    $url = "http://localhost/19April/api/".$username;

    $client = curl_init($url);
    curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
    $response = curl_exec($client);
    
    $result = json_decode($response);
    
    // echo "<table>";
    echo "<tr><td>User Name:</td><td>$result->username</td></tr>";
    // echo $result->$username;
    // echo "<tr><td>Age:</td><td>$result->age</td></tr>";
    // echo "<tr><td>Email-Id:</td><td>$result->email</td></tr>";
    // echo "</table>";
}
?>

My api.php file

<?php
header("Content-Type:application/json");

if (isset($_GET['username']) && $_GET['username']!="") {
    include('db.php');
    $username = $_GET['username'];
    $result = mysqli_query($con,"SELECT * FROM `transactions` WHERE username=$username");

    if(mysqli_num_rows($result)>0){
        $row = mysqli_fetch_array($result);
        $username = $row['username'];
        $age = $row['age'];
        $email = $row['email'];
        response($username, $username, $age,$email);
        mysqli_close($con);
    }else{
        response(NULL, NULL, 200,"No Record Found");
    }
}else{
    response(NULL, NULL, 400,"Invalid Request");
}

function response($username,$age,$email){
    $response['username'] = $username;
    $response['age'] = $age;
    $response['email'] = $email;
    
    $json_response = json_encode($response);
    echo $json_response;
}
?>

How to use ACF in WordPress to add multiple images to a custom page template?

I have a number of pages (400) which are all build individually in a visual editor (DIVI), even though they are identical other than the images on each page – This was my first website and so I knew no better than this approach when I began.

They are all child-pages of pageX and their slug begins with a common word. eg:

mysite.com/pageX/commonword-page1/

mysite.com/pageX/commonword-page2/

If I wanted to use a custom page template and insert unique images for each page, how would I go about doing this? Would adding an advanced custom field for each page containing an array of image ids/urls be a good option? Then simply call this and loop through each one and insert into the DOM?

Base64 Image not properly display after Update

I am trying to update of an blob image using base64_encode but when I pressed button Update its successfully update the text and image however the image is not properly display

HERE’S MY EDIT CODE:

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

    $updateitemName = $_POST['itemName'];
    $updateitemDescription = $_POST['litemDescription'];
    $updateitemPrice = $_POST['itemPrice'];

    //when user upload image to update
    if(isset($_FILES['itemIMG']['name'])){
        $updateImage = $_FILES['itemIMG']['name'];
        $updateimageTempLoc = $_FILES['itemIMG']['tmp_name'];
        $pathIMG = "image/".base64_encode($updateImage);
        move_uploaded_file($updateimageTempLoc,$pathIMG);

        $sql = "UPDATE item SET ITEM_NAME = '$updateitemName',
        ITEM_DESCRIPTION = '$updateitemDescription',
        ITEM_IMG  = '$updateImage',
        ITEM_PRICE = '$updateitemPrice'  WHERE ITEM_ID = $updateitemID";

        $results=mysqli_query($conn,$sql);

        if($results){
            $messages = "Successfully updated Item";
            echo "<script type='text/javascript'>alert('$messages');window.location.replace('item.php');</script>";
        }else{
            die(mysqli_error($conn));
        }

        //if the user update the text only not inlcude the image          
    }else{
        
        $sql = "UPDATE item SET ITEM_NAME = '$updateitemName',
        ITEM_DESCRIPTION = '$updateitemDescription',
        ITEM_PRICE = '$updateitemPrice'  WHERE ITEM_ID = $updateitemID";

        $results=mysqli_query($conn,$sql);
        if($results){
            $messages = "Successfully updated Item";
            echo "<script type='text/javascript'>alert('$messages');window.location.replace('myinventoryitem.php');</script>";
        }else{
            die(mysqli_error($conn));
        }
    }
}

in csv file data is not in proper format show some html code in cakephp

data in csv file is not in proper format it show like as javascript code or html code in only one coloumn

code in userscontroller 

for export data in csvfile from database of user table
public function export() {

            $this->response->download("export.csv");
    
            $data = $this->Users->find('all');
            $this->set(compact('data'));
    
            $this->layout = 'ajax'; 
    
            
    
            return;
    
        }
    
    // app/Views/Users/export
    
    header('Content-type: text/csv');
    header("Content-Disposition: attachment; filename=export.csv");  
        
    
    
    foreach ($data as $row){
        foreach ($row['Users'] as $cell){
            // Escape double quotation marks
            $cell = '"' . preg_replace('/"/','""',$cell) . '"';
        }
        echo implode(',', $row['Users']) . "n";enter code here
    }
    
    

//image of output

      [1]: https://i.stack.imgur.com/SH5iF.png

How do I assign a string to $_SESSION?

The value of the two problematic session variables I get are NULL after passing all 3 if statements.

the login session variable works fine, it changes to true. I’ve tried removing the first appearance of the two problematic session variables, but those two variables stopped existing once I did that.

<?php
    session_start();
    include("sambungan.php");
    $_SESSION["login"] = false;
    $_SESSION["nama_pengguna"] = NULL; #Problem
    $_SESSION["kata_laluan"] = NULL;  #Problem

    if ($_POST) {
        $nama_pengguna = $_POST["nama_pengguna"];
        $kata_laluan = $_POST["kata_laluan"];
    
        if (isset($_POST["daftar"])) {
            $sql = "INSERT INTO urusetia (nama_pengguna,kata_laluan) VALUES ('$nama_pengguna','$kata_laluan')";
            $result = mysqli_query($sambungan,$sql);
            if ($result) {
                $_SESSION["login"] = true;
                $_SESSION["nama_pengguna"] = $nama_pengguna; #Problem
                $_SESSION["kata_laluan"] = $kata_laluan; #Problem

                $_POST = array();
                header("Location:./hakim.php");
                die();
            }
        }
    ...

Insert Failed : SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table

i need help!

I have a relation data like this:
enter image description here

i want to pluck 2 columns from relation mail->mail meta.

so far i have tried this:

$data= AppModelsMailRevisionHistory::with(['mail.mail_meta'])
    ->where('mail_id',$request->mail_id)
    ->first()
    ->pluck('mail.mail_meta.id','mail.mail_meta.key'); 

but i have an error like this:

{"status":1,"message":"Insert Failed : SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "mail_meta"nLINE 1: select "mail"."mail_meta"."key" from "trx_mail_revision_hist...n ^ (SQL: select "mail"."mail_meta"."key" from "trx_mail_revision_history")"

please correct where did i go wrong

why does my PHP PDO in MySQL fails with Integrity Constraint Violation error when the data is present in the table (SQLSTATE 23000, 1452) [closed]

I have a strange issue with my PHP PDO with MySQL on Windows 10, which fails with an Integrity Constraint Exception while attempting to store a record in the child table despite the entry in parent gets created successfully.

I have the following tables in my Database, namely TblUser, TblRole, TblUserRole and TblStudent – where I capture the essential info of the logged in User in TblUser, and the master roles in TblRole, the mapping of User and Roles in TblUserRole, the details of the students in TblStudent.

The ID column of the TblUser is a FK in TblUserRole and TblStudent, and the ID Column of TblRole is a FK in TblUserRole.

TblUser

CREATE TABLE TblUser
(
  Id int primary key auto_increment not null,
  UserId VARCHAR(50) UNIQUE NOT NULL COMMENT 'Unique Registration No',
  Password VARCHAR(50) NOT NULL
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;

TblRole

CREATE TABLE TblRole
(
  Id int primary key auto_increment not null,
  Name VARCHAR(50) UNIQUE NOT NULL COMMENT 'The name of the Role',
  Description VARCHAR(50) NOT NULL COMMENT 'The Description of the Role'
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;

TblUserRole

CREATE TABLE TblUserRole
(
  Id int primary key auto_increment not null,
  UserId INT NOT NULL COMMENT 'The Id of the User',
  RoleId INT NOT NULL COMMENT 'The Id of the Role',
  UNIQUE INDEX (UserId, RoleId),
  CONSTRAINT fk_UserRole_UserId
    FOREIGN KEY (UserId)
        REFERENCES TblUser(Id)
  CONSTRAINT fk_UserRole_RoleId
    FOREIGN KEY (RoleId)
        REFERENCES TblRole(Id)
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;

TblStudent

CREATE TABLE TblStudent
(
  Id int primary key auto_increment not null,
  UserId INT NOT NULL COMMENT 'The Id of the User',
  RegnNo VARCHAR(15) UNIQUE NOT NULL,
  Name VARCHAR(50) NOT NULL,
  DOB DATE NOT NULL,
  Gender CHAR(1) NOT NULL,
  Department VARCHAR(50) NOT NULL,
  Year INT NOT NULL
  CONSTRAINT fk_TblStudent_UserId
    FOREIGN KEY (UserId)
        REFERENCES TblUser(Id)
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;

Problem Statement: In my PHP application, I need to check and add a Student with the Registration Id in the System – in the tables as follows.

  1. First add an entry in the TblUser (both UserId and Password will be the same as that Registration Id initially, later it will be changed) — PASS
  2. Create a Student Role for the user in the TblUserRole table — PASS
  3. Create an entry in the TblStudent with the rest of the attributes like Age, Gender, Department ,Year etc., — FAIL

I do it all in one flow from from the PHP Script acts a Controller to the DAO (with different methods for each Table). I use a little older of version of XAMPP (v3.2.2) on Windows 10 – FYI.

Issue: A strange scenario / issue I face is that I am able to successfully add an entry in TblUser and also in TblUserRole (where UserId is a FK), but NOT in the TblStudent, which always keep failing with the IntegrityConstraintViolation exception that says the Child/Foreign key is missing.

I have even verified and printed the value from TblUser in the middle of the flow, just to ensure the saved data was flushed by PDO to the MySQL Database. I have been struggling with this strange behavior of PHP PDO. I have also tried adding many debugging statements with the help of print_r and var_dump and all prove the values are valid.

I will really appreciate if someone throws a light on this strange behavior and the gaps if any I have in my flow of execution.

Let me know if you need any other information pertaining to the issue.

Convert a multidimensional array into a specific array pattern in PHP

I’ve been having difficulty visualizing how to return a specific array pattern from my extracted array from the spreadsheet table. You may refer to the extracted arrays below.

Here are the extracted arrays from my spreadsheet table

Array
(
    [0] => Array
        (
            [0] => Order Number
            [1] => Status
        )

    [1] => Array
        (
            [0] => 1111
            [1] => Shipped
        )

    [2] => Array
        (
            [0] => 2222
            [1] => For Veri
        )

    [3] => Array
        (
            [0] => 3333
            [1] => Delivered
        )

    [4] => Array
        (
            [0] => 4444
            [1] => Problematic
        )

    [5] => Array
        (
            [0] => 5555
            [1] => Onhold
        )

)

I would like for the array to be returned as below:

 Array(
      [1111] => Array
         {  
          [Order Number] => 1111
          [Status] => Delivered
          }
       [2222] => Array
         {  
          [Order Number] => 2222
          [Status] => Delivered
          }
     )

Would like to confirm if the array_combine function would work on this? Any help would be greatly appreciated.

Thanks!

Errors in prepared statement

I get the following error

Notice: Undefined variable: prepared_stmt in “// Fetch the result”

My code is:

    // The prepared statement
    $sql = $pdo->query('SELECT * FROM table1 WHERE answer LIKE :answer');
    while ($row = $sql->fetch())
    {
        echo $row['name'] . "n";
    }

    // Prepare, bind, and execute the query
    $prepared_stmt->bind_param(':answer', $searchString);
    $prepared_stmt->execute();

    // Fetch the result
    $result = $prepared_stmt->get_result();

    if ($result->num_rows === 0) {
        // No match found
        echo "No match found";
        // Kill the script
        exit();

    } else {
        // Process the result(s)
        while ($row = $result->fetch_assoc()) {
            echo "<b>Qn Number</b>: ". $row['qnumber'] . "<br />";
            echo "<b>Question</b>: ". $row['questionr'] . "<br />";

        } // end of while loop
    } // end of if($result->num_rows)

Could someone help me out?

video is uploaded to the sever but not into the database

Hey guys im trying to upload videos on my website but some videos work mostly small videos but when uploading large videos it will upload it but it wont insert it into the db any idea why?

    if(isset($_POST["Upload-Video"])) {
        $getID3 = new getID3;
        $target_dir = "category/videos-images/";
        
        $video_name = $_POST["title"];
        $video_description = $_POST["description"];
        $video_category_id = $_POST["category"];
        $video_md5_name = convert_file_name("image");
        $video_duration = get_file_duration("image", $getID3);
        
        empty_file_inputs($video_name, $video_description, $_FILES, $video_category_id);
        
        if(file_exists("$target_dir/$video_md5_name")) {
            die(header("location: ../admin.php?error=file exists"));
        } else {
            insert_video_to_database($conn, $video_name, $video_description, $video_duration, $video_md5_name, $video_category_id);
            move_uploaded_file($_FILES["image"]["tmp_name"],"$target_dir/$video_md5_name");
            wait_file_upload($target_dir, $video_md5_name);
            echo "Uploaded.";
           }

    } 

the insert_video_to_database() works fine if i use small video but for some reasons if i use a large video it will upload it to the videos folder but not insert it into the db why is that? i tried adding the insert before the upload and after the upload didnt work i have no idea why

Basic Php Array in html table

I was doing a simple php array table, but the result of my code is not what I’ve expected,

<?php 
    $names = array (
        'First Name' => 
            array('Alfre', 'Beka', 'Charlie'),
        'Middle Name' =>
            array('Brom', 'Tiv', 'Clore'),
        'Last Name' =>
            array('Adani', 'Filial', 'Chrome'),
    );
    
    echo '<table border="1">';
    foreach($names as $name => $indv_name) {
                echo '<tr>';
                echo "<th>$name</th>";
                foreach($indv_name as $per_name) {
                    echo '<td>',$song, '</td>';
                }
                echo '</tr>';
            }
    echo '</table>';
    ?>

The result of the array of this code is echoed horizontally, can anyone help me to echo it in a vertical way?

WordPress category of CPT pagination page 2 ERROR

I got problem of my pagination in category pages >>
I made a category taxonomy for my CPT and when I add posts and posts goes to page 2 .. the page 2 got a ERROR not found


 <?php 
                  //==== Query Dynamic Options ====//
              
                  $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
                  $args = array(
                    'post_type' => 'portfolio',
                    'post_status' => 'publish',
                    'posts_per_page' => 9,
                    'paged' => $paged,
                    'order' => 'DESC',
                    'orderby' => 'ID',
                    'taxonomies' => 'portfolio-categories'
           
                );
                $the_query = new WP_Query( $args );
            ```
 if you wanna see more code that will helps u to help me ask it for me I will capture it